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 my initial index.html page has been downloaded.
Is there a way I can make my server code give out the javascript files to only authenticated and authorized users? Something similar to the way a controller action method returns data to only authenticated and authorized users.
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:
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.
If you can use jQuery, there is a $.getScript
ajax function.
http://api.jquery.com/jquery.getscript/
It is an asynchronous call to the server 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
});
来源:https://stackoverflow.com/questions/23879769/how-can-i-limit-the-serving-of-a-javascript-file-to-only-authenticated-users