第4章 令牌端點(Token Endpoint) - IdentityModel 中文文檔(v1.0.0)


令牌端點的客戶端庫(OAuth 2.0OpenID Connect)作為HttpClient一組擴展方法提供。這允許HttpClient以您喜歡的方式創建和管理生命周期- 例如靜態或通過像Microsoft這樣的工廠HttpClientFactory

4.1 請求令牌

調用主擴展方法RequestTokenAsync- 它直接支持標准參數,如客戶端ID /機密(或斷言)和授權類型,但它也允許通過字典設置任意其他參數。所有其他擴展方法最終在內部調用此方法:

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_tokenexpires_in等等。你也可以訪問原始響應以及對已解析JSON的文檔(通過RawJson屬性)。

在使用響應之前,您應該始終檢查IsError屬性以確保請求成功:

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類型:

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類型:

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:

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類型:

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類型

var response = await client.RequestDeviceTokenAsync(new DeviceTokenRequest
{
    Address = disco.TokenEndpoint,

    ClientId = "device",
    DeviceCode = authorizeResponse.DeviceCode
});

github地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM