Asp.net-Web-Api

自定義身份驗證 asp.net core web api

  • October 5, 2017

我想用一個秘鑰(api key)授權asp.net core web api。密鑰將在授權標頭中傳遞,如下所示,

ex. Authorization keytype;h43484344343bbhfdjfdfhj34343

我想編寫一個中間件來從請求標頭中讀取此密鑰並呼叫內部 api 來驗證密鑰。

在 web api 中,我們可以編寫一個消息處理程序來執行此操作,但我是 asp.net 核心的新手。我看到了很多範例,但它們使用的是內置的 JWT 令牌身份驗證。但我想使用我自己的密鑰,我解密這個密鑰並根據數據庫條目進行驗證。

誰能建議一些關於如何執行此操作的程式碼範例?

我在使用 asp core 1.1 的解決方案中使用了這種方法。首先定義一個自定義方案:

public static class Authentication
{
   public const string Scheme = "Custom";
}

然後你必須繼承AuthenticationHandler<TOptions>. 這是驗證標頭值的邏輯所在:

public class MyAuthenticationHandler : AuthenticationHandler<MyOptions>
{
   protected override Task<AuthenticateResult> HandleAuthenticateAsync()
   {
       var authorizationHeader = Context.Request.Headers["Authorization"];
       if (!authorizationHeader.Any())
           return Task.FromResult(AuthenticateResult.Skip());

       var value = authorizationHeader.ToString();
       if (string.IsNullOrWhiteSpace(value))
           return Task.FromResult(AuthenticateResult.Skip());

       // place logic here to validate the header value (decrypt, call db etc)

       var claims = new[]
       {
           new Claim(System.Security.Claims.ClaimTypes.Name, "Bob")
       };

       // create a new claims identity and return an AuthenticationTicket 
       // with the correct scheme
       var claimsIdentity = new ClaimsIdentity(claims, Authentication.Scheme);

       var ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties(), Authentication.Scheme);

       return Task.FromResult(AuthenticateResult.Success(ticket));
   }
}

為了繼承AuthenticationHandler,您必須創建一個選項類,在其中將AuthenticationScheme-property 設置為您正在使用的方案:

public class MyOptions : AuthenticationOptions
{
   AuthenticationScheme = Authentication.Scheme;
}

在此之後,您必須繼承AuthenticationMiddleware<TOptions>. 這將創建您在上一步中實現的處理程序:

public class MyAuthenticationMiddleware : AuthenticationMiddleware<MyOptions>
{
   public MyAuthenticationMiddleware(RequestDelegate next, IOptions<MyOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder) : base(next, options, loggerFactory, encoder)
   {
   }

   protected override AuthenticationHandler<MyOptions> CreateHandler()
   {
       return new MyAuthenticationHandler();
   }
}

為了輕鬆插入中間件,您可以定義以下擴展方法:

public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder app, IConfigurationSection config)
{
   return app.UseMyAuthentication(options => {});
}

private static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder app, Action<MyOptions> configure)
{
   var options = new MyOptions();
   configure?.Invoke(options);

   return app.UseMiddleware<MyAuthenticationMiddleware>(new OptionsWrapper<MyOptions>(options));
}

然後在您的Startup班級中,您終於可以添加中間件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMyAuthentication(Configuration.GetSection("MyAuthenticationOptions"));

   // other stuff

   app.UseMvc();
}

然後AuthorizeAttribute在您的操作中添加指定您剛剛創建的方案:

[Authorize(ActiveAuthenticationSchemes = Authentication.Scheme)]
public IActionResult Get()
{
   // stuff ...
}

有很多步驟,但希望這會讓你繼續前進!

引用自:https://stackoverflow.com/questions/46556225