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
}
Before MVC 6 there was a possibility to create a web.config file and place it in this restricted folderhave you tried exactly that? This should still work (you possibly need to enable "route static files via ASP.NET")...