public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = $"/api{CookieAuthenticationDefaults.LoginPath}";
options.LogoutPath = $"/api{CookieAuthenticationDefaults.LogoutPath}";
options.EventsType = typeof(MyEvents);
});
services.AddScoped<MyEvents>();
}
public class MyEvents : CookieAuthenticationEvents
{
public async override Task SignedIn(CookieSignedInContext context)
{
// do some checks
// add cookie to CookieManager >> WORKS WELL
// add claims to Principal >> NOT WORKING
if (error)
{ await context.HttpContext.SignOutAsync(scheme); context.Principal = null ; }
}
public async override Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
// idea here is to check if claims are already set, if not add them
if (context.Principal.HasClaim(c => c.Type == ClaimTypes.NameIdentifier))
return;
// time consuming claims search
// add claims here : WORKS but only for this instance
}
问题
在SignedIn中添加声明绝对没有任何作用,当返回调用方法时,声明未设置。
在ValidatePrincipal中添加声明仅适用于当前的[Authorize]检查。每次我输入此方法时,声明就不再设置。
我想避免搜索索赔的耗时过程。有没有一种安全的方法可以为会话添加一次?
干杯