这个问题通常是由于缺少适当的缓存机制导致的。每次调用AcquireTokenSilent都会生成一个新的令牌,如果将其用于多个请求,会导致多次生成新令牌,从而使令牌不一致,导致每次获取到null值。
以下是解决这个问题的示例代码:
// 在Startup.Auth.cs文件中添加下面的代码。
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = postLogoutRedirectUri,
Scope = "openid profile",
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
NameClaimType = "name"
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async n =>
{
var claims = new List();
// 处理SecurityTokenValidated事件
// 更新缓存中的令牌状态等
n.AuthenticationTicket = new AuthenticationTicket(
new ClaimsIdentity(claims, n.AuthenticationTicket.Identity.AuthenticationType),
n.AuthenticationTicket.Properties);
}
}
});
此处使用了SecurityTokenValidated事件来更新缓存中的令牌状态以及其他的相关信息。在获取数据时,使用令牌的缓存,而不是每次都指定新的令牌。