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

令牌端點的客戶端庫(OAuth 2.0OpenID Connect)做爲HttpClient一組擴展方法提供。這容許HttpClient以您喜歡的方式建立和管理生命週期- 例如靜態或經過像Microsoft這樣的工廠HttpClientFactoryhtml

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

相關文章
相關標籤/搜索