我在我的应用程序中使用的是中间件,以通过Identity Provider使用外部身份验证。代码(不是整个启动,而是仅相对于此中间件的一部分)如下:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:50001",
RedirectUri = "http://localhost:26525/signin-oidc",
PostLogoutRedirectUri = "http://localhost:26525/signout-callback-oidc",
RequireHttpsMetadata = false,
ClientId = "webforms2",
AuthenticationType = "oidc",
SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
ResponseType = "id_token token",
Scope = "openid profile email",
UseTokenLifetime = false
});
工作正常。目前,我添加了 Notification (通知)属性,并要求Identity Server使用接收到的Identity Token获得更多的声明,我收到了异常。逐步,代码看起来像这样,导致异常的部分:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:50001",
RedirectUri = "http://localhost:26525/signin-oidc",
PostLogoutRedirectUri = "http://localhost:26525/signout-callback-oidc",
RequireHttpsMetadata = false,
ClientId = "webforms2",
AuthenticationType = "oidc",
SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
ResponseType = "id_token token",
Scope = "openid profile email",
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async n =>
{
var claimsToExclude = new[]
{
"aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
};
var claimsToKeep = n.AuthenticationTicket.Identity.Claims.Where(x => !claimsToExclude.Contains(x.Type)).ToList();
claimsToKeep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));
if (n.ProtocolMessage.AccessToken != null)
{
claimsToKeep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:50001");
var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
{
Address = disco.UserInfoEndpoint,
Token = n.ProtocolMessage.AccessToken
});
var userInfoClaims = userInfoResponse.Claims
.Where(x => x.Type != "sub"); // filter sub since we're already getting it from id_token
claimsToKeep.AddRange(userInfoClaims);
}
var ci = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType, "name", "role");
ci.AddClaims(claimsToKeep);
n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(ci, n.AuthenticationTicket.Properties);
},
RedirectToIdentityProvider = n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
n.ProtocolMessage.IdTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
}
return Task.FromResult(0);
}
}
});
而且我无法弄清楚该异常,因为 mscorlib.pdb未加载会弹出而没有提供更多信息。实际上,我看到此页面弹出是因为我在工具>调试>常规下关闭了仅我的代码选项。否则,应用程序只会说我的“应用程序已进入中断状态”。在这种情况下,如果我检查调用堆栈,我会看到最后一个调用是:
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.__Canon>(ref System.__Canon stateMachine) Unknown
在此先感谢您的帮助!