How can I limit the serving of a javascript file to only authenticated users?

If you host your site in IIS you can configure the IIS to serve *.js files via the .Net framework. Then you'll need to create an HTTPHandler to serve these files (checking if the user is authenticated within the HTTPHandler's code).

If you aren't sure where to start, you can read Combine, minify and compress JavaScript files to load ASP.NET pages faster or some similar article. Although the purpose there is different, it does explain how to serve js files via ASP .Net. You'll just add your authentication checks to the HTTPHandler.

Update: Here is an explanation how to setup IIS for this. Just make sure you know which version of IIS you have.


You can force the static files to go through the server in order to ensure authentication by setting it up on the web.config:

Web.config

<compilation>
    <buildProviders>
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider" />
        <add extension=".htm" type="System.Web.Compilation.PageBuildProvider" />
         <add extension=".js" type="System.Web.Compilation.ForceCopyBuildProvider"/>
    </buildProviders>
</compilation>

<system.webServer>
     <handlers>
         <add name="HTML" path="*.html" verb="GET, HEAD, POST, DEBUG"   type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" requireAccess="Script" />
         <add name="HTM" path="*.htm" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" requireAccess="Script" />
     </handlers>
</system.webServer>

This will allow me to set up <authorization> in my web.config for the locations I want, like:

Location: scripts/secured/demo

<authorization>
  <allow roles="demo" />
</authorization>

or Location: scripts/secured/

 <authorization>
   <deny users="?" />
 </authorization>

http://msdn.microsoft.com/en-us/library/h0e51sw9(v=vs.85).aspx

A similar question was recently if it helps:

Secure angular app access and Web API Service


Another Option: Serve your js from webapi!

This is surely not the best performing way to do it, but it works great, gives you a lot of control, is super easy to wrap your brain around, and requires no IIS or config file changes. I do this on WebAPI2 in several ASP.Net projects - YMMV.

(Another thing that gets tricky is if you want your authentication mechanism to be by a Bearer token in the request header - that's pretty much impossible unless you download the javascript via ajax, and then add it to the document ... or put the token in the querystring - which would be weird as you'd have to render the script tag with the token. This really works best with cookie-based authentication. )

  1. Load your JS file(s) into a static variable(s) on the API controller
  2. Make sure Attribute Routing is turned on for WebAPI (https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2)
  3. Create an endpoint for your javascript file(s) with a route like:
[Route("api/system/GlobalConstants.js")]
public HttpResponseMessage GlobalConstantJS()
{
    var resp = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(MY_STATIC_STRING_WITH_THE_JS_TEXT)
    };
    return resp;
}
  1. Make sure your API controller is secured with the Authorize attribute :)
  2. Use a plain-old regular script element, pointing to the route:
 <script src="~/api/system/GlobalConstants.js" type="text/javascript"></script>

...obviously this has the additional advantage of being able to serve dynamically generated javascript files - if you so choose.