2017-08-03 59 views
2
[HttpGet] 
public IActionResult Get() 
{ 
    string token = Request.Headers["Authorization"]; 
    // Validate token. 
} 

[HttpPost] 
public IActionResult Post(int id) 
{ 
    string token = Request.Headers["Authorization"]; 
    // Validate token. 
} 

如何驗證所有控制器在一個地方的Request.Headers [「授權」]?如何驗證一個地方的所有控制器的Request.Headers [「授權」]?

+2

https://damienbod.com/2015/09/15/asp-net-5-action-filters/ – Hackerman

+0

它們是什麼樣的標記?有很多現有的基礎設施來做到這一點。以JwtBearer爲例。 – Tratcher

+0

我現在只需在一個地方閱讀和驗證標題。但是,我會讀到JwtBearer要知道,thx。 –

回答

4

您可以創建並使用自定義中間件,您可以在其中檢查標題並驗證它是否應傳遞給控制器​​。

爲了更好地實現創造中間件類,並在Startup.cs regiester它如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConnectionManager conn, ILoggerFactory loggerFactory) 
{ 
      app.UseMiddleware<YourMidllewareClass>(); 
} 

創建中間件類中調用方法。這個方法會在每個請求跳轉到你的控制器之前被調用。

public async Task Invoke(HttpContext context) 
     { 
      string token = Request.Headers["Authorization"]; 
      //do the checking 

      //pass request further if correct 
      await _next(context); 
     } 

至於我的rember必須regiester前UseMvc()方法,中間件,以確保您的invoke()將管道的mvc之前調用。

1

對於ASP.NET Core 2.0,有些事情已經改變,您也可以使用AuthenticationHandler。
幫助您入門的好文檔是https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

我用我的當前項目自定義身份驗證的一個例子:

Startup.ConfigureServices:

 services.AddAuthentication(options => 
     { 
      options.DefaultAuthenticateScheme = "Custom Scheme"; 
      options.DefaultChallengeScheme = "Custom Scheme"; 
     }).AddCustomAuth(o => { }); 

Startup.Configure:

 app.UseAuthentication(); 

最後:

internal class CustomAuthenticationHandler : 
    AuthenticationHandler<CustomAuthenticationOptions> 
{ 
    public CustomAuthenticationHandler(IOptionsMonitor<CustomAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : 
     base(options, logger, encoder, clock) 
    { 
    } 

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync() 
    { 
     try 
     { 
      // Your auth code here 
      // Followed by something like this: 
       return AuthenticateResult.Success(
        new AuthenticationTicket(
         new ClaimsPrincipal(
          new ClaimsIdentity(
           new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) }, 
           Scheme.Name)), 
         Scheme.Name)); 
     }   
     catch 
     { 
      return AuthenticateResult.Fail("Error message."); 
     } 
    } 
} 

這樣,所有對您的控制器的調用都將通過身份驗證中間件,並且您可以通過在控制器上使用[AllowAnonymous]屬性(如有必要)忽略它。

相關問題