Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restrict access to js file if not logged in

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>
like image 899
CMedina Avatar asked Dec 10 '22 16:12

CMedina


1 Answers

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.)

like image 116
Bryan Euton Avatar answered Dec 23 '22 00:12

Bryan Euton