I have an application developed in .net vb and SQLServer, I want to restrict files js to be available to logged in users, but otherwise return a 403 error or similar. For example a user should be able to media/js/controller/myController.js
only if they're logged in.
I know how to control the actual displaying of the files aspx, ashx and ascx if they're not logged in, but not how to block access to the js file if they visit the link directly in their browser, for example http://www.myapp.com/media/js/controller/myController.js
. It's show my code javascript.
How can I achieve this?
UPDATE
It's my authentication mode in my web.config
<!--<authentication mode="Windows"/>-->
<authentication mode="Forms">
<forms name="AuthCookie" path="/" loginUrl="login.aspx" protection="All" timeout="2000">
<credentials passwordFormat="Clear" />
</forms>
</authentication>
<authorization>
<!--<allow roles="***" />
<deny users="*" />-->
<deny users="?" />
<allow users="*" />
</authorization>
I'm not sure why you care to restrict your JavaScript files but use this to serve the files via the controller.
public class ScriptsController : Controller
{
//option 1. Have one method for all the files.
[LoggedIn]
public ActionResult Get(string fileName)
{
return File(Server.MapPath("~/media/js/" + fileName + ".js"), "text/javascript");
}
//option 2: have a method for each file
[LoggedIn]
public ActionResult main()
{
return File(Server.MapPath("~/media/js/main.js"), "text/javascript");
}
}
In the route config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"JSFiles",
"{controller}/{fileName}",
new { controller = "Scripts", action = "Get" }
);
}
}
If you put this method in your "ScriptsController", the url would be something like http://www.myapp.com/Scripts/Get/main where main is the name of the javascript controller.
In order to prevent the direct download, you can set that in the web config or put the files in a non served location on the server. Either way. Web config would probably be better for the long term.
web config way
<location path="media">
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</location>
You should also add validation to prevent the user from serving files other than the js files you want to serve (like the web config, etc.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With