簡體   English   中英

ASP.NET MVC 6文件夾授權

[英]ASP.NET MVC 6 folder authorization

我正在ASP.NET MVC 6中准備應用程序。此應用程序有一個文件夾,其中包含一些用於管理目的的靜態文件。 我想限制對具有特定角色的用戶訪問此內容。

在MVC 6之前,有可能創建一個web.config文件並將其放在這個受限制的文件夾中(例如: asp.net文件夾授權 )。

vNext中是否有類似的方法?

如果您在IIS中托管它,您仍然可以以相同的方式在文件夾上設置安全性。

您可以關注Scott Allen的博客文章,其中介紹了如何使用某些中間件執行此操作:

// 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());
    });
}

ProtectFolder類是中間件本身。 中間件對象上的Invoke方法是可注入的,因此我們將要求當前的授權服務,並在當前請求朝向受保護的文件夾時使用該服務來授權用戶。 如果授權失敗,我們使用身份驗證管理器來挑戰用戶,這通常會將瀏覽器重定向到登錄頁面,具體取決於應用程序的身份驗證選項。

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);
    }
}

回到應用程序的Startup類,我們將配置新的中間件以使用“Authenticated”策略保護/ secret目錄。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM