我正在使用Azure Active Directory的Adal,我需要通过自定义OwinMiddleware添加额外的声明。当我向这个主体添加声明时,我可以在当前请求中访问它们。但是在页面刷新后,索赔就消失了。
我认为Owin处理了声明的序列化并将其放入cookie中,但情况似乎并非如此。
我按如下方式增加索赔:
var claimsIdentity = (ClaimsIdentity) ClaimsPrincipal.Current.Identity;
if (!claimsIdentity.IsAuthenticated) return;
var identity = new ClaimsIdentity(claimsIdentity);
var currentTenantClaim = GetTenantClaim();
if (currentTenantClaim != null)
claimsIdentity.RemoveClaim(currentTenantClaim);
claimsIdentity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));
context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
(new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});
对于如何将新的声明持久化到cookie中有什么想法吗?
我将声明添加到错误的Identity中。它们必须添加到identity变量中,而不是添加到claimsIdentity中。
工作代码:
var claimsIdentity = (ClaimsIdentity) context.Authentication.User.Identity;
if (!claimsIdentity.IsAuthenticated) return;
var identity = new ClaimsIdentity(claimsIdentity);
var currentTenantClaim = GetTenantClaim(identity);
if (currentTenantClaim != null)
identity.RemoveClaim(currentTenantClaim);
identity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));
context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
(new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});
这就是我使用。net 6的方法:
var identity = (ClaimsIdentity)Request.HttpContext.User.Identity;
identity.AddClaim(new Claim("ClaimName", "ClaimValue"));
如果我想在这个恒等式中验证这个声明,我要这样做
var Claims = User.Claims;
希望对大家有所帮助