简体   繁体   中英

Blazor (server side) authentication and static files

As per Microsoft's recommendation, I am using a custom AuthenticationStateProvider service for handling authentication/authorization for a Blazor server page.

It all works fine within razor components, where I can use the [Authorize] attribute or the AuthorizeView/Authorized/NotAuthorized tags.

Now, I wanted to serve static files outside the wwwroot folder but have control if the user is authenticated or not in order to serve the files.

Is there a way to control access to static files served outside the wwwroot folder?

What I found is something similar to (in program or startup):

app.UseStaticFiles(new StaticFileOptions
{    
    OnPrepareResponse = (context) =>
    {        
        if (context.Context.Request.Path.StartsWithSegments("/MyRequestPath"))
        {
            context.Context.Response.Headers.Add("Cache-Control", "no-store");

            if (!context.Context.User.Identity.IsAuthenticated)
            {
                context.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Context.Response.ContentLength = 0;
                context.Context.Response.Body = Stream.Null;
            }
        }
    },
    FileProvider = new PhysicalFileProvider("PathToMyFilesOutsidewwwroot"),
    RequestPath = "/RequestPath"
    });

The problem with that is that is uses Context.User.Identity.IsAuthenticated, ie, it uses HTTPContext, which is not available within a Blazor page (and that is why we have to use AuthenticationStateProvider).

I'd like to stick to just using Blazor best practices, and not try to circumvent it via scaffoldding, javascript, or whatever.

Thanks in advance.

In the end I sticked to using the app.UseStaticFiles... approach, but in order to make it work I had to add authentication via cookies (outside of Blazor). Inside of Blazor I still use AuthenticationStateProvider, so the only thing that I had to take care is to authenticate via cookies and AuthenticationStateProvider at the same time when a user logs in. I suppose it makes sense, because authentication via cookies (prior to entering the Blazor "environment") gives me also the chance to call controllers or other pages out the razor components while still being authenticated (via cookies).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM