2015-02-10 57 views
3

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

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

vNext中有類似的方法嗎?

+0

'在MVC 6之前有可能創建一個web.config文件並將它放在這個受限制的文件夾中'你有沒有試過這個?這應該仍然有效(您可能需要啓用「通過ASP.NET路由靜態文件」)... – ChrFin 2015-02-10 15:05:26

+3

在發佈堆棧溢出問題之前總是比較容易嘗試。省卻尷尬。 – BenjaminPaul 2015-02-10 15:08:23

+1

是不是它在vNext中過時了web.config? 「添加新項目」嚮導中沒有這樣的模板。 – azachert 2015-02-17 13:53:31

回答

2

您可以按照Scott Allen's博客文章展示瞭如何使用一些中間件來做到這一點:

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

,我們將配置新的中間件來保護/祕密目錄中的「身份驗證」的政策。

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 
} 
2

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