我正在尝试在SecurityTokenValidated事件中获取访问令牌,在获得访问令牌后,我将其保存在声明中。问题是,当我尝试访问该声明时,它不再存在。
SecurityTokenValidated代码是这样的:
public static async Task<Task> SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
string source = ConfigurationManager.AppSettings["ExchangeOnlineId"];
var authContext = new AuthenticationContext(aadInstance, false);
var credentials = new ClientCredential(clientId, clientSecret);
var appRedirectUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + "/";
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(appRedirectUrl), credentials, source);
var accessToken = authResult.AccessToken;
var applicationUserIdentity = new ClaimsIdentity(context.OwinContext.Authentication.User.Identity);
applicationUserIdentity.AddClaim(new Claim("AccessToken", accessToken));
context.OwinContext.Authentication.User.AddIdentity(applicationUserIdentity);
return Task.FromResult(0);
}
我试图像这样访问它:
var accessToken =((ClaimsPrincipal)HttpContext.Current.User).FindFirst("AccessToken").Value;
更新: 事实证明我们有一些代码覆盖了HttpContext.Current.User。我对这段代码做了一些改动:
var claims = ((ClaimsPrincipal)HttpContext.Current.User).Claims;
var newPrincipal = new GenericPrincipal(new GenericIdentity(domainUserName), null);
((ClaimsIdentity)newPrincipal.Identity).AddClaims(claims);
HttpContext.Current.User = newPrincipal;
但没有运气。我可以很好地得到索赔,但我不能在newPrincipal上看到它们......
答案 0 :(得分:-1)
问题似乎是我访问它们的方式。这不起作用:
var accessToken =((ClaimsPrincipal)HttpContext.Current.User).FindFirst("AccessToken").Value;
虽然这样做:
var accessToken =((ClaimsIdentity)HttpContext.Current.User.Identity).FindFirst("AccessToken").Value;