第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地址

posted @ 2019-04-28 23:06  ThinkJay  阅读(4755)  评论(0编辑  收藏  举报