IdentityServer4在.net6中使用的变化
IdentityServer4在.net6中不再使用DiscoveryClient
之前使用的DiscoveryClient连接Identity Server,这次使用时发现找不到了,查了文档发现已更新为使用HttpClient
发现服务。会连接identity server的/.well-known/openid-configuration构建
using IdentityModel.Client; var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } Console.WriteLine("Hello, World!");
获取Token的多种方式
TokenClient也没有使用了,新的写法
RequestTokenAsync
var response = await client.RequestTokenAsync(new TokenRequest { Address = "https://demo.identityserver.io/connect/token", GrantType = "custom", ClientId = "client", ClientSecret = "secret", Parameters = { { "custom_parameter", "custom value"}, { "scope", "api" } } });
RequestClientCredentialsTokenAsync
var response = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "client", ClientSecret = "secret", GrantType = "client_credentials", Scope = "api" }).Result;
RequestPasswordTokenAsync
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = "https://demo.identityserver.io/connect/token", ClientId = "client", ClientSecret = "secret", Scope = "api1", UserName = "bob", Password = "bob" });
RequestAuthorizationCodeTokenAsync
var response = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { Address = IdentityServerPipeline.TokenEndpoint, ClientId = "client", ClientSecret = "secret", Code = code, RedirectUri = "https://app.com/callback", // optional PKCE parameter CodeVerifier = "xyz" });
RequestDeviceTokenAsync
var response = await client.RequestDeviceTokenAsync(new DeviceTokenRequest { Address = disco.TokenEndpoint, ClientId = "device", DeviceCode = authorizeResponse.DeviceCode });
获取刷新Token
var response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "client", ClientSecret = "secret", RefreshToken = "xyz" });