How can I restrict javascript file submission to authenticated users only?

I have a WebAPI 2 / AngularJS SPA application that uses Identity 2 for authentication. Locally, my code stores a token for authentication. I would like to implement functionality that allows my application to request additional javascript for authenticated users after loading the index.html start page.

Is there a way to make the server code issue javascript files only for authorized and authorized users? Something similar to how the controller action method returns data only to authorized and authorized users.

+8
asp.net-mvc asp.net-web-api asp.net-mvc-5 asp.net-web-api2
source share
3 answers

You can force static files to go through the server to provide authentication by setting it to 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 configure <authorization> in my web.config for the locations I want, for example:

Location: scripts / protected / demo

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

or Location: scripts / secure /

  <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 access to angular applications and the web API service

+4
source share

If you host your site in IIS, you can configure IIS to serve * .js files through the .Net infrastructure. Then you will need to create an HTTPHandler to serve these files (user authentication in the HTTPHandler code).

If you don’t know where to start, you can read Combine, reduce and compress JavaScript files to load ASP.NET pages or some similar articles faster . Although the goal there is different, it explains how to serve js files through ASP.Net. You simply add authentication to the HTTPHandler.

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

+3
source share

If you can use jQuery, there is a $.getScript ajax function. http://api.jquery.com/jquery.getscript/

This is an asynchronous server call to load a javascript file. But on the server side, if the user is not currently authenticated by the server, return null.

 $.getScript('url', function(data) { // check if data is null, if yes, means the user needs to be authenticated still }); 
-2
source share

All Articles