[英]check user validation in Asp.net core with jwt authorization
我在我的 web api 中實現了 Microsoft Identity 和 JWT,客戶端可以登錄並獲取 JWT 令牌並將其存儲在應用程序中。 由於令牌過期,用戶可以訪問服務器,但是如果我從我的數據庫中刪除一個用戶,被刪除的用戶仍然擁有它的令牌並且可以訪問 web api,我如何檢查用戶的驗證?
一種選擇是在 JwtBearerEvent OnTokenValidated 事件上驗證當前用戶,該事件將在每次成功認證后觸發
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = ServiceProvider.GetService<IUserService>();
if(userService.IsUserRemoved(context.Principal.Identity.Name))
context.Fail("User is removed");
return Task.CompletedTask;
}
};
});
注意:在本例中,我使用 ServiceProvider 來獲取 IUserService 的一個實例,該實例作為參數存儲在 Startup.cs 類中。 初始化為ServiceProvider = services.BuildServiceProvider();
在 ConfigureServices 方法中。 IUserService 是一個包裝類,您需要在其中實現 IsUserRemoved 方法,該方法將對您的用戶提供程序實現進行操作。
另一種選擇是實現和注冊您自己的SecurityTokenValidator
。 為此,您需要創建一個實現ISecurityTokenValidator
接口的類:
//using Microsoft.IdentityModel.Tokens
public class CustomValidator : ISecurityTokenValidator
{
//interface implementation
...
}
並通過JwtBearerOptions.SecurityTokenValidators
屬性將其注冊為額外的令牌驗證器:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer( options => {
options.SecurityTokenValidators.Add(new CustomValidator())
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.