c# - 登录时添加声明
问题描述
我在 .NET Core 2.2 中为新的身份验证而苦苦挣扎的日子我有:
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] 检查。每次我输入此方法时,都不再设置索赔。
我想避免搜索索赔的耗时过程。有没有更安全的方法可以为会话添加一次?
干杯,
解决方案
推荐阅读
- android - 使用部署和上传证书签署颤振 apk
- c++ - 我可以使用字符串变量而不是名称创建容器吗?C++
- python-3.x - Keras Init Sequential 模型层按模型层
- python - 如何在 django 中自定义 {% bootstrap_form form %}?
- javascript - 如何在 React Native 中切换状态
- opentracing - Jaeger 服务未显示在 Jaeger UI 中
- scala - 为什么在 Akka Streams 中添加异步边界会消耗大量 CPU?
- python - Eclipse PyDev 忽略 __init__,导致未解决的模块导入错误
- laravel - @Laravel 迁移:无法在 laravel 中添加外键约束
- python - 外部连接 Python 套接字服务器