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

為{幸葍}努か 提交于 2020-01-29 04:56:06

问题


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.


回答1:


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




回答2:


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.




回答3:


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://docs.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.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!