请求我帮助实现向经过身份验证的用户分配声明的自定义方式.成功登录后,
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
//Get the user
ApplicationUser user = UserManager.FindByEmail(model.Email);
//Ends here
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
Run Code Online (Sandbox Code Playgroud)
我使用userId从数据存储区中获取有关用户的角色和其他信息.此后,我需要在重定向到用户仪表板之前,使用电子邮件,角色,名字,姓氏,性别等信息添加有关用户的声明.这是我尝试这样做的方式,但问题是即使在登录方法添加声明后,我也无法在_loginPartial剃刀视图中检索它
例如,当我想在登录部分显示电子邮件索赔值时,就像这样
var claims = ClaimsPrincipal.Current.Claims;
var principal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = principal.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
它返回null.
因此,我只能在添加它们后使用相同的登录方法访问它们,但我需要能够从应用程序的任何位置访问它们.如果能够在整个申请中的任何其他地方检索这些声明,我将非常感谢.
谢谢.
到处都抬头,但看起来我现在被困住了。我在应用程序中使用Windows Active Directory进行身份验证。为了获得授权,我使用索赔。在搜索了有限的.net核心文档之后,这就是我的代码的样子。
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPrincipal>(
provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
Run Code Online (Sandbox Code Playgroud)
ClaimsTransformer.cs
class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
// call to database to get more claims based on user id ClaimsIdentity.Name
((ClaimsIdentity)principal.Identity).AddClaim(new Claim("now",DateTime.Now.ToString()));
return Task.FromResult(principal);
}
}
Run Code Online (Sandbox Code Playgroud)
但是问题是,每次请求都会调用此代码,并且每次都会从db加载声明,这是绝对错误的。有什么办法可以缓存它?我能够创建声明的cookie并将该cookie用于.net 4.0中的任何其他调用。我似乎找不到核心的方法。我检查的所有文档都不完整,或者不涵盖我的情况。我可以在应用程序中进一步声明文档在这里的说法:https : //docs.microsoft.com/zh-cn/aspnet/core/security/authorization/claims
但是没有提到有关缓存索赔的内容。
有人在同一条船上吗?还是知道出路?