令牌端點的客戶端庫(OAuth 2.0和OpenID Connect)做爲HttpClient
一組擴展方法提供。這容許HttpClient
以您喜歡的方式建立和管理生命週期- 例如靜態或經過像Microsoft這樣的工廠HttpClientFactory
。html
4.1 請求令牌
調用主擴展方法RequestTokenAsync
- 它直接支持標準參數,如客戶端ID /機密(或斷言)和受權類型,但它也容許經過字典設置任意其餘參數。全部其餘擴展方法最終在內部調用此方法:git
var client = new HttpClient(); 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", "api1" } } });
響應屬於TokenResponse
類型而且具備用於標準令牌響應參數等屬性access_token
,expires_in
等等。你也能夠訪問原始響應以及對已解析JSON的文檔(經過Raw
和Json
屬性)。github
在使用響應以前,您應該始終檢查IsError
屬性以確保請求成功:api
if (response.IsError) throw new Exception(response.Error); var token = response.AccessToken; var custom = response.Json.TryGetString("custom_parameter");
4.2 使用client_credentials
受權類型請求令牌
該方法具備方便requestclientcredentialstoken
擴展屬性的client_credentials
類型:app
var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = "https://demo.identityserver.io/connect/token", ClientId = "client", ClientSecret = "secret", Scope = "api1" });
4.3 使用password
受權類型請求令牌
該方法具備方便requestclientcredentialstoken
擴展屬性的password
類型:ide
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = "https://demo.identityserver.io/connect/token", ClientId = "client", ClientSecret = "secret", Scope = "api1", UserName = "bob", Password = "bob" });
4.4 使用authorization_code
受權類型請求令牌
該方法具備方便requestclientcredentialstoken
擴展屬性的authorization_code
類型和PKCE:url
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" });
4.5 使用refresh_token
受權類型請求令牌
該方法具備方便requestclientcredentialstoken
擴展屬性的refresh_token
類型:spa
var response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "client", ClientSecret = "secret", RefreshToken = "xyz" });
4.6 請求設備令牌
該方法具備方便requestclientcredentialstoken
擴展屬性的urn:ietf:params:oauth:grant-type:device_code
類型.net
var response = await client.RequestDeviceTokenAsync(new DeviceTokenRequest { Address = disco.TokenEndpoint, ClientId = "device", DeviceCode = authorizeResponse.DeviceCode });
github地址code