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

核能气质少年 提交于 2019-11-30 13:43:17
Dalorzo

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

H.Wolper

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