我的应用程序使用OpenId进行身份验证,如下所示:
services.AddAuthentication(o =>
{
o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.Scope.Add("openid");
o.Scope.Add("permissions");
o.Authority = "https://localhost:44305";
o.ClientId = "MyTestClient";
o.ClientSecret = "MyTestClientSecret";
o.ResponseType = OpenIdConnectResponseType.IdTokenToken;
});
当我在验证后检查User对象时,它只有来自ID令牌的声明,而不是访问令牌。如何从访问令牌中获取声明?
答案 0 :(得分:1)
您可以使用OpenIdConnectOptions.Events中的OnTokenResponseReceived事件
services.AddAuthentication(o =>
{
o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.Scope.Add("openid");
o.Scope.Add("permissions");
o.Authority = "https://localhost:44305";
o.ClientId = "MyTestClient";
o.ClientSecret = "MyTestClientSecret";
o.ResponseType = OpenIdConnectResponseType.IdTokenToken;
o.Events = new OpenIdConnectEvents
{
OnTokenResponseReceived = ctx =>
{
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadJwtToken(ctx.TokenEndpointResponse.AccessToken);
//jsonToken.Claims <--here you go, update the ctx.Principal if necessary.
return Task.CompletedTask;
}
};
});
答案 1 :(得分:0)
我相信您需要拦截AddOpenIdConnect()中的OnAuthorizationCodeReceived事件。从那里你应该有权访问ctx.ProtocolMessage.Code,这是与AcquireTokenByAuthorizationCodeAsync()一起使用的AuthorizationCode,以生成更多的令牌。您还需要将ResponseType设置为&#34; code id_token&#34;以便为您生成代码。一个很好的教程是https://joonasw.net/view/aspnet-core-2-azure-ad-authenticatio。希望这有帮助