gpt4 book ai didi

asp.net-core - 使用自定义函数 .NET Core 2 覆盖 OnTokenValidated JwtBearerEvents

转载 作者:行者123 更新时间:2023-12-03 14:45:12 55 4
gpt4 key购买 nike

在我的 API 项目中,我正在使用 JwtBearer 处理身份验证(用户使用 Azure 登录)。调用 API 时,将使用定义的 Azure 实例验证 token ,这一切正常。
当 token 被成功验证时,登录用户将被插入到我们自己的数据库中,并具有适当的角色。现在处理的方式如下:

// Add authentication (Azure AD)
services
.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = this.Configuration["AzureAd:ClientId"];
options.Authority = $"{this.Configuration["AzureAd:Instance"]}{this.Configuration["AzureAd:TenantId"]}";

options.Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
// Check if the user has an OID claim
if (!context.Principal.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier"))
{
context.Fail($"The claim 'oid' is not present in the token.");
}

ClaimsPrincipal userPrincipal = context.Principal;

// Check is user exists, if not then insert the user in our own database
CheckUser cu = new CheckUser(
context.HttpContext.RequestServices.GetRequiredService<DBContext>(),
context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>(),
userPrincipal);

cu.CreateUser();

return Task.CompletedTask;
},
};
});
这工作正常,但它不是最漂亮/最正确的方法。我会说我应该使用依赖注入(inject)/覆盖 OnTokenValidated事件并整合' CheckUser ' 那里的逻辑所以 startup类保持整洁。
遗憾的是,我缺乏对 DI 的了解,我不完全确定正确处理此问题的最佳方法是什么。因此,我环顾四周,发现了一篇准确描述我的问题的帖子:
Problems handling OnTokenValidated with a delegate assigned in startup.cs
阅读这篇文章后,我尝试用自己的逻辑对其进行一些修改,最终得到以下结果:
在启动中:
services.AddScoped<UserValidation>();

services
.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = this.Configuration["AzureAd:ClientId"];
options.Authority = $"{this.Configuration["AzureAd:Instance"]}{this.Configuration["AzureAd:TenantId"]}";

options.EventsType = typeof(UserValidation);
});
自定义 JwtBearerEvents 类:
public class UserValidation : JwtBearerEvents
{
private string UserID { get; set; }

private string UserEmail { get; set; }

private string UserName { get; set; }

public override async Task TokenValidated(TokenValidatedContext context)
{
try
{
TRSContext context2 = context.HttpContext.RequestServices.GetRequiredService<TRSContext>();
UserManager<ApplicationUser> userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();

ClaimsPrincipal userPrincipal = context.Principal;

this.UserID = userPrincipal.Claims.First(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

if (userPrincipal.HasClaim(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"))
{
this.UserEmail = userPrincipal.Claims.First(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").Value;
}

if (userPrincipal.HasClaim(c => c.Type == "name"))
{
this.UserName = userPrincipal.Claims.First(c => c.Type == "name").Value;
}

var checkUser = userManager.FindByIdAsync(this.UserID).Result;
if (checkUser == null)
{
checkUser = new ApplicationUser
{
Id = this.UserID,
Email = this.UserEmail,
UserName = this.UserEmail,
};

var result = userManager.CreateAsync(checkUser).Result;

// Assign Roles
if (result.Succeeded)
{
return;
}
else
{
throw new Exception(result.Errors.First().Description);
}
}
}
catch (Exception)
{
throw;
}
}
}
然而,由于某种原因,这不起作用。没有错误和 UserValidation从未被命中(尝试设置调试点但从未命中)并且它不会插入新用户(在使用旧代码时会这样做)。
任何人都知道我在这里做错了什么,或者可能有一些更好的想法来处理这个问题?

最佳答案

如您所展示的,我建议您在启动时进行基本的 token 验证(例如权威和受众)。我建议您使用基于策略的验证来进行特定的 claim 验证。见 Policy-based authorization in ASP.NET Core
结果将是更简单、更易于维护的代码。

关于asp.net-core - 使用自定义函数 .NET Core 2 覆盖 OnTokenValidated JwtBearerEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50756478/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com