Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 6 folder authorization

I'm preparing application in ASP.NET MVC 6. This application has a folder with some static files for administration purposes. I would like to restrict access to this content to users with specific role.

Before MVC 6 there was a possibility to create a web.config file and place it in this restricted folder (example: asp.net folder authorization).

Is similar approach available in vNext?

like image 399
azachert Avatar asked Dec 03 '25 15:12

azachert


1 Answers

You can follow Scott Allen's blog post which shows how to do this using some middleware:

// First, in the Startup class for the application, we will add the required services. 
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
    });
}

The ProtectFolder class is the middleware itself. The Invoke method on a middleware object is injectable, so we’ll ask for the current authorization service and use the service to authorize the user if the current request is heading towards a protected folder. If authorization fails we use the authentication manager to challenge the user, which typically redirects the browser to a login page, depending on the authentication options of the application.

public class ProtectFolderOptions
{
    public PathString Path { get; set; }
    public string PolicyName { get; set; }
}

public static class ProtectFolderExtensions
{
    public static IApplicationBuilder UseProtectFolder(
        this IApplicationBuilder builder, 
        ProtectFolderOptions options)
    {
        return builder.UseMiddleware<ProtectFolder>(options);
    }
}

public class ProtectFolder
{
    private readonly RequestDelegate _next;
    private readonly PathString _path;
    private readonly string _policyName;

    public ProtectFolder(RequestDelegate next, ProtectFolderOptions options)
    {
        _next = next;
        _path = options.Path;
        _policyName = options.PolicyName;
    }

    public async Task Invoke(HttpContext httpContext, 
                             IAuthorizationService authorizationService)
    {
        if(httpContext.Request.Path.StartsWithSegments(_path))
        {
            var authorized = await authorizationService.AuthorizeAsync(
                                httpContext.User, null, _policyName);
            if (!authorized)
            {
                await httpContext.Authentication.ChallengeAsync();
                return;
            }
        }

        await _next(httpContext);
    }
}

Back in the application’s Startup class, we’ll configure the new middleware to protect the /secret directory with the “Authenticated” policy.

public void Configure(IApplicationBuilder app)
{
    app.UseCookieAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
    });

    // This must be before UseStaticFiles.
    app.UseProtectFolder(new ProtectFolderOptions
    {
        Path = "/Secret",
        PolicyName = "Authenticated"
    });

    app.UseStaticFiles();

    // ... more middleware
}
like image 159
Muhammad Rehan Saeed Avatar answered Dec 05 '25 15:12

Muhammad Rehan Saeed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!