Asp.net-Core

根據 ASP.NET Core 請求標頭中提供的 API 密鑰授權使用者

  • April 2, 2018

我正在嘗試重寫我目前在 ASP.NET Core 中對 ASP.NET 4.6 的一些授權。

我知道授權發生了一些變化,我發現很難在 ASP.NET Core 中實現我非常簡單的身份驗證策略。

我的要求:

對伺服器的每個請求都應包含一個名為“key”的標頭。根據該鍵的值,我將能夠查詢數據庫並檢查該鍵是代表普通使用者還是管理員使用者。如果請求不包含有效密鑰,則該請求未被授權。

我將如何在 ASP.NET Core 中實現這一點?我發現的每個範例似乎都完全超出了我的需求。

在 ASP.NET 4.6 中,我使用自己的自定義 AuthorizeAttributes 在我的控制器上使用,例如

[User]
public IHttpActionResult DoSomethingOnlyUsersCanDo() {}

[Admin]
public IHttpActionResult DoSomethingOnlyAdminsCanDo() {}

我可以在 ASP.NET Core 中做同樣的事情嗎?

在 ASP.NET Core 中,建議不要從 AuthorizeAttribute 繼承。相反,您可以製定自定義授權策略:https ://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims 。

您將需要一個身份驗證處理程序,該處理程序根據標頭為使用者創建 ClaimsIdentity。然後,您可以製定策略來斷言使用者存在某些聲明。

您可以在此處找到基本身份驗證的實現:https ://github.com/blowdart/idunno.Authentication 。當然請注意巴里的評論:

它旨在展示如何編寫身份驗證中間件,而不是您會認真考慮使用的東西。

它的核心在BasicAuthenticationHandler中,它繼承自AuthenticationHandler<BasicAuthenticationOptions>.

此實現中的主體是在開發人員製作的事件回調中創建的,在範例中它位於此處

if (context.Username == context.Password)
{
   var claims = new[]
   {
       new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
       new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
   };

   context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
   context.Success();
}

然後在基於主體呼叫此回調後在處理程序中創建身份驗證票證:

var ticket = new AuthenticationTicket(validateCredentialsContext.Principal, Scheme.Name);
return AuthenticateResult.Success(ticket);

我還寫了一篇關於實現自定義身份驗證方案的文章:在 ASP.NET Core 2.0 中創建身份驗證方案

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