3

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?

4
  • Before MVC 6 there was a possibility to create a web.config file and place it in this restricted folder have you tried exactly that? This should still work (you possibly need to enable "route static files via ASP.NET")... Commented Feb 10, 2015 at 15:05
  • 3
    Always easier to try before posting a Stack Overflow question. Saves embarrassment. Commented Feb 10, 2015 at 15:08
  • 1
    Isn't it web.config obsolete in vNext? There is no such template in "Add New Item" wizard. Commented Feb 17, 2015 at 13:53
  • @azachert You will see lots of people say you don't need web.config but if you are using IIS (Most people are), then you still need web.config it to configure IIS. Those people are spreading half-truths. Commented Oct 15, 2015 at 9:21

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you're hosting it in IIS, you can still set security on the folder the same way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.