Skip to main content
 首页 » 编程设计

c#之Web api 客户端 IdSrv3 身份验证中的访问 token

2024年04月18日44fff_TT

我正在使用 IdSrv3 进行身份验证。我需要在我的 web api owin 客户端中获取 access_token 以在另一个 web api 客户端中通过承载身份验证。 我的 Startup.cs 代码:

public class Startup 
{ 
        public void Configuration(IAppBuilder app) 
        { 
 
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; 
 
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); 
 
            var identityServerPath = ConfigurationManager.AppSettings["IdentityServerPath"]; 
 
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions 
            { 
                Authority = $"{identityServerPath}/core", 
 
                RequiredScopes = new[] { "openid"}, 
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, 
 
                // client credentials for the introspection endpoint 
                ClientId = "someid" 
            }); 
        } 
} 

我正在尝试通过这种方式获取访问 token :

var claims = (User as ClaimsPrincipal).Claims; 
var AccessToken = claims.First(x => x.Type == "access_token").Value; 

如何获取access_token?声明变量为空。

请您参考如下方法:

您可以将“PreserveAccessToken”属性设置为 true(默认为 false)。例如:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions 
{ 
    Authority = "https://localhost:44331", 
    ClientId = "apiOne",     
    ClientSecret = "secret", 
    RequiredScopes = new[] {"apiOne"}, 
    ValidationMode = ValidationMode.ValidationEndpoint, 
    PreserveAccessToken = true 
}); 

这会将访问 token 保留为声明。然后您可以像上面那样检索它。除了声明是“token”,而不是“access_token”。