我在 Cookie ASP.NET Core 中使用 OIDC 中间件。这工作得很好。现在,我需要将自己的声明添加到 Context.User's Claims 中。我试过这个:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["Authentication:AzureAd:ClientId"],
ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"],
Authority = Configuration["Authentication:AzureAd:Authority"],
ResponseType = Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectResponseType.CodeIdToken,
PostLogoutRedirectUri = "/signed-out",
Events = new OpenIdConnectEvents()
{
OnAuthorizationCodeReceived = async context =>
{
// Trying to add my claims here...
// This must be wrong obviously
context.HttpContext.User.AddIdentity(new ClaimsIdentity(new List<Claim>() { new Claim(ClaimTypes.Role, "admin") }));
}
}
});
基本上,我想挂接OnAuthorizationCodeReceived
事件并添加声明。但这似乎不起作用,因为在进一步的请求中,添加的身份不在上下文的用户上。我该怎么做?
您可以改用 OnTokenValidated
事件。