asp.net core control authorization static files

 Static files in a site visit is an important service to provide direct access to the front end of the file, such as js, css, documents, etc., is to add UseStaticFiles () pipeline in the Configure Startup in.

Reference: ASP.NET Core Static file

 But if I want my documents are also authorized to access, and not just a request will be able to download, how to do it?

  Let me talk about my environment, authentication services using a identityserver4. Api access by adding bearer token pass authentication information in HttpHeader in.

  I think there are two methods:

  1) First, the file is accessed by the API returns to the front end, so that we can add in the API [the Authorize] tab to control access to the file. Probably something like the following code

  

    [Authorize] 
  public IActionResult BannerImage()
  {
    var file = Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles", "images", "banner1.svg");   
    return PhysicalFile(file, "image/svg+xml");
  }

    This way there will be two issues, first it is my project token presence localStore information is then added to the HttpHeader when they access the api, if you type the access path directly in the browser, or open the link in a tab, then request It will be rejected out. then what should we do? Solution I consider is the token in a cookie so the server through

Take the token cookie information, and this is the default mode asp.net core. I have not tried this method, be it from experience.

         Another problem is the interview I was asked the interviewer, to the effect that a program like this, then we have to first read the file stream back to the front, so that when memory pressure requests more time the program is not big yet? The moment I can not answer this question, because I feel a little sense. But I then I think even if the pressure is transferred to the IIS, IIS is the same file to read it, do not know there is no IIS

There's optimized for accessing static files. And other free and then measuring about two of the performance difference.

2) The second method is what I am using, can solve the problem browser type or a tag access, but also less than cookie. The idea is simply put into the token information request link, and then deal with token information in the background before accessing static files to the directory authorization and authentication into the pipeline.

   Here is the code, I suppose static directory to be accessed is "Storage".

   First, the process token information in the link:

// In the Startup configuration service, only the key codes listed here    
services.AddAuthentication (Options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer (Options => { options.Events = new new JwtBearerEvents { OnMessageReceived = context => { var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(path) && (path.StartsWithSegments("/Storage"))) { var accessToken = context.Request.Query["access_token"]; context.Token = accessToken; //把token信息设置到上下文中 } return Task.CompletedTask; } }; });

Configure disposed in the conduit

     app.UseAuthentication (); 
     app.UseAuthorization (); 
         
     app.UseMiddleware <AuthorizeStaticFilesMiddleware> (); 
     app.UseFileServer ( new new FileServerOptions // note static file and the authorization to write back pipe seriously 
     {
           RequestPath = " / Storage " , 
          FileProvider = new new PhysicalFileProvider ( "your direcotry path"),
       });
             

Written authorization judgment pipe file

public class AuthorizeStaticFilesMiddleware
    {
        RequestDelegate _next; 
        public AuthorizeStaticFilesMiddleware(RequestDelegate next )
        {
            this._next = next; 
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/storage"))
            {
                if (context.User.Identity.IsAuthenticated)  //判断用户是否认真
                {  
                        await this._next(context); 
                }
                else
                {
                    await context.ForbidAsync();
                }
            }
            else
            {
                await this._next(context);
            } 
        }
    }

The above is a License Rights static files.

 

Guess you like

Origin www.cnblogs.com/jidanfan/p/11909027.html