Block direct access to js, css file but allow access from index.html?
My tips are easily bypassed, but without be careful, we can be trapped.
Only live view of the page
You can replace or remove script tag with javascript for hide this in live view of the page. But if you watch directly the network, you can see easily the javascript file/code.
<div id="RemoveMe0">
<script type="text/javascript">
//This code it is hidden to live view.
var my_var = 5 + 5;
$('#RemoveMe0').remove();
//or document.getElementById("RemoveMe0").innerHTML = "";
</script>
</div>
For include javascript :
<div id="RemoveMe1">
<script type="text/javascript" src="Javascript/MyJS.js"></script>
<script>
//Your include it is hidden to live view.
$('#RemoveMe1').remove();
</script>
</div>
Only direct view
Put your files in an HTML file (myfile.js to myfile.html), like this on a direct view you can execute a javascript function.
function Hello() {
alert("Hello");
}
Hello();
//<script>document.body.innerHTML = "";</script>
Or if you don't want to rename your file, you can to use .htaccess file to modify file header.
AddType text/html .js
Or minize/parse your JS
You can use tool like this :
- minize your js : This tool use eval function, and try to complicate your script.
- Javascript Obfuscator : Complicates the code for beginners, it's easy to by-pass.
- Google Closure JS Compiler : Optimize, compress, and minify your code. It is a natural tool for the production environment.
- Javascript to Asm.js
Block direct access to file css and javascript
It sounds like you want to set CORS policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
How can I block direct access to my JavaScript files?
Can't you just use an .htaccess file inside doc_root/scripts
to prevent all access over the web to .js
files over HTTP?
It won't stop minify, since that provides indirect access.
So in doc_root/scripts/.htaccess
, something along the lines of
<Files ~ "\.js$">
order allow,deny
deny from all
</Files>
Note that the location of the .htaccess
file matters in this case.
How can I hide direct access to my javascript files?
I opted to just pursue the $_SESSION
/$_GET
/$_POST
-gated script I had started before visiting StackOverflow.
The solution's not perfect, but it suits my needs, in that the scripts are accessible via my tags, but inaccessible directly. This is a simplified version of what I am doing:
File 1 is the PHP file generating the HTML page the user sees. This file creates a random value, and sets the value to the session. The script file File 2 is included using this random value as a GET parameter.
File 1:
<?php
session_start();
$gate['first_gate'] = crypt((time() * md_rand()) . 'salt');
$gate['second_gate'] = null;
$_SESSION['gate'] = json_encode($gate);
?>
<html>
...
<!--this is just the HTML page including the script-->
<script src="file_2.php?gate=<?=base64_encode(json_encode($gate))?>"></script>
...
</html>
File 2 is the PHP file functioning as a gate for the actual JavaScript code. It verifies that the randomized session variable is equal to the GET parameter, then grabs the code from File 3 using a POST request.
File 2:
<?php
$session_gate = json_decode($_SESSION['gate']);
$get_gate = json_decode(base64_decode($_GET['gate']));
//Exit if the session value != the get value
if($get_gate->first_gate != $session_gate->first_gate) exit;
//Set first gate to null to prevent re-visit
$session_gate->first_gate = null;
$session_gate->second_gate = crypt((time() * md_rand()) . 'salt');
$_SESSION['gate'] = json_encode($session_gate);
header('Content-Type: application/javascript');
?>
//This is visible via "view source" (then clicking on the script's URL)
//Grab the actual JS file, hidden behind a POST "wall"
$.post("file_3.php", { gate: '<?=base64_encode($_SESSION['gate'])?>' });
File 3 is inaccessible when directly viewing the page, as it exits without the POST data from File 2. Bots will still be able to ping it with a POST request, so some additional safety measures should be added here.
File 3:
<?php
$session_gate = json_decode($_SESSION['gate']);
$post_gate = json_decode(base64_decode($_POST['gate']));
//Exit without a POST request. Use a more specific value, other than
//the $_POST superglobal by itself (just using $_POST for illustrative purposes)
if(!$_POST) exit; //or print an error message
//Exit if the session value != the get value
if($get_gate->second_gate != $session_gate->second_gate) exit;
//Set both gates to null to prevent re-visit
$session_gate->first_gate = null;
$session_gate->second_gate = null;
$_SESSION['gate'] = json_encode($session_gate);
//Additional safety measures (such as IP address/HOST check) here, if desired
header('Content-Type: application/javascript');
?>
//Javascript code here
block direct access to file but allow access through jquerys load function
Please follow below steps to achieve:
- In the
.load
function of jquery post a security code. - In the Feed.php page place a PHP condition if the posted
security_code
params found and match withsecurity_code
passed in the.load
then only allow to access the page otherwise restrict.
Please follow below changes in your existing code to achieve it.
JS
<?php
$_SESSION['security_code'] = randomCode();
?>
<script type="text/javascript">
$("#dock-left-container").load("feed.php", {
security_code: '<?= $_SESSION['security_code']; ?>'
}); // load feed.php into the dock-left-container div
</script>
PHP
Place php condition in the top of feed.php
if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
//Feed.php page's all the stuff will go here
}else{
echo "No direct access of this page will be allowed.";
}
Deny Direct Access to JavaScript Files in IIS Web Server
You cannot block direct access to the file. If you restrict access to the file, as you mentioned the php file will 'break' for users who don't have access to that js file.
You could however redirect users who visit the URL to the file directly:
Javascript example:
<script>
if(window.location.href.endsWith('baseView.js'))
{
window.location = 'www.google.com'
}
</script>
You may also be able to use the .htaccess file to do this, which would be much better. (although I cannot test this myself right now, I'm not sure if it would work and not be invoked through the php file)
Note: This will in no way stop users from reading the Javascript file, so I am not sure why you want to do this.
restrict access to js file if not logged in
JS files are considered static content and .NET does not handle them by default.
From MSDN:
By default, IIS processes static content itself - like HTML pages and CSS and image files - and only hands off requests to the ASP.NET runtime when a page with an extension of .aspx, .asmx, or .ashx is requested.
You can manually set the configuration to handle .js files. Keep in mind that it will add a bit overhead, because they will go through .NET's pipeline.
Add to your web.config:
<compilation>
<buildProviders>
<remove extension=".js" />
<add extension=".js" type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
</compilation>
And:
<system.webServer>
<handlers>
<add name="JS" path="*.js" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" requireAccess="Script" />
</handlers>
</system.webServer>
Now, because your web.config already has a global rule to deny unauthenticated users from .NET resources, these settings will restrict all the JS files too.
Therefore you should open the path to the public js files that you don't want to block from unauthenticated users:
<location path="public-js-folder-path">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Hope it helps. If you have any questions please tell me.
How to block direct access to html page
You can define a variable like window.parentPage = true;
in the index.html file.
In the products.html page make a check like so:
if(!window.parentPage)
{
window.location.href = "YOUR REDIRECTION PAGE"
}
Related Topics
Sending Post Requests Without Waiting for Response
Validating Base64 Encoded Images
How to Get Only Date from Datetime in Codeigniter
How to Check, If a PHP String Contains Only English Letters and Digits
Regex Optionally Match a Pattern Multiple Times
Api to Get All the Reviews and Rating from Google for Business
Php Curl Required Only to Send and Not Wait for Response
How to Remove Back Slashes from Json Output in PHP
Warning: Mysqli_Connect(): (Hy000/1049): Unknown Database in MAC Terminal Only
[Php][Mysql] How to Insert Data in 2 Tables At Same Time
How to Create Multi Level Category Hierarchy ( Category Tree ) - Codeigniter
How to Center the Text in Phpexcel Merged Cell
How to Prevent a User from Directly Accessing My HTML Page by Writing Url