pur*_*uri 14 c# asp.net authentication owin openid-connect
我对使用新的ASP.Net OpenID Connect框架有疑问,同时在身份验证管道中添加新的声明,如下面的代码所示.我不确定幕后会发生多少'魔术'.我认为我的大部分问题都集中在不了解OWIN认证中间件而不是OpenID Connect上.
Q1.我要手动设置HttpContext.Current.User和Thread.CurrentPrincipal自OwinContext.Authentication.User?
Q2.我希望能够像以前一样将对象类型添加到声明中System.IdentityModel.Claims.Claim.新System.Security.Claims.Claim类只接受字符串值?
Q3.我是否需要使用新的SessionSecurityToken包装我ClaimsPrincipal在System.Security.Claims.CurrentPrincipal序列化到一个cookie -我使用的 app.UseCookieAuthentication(new CookieAuthenticationOptions());,但现在肯定在维护期间我添加任何额外的权利要求书,做究竟是什么SecurityTokenValidated事件?
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
SecurityTokenValidated = (context) =>
{
// retriever caller data from the incoming principal
var UPN = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
var db = new SOSBIADPEntities();
var user = db.DomainUser.FirstOrDefault(b => (b.EntityName == UPN));
if (user == null)
{
// the caller was not a registered user - throw to block the authentication flow
throw new SecurityTokenValidationException();
}
var applicationUserIdentity = new ClaimsIdentity();
applicationUserIdentity.AddClaim(new Claim(ClaimTypes.Name, UPN, ""));
applicationUserIdentity.AddClaim(new Claim(ClaimTypes.Sid, user.ID.ToString(CultureInfo.InvariantCulture)));
var applications =
db.ApplicationUser
.Where(x => x.ApplicationChild != null && x.DomainUser.ID == user.ID)
.Select(x => x.ApplicationChild).OrderBy(x => x.SortOrder);
applications.ForEach(x =>
applicationUserIdentity.AddClaim(new Claim(ClaimTypes.System, x.ID.ToString(CultureInfo.InvariantCulture))));
context.OwinContext.Authentication.User.AddIdentity(applicationUserIdentity);
var hasOutlook = context.OwinContext.Authentication.User.HasClaim(ClaimTypes.System, "1");
hasOutlook = hasOutlook;
HttpContext.Current.User = context.OwinContext.Authentication.User;
Thread.CurrentPrincipal = context.OwinContext.Authentication.User;
var usr = HttpContext.Current.User;
var c = System.Security.Claims.ClaimsPrincipal.Current.Claims.Count();
return Task.FromResult(0);
},
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
小智 18
您是否有特定原因要添加新的ClaimsIdentity?
执行目标的最简单方法是检索ClaimsIdentity通过验证传入令牌生成的内容,ClaimsIdentity claimsId = context.AuthenticationTicket.Identity;一旦获得它,只需添加声明即可.其余的中间件将负责在会话cookie中将其与其他所有内容串行化,将结果放在当前ClaimsPrincipal,以及您似乎尝试手动执行的所有其他操作.
HTH
V.