1. 程式人生 > >IdentityServer4之Resource Owner Password Credentials(資源擁有者密碼憑據許可)

IdentityServer4之Resource Owner Password Credentials(資源擁有者密碼憑據許可)

cti -m error .text json conf ret logs send

IdentityServer4之Resource Owner Password Credentials(資源擁有者密碼憑據許可)

參考

官方文檔:2_resource_owner_passwords

概念:資源擁有者密碼憑據許可

認證服務端配置

認證服務ApiResource配置

new ApiResource("api1", "api項目 一")
{
    ApiSecrets = { new Secret("api1pwd".Sha256()) }
},

認證服務Client配置

//resource owner password grant client
new Client
{
    ClientId 
= "ro.client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, AccessTokenType = AccessTokenType.Reference, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { "api1" } },

認證服務Startup配置

public void ConfigureServices(IServiceCollection services)
{
    
// configure identity server with in-memory stores, keys, clients and scopes services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()) .AddTestUsers(Config.GetUsers()); }

配置完成啟動訪問http://localhost:5000/.well-known/openid-configuration

技術分享圖片

資源服務Api配置

資源服務器Startup配置

services.AddMvcCore()
    .AddAuthorization()
    .AddJsonFormatters();

services.AddAuthentication("Bearer")
    .AddIdentityServerAuthentication(options =>
    {
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ApiName = "api1";  
        options.ApiSecret = "api1pwd";  //對應ApiResources中的密鑰
    });

添加接口

[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var info = from c in User.Claims select new { c.Type, c.Value };
        var list = info.ToList();
        list.Add(new { Type = "api1返回", Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
        return new JsonResult(list);
    }
}

Client客戶端

(A)資源擁有者提供給客戶端它的用戶名和密碼。
(B)通過包含從資源擁有者處接收到的憑據,客戶端從授權服務器的令牌端點請求訪問令牌。當發起請求時,客戶端與授權服務器進行身份驗證。
(C)授權服務器對客戶端進行身份驗證,驗證資源擁有者的憑證,如果有效,頒發訪問令牌。

//resource owner password grant client
private void btnROAuth_Click(object sender, EventArgs e)
{
    Task<DiscoveryResponse> discoTask = DiscoveryClient.GetAsync(txtROAuthSer.Text);
    discoTask.Wait();
    var disco = discoTask.Result;
    if (disco.IsError)
    {
        MessageBox.Show(disco.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        txtROResult.Text = string.Empty;
        txtAccessToken.Text = string.Empty;
        return;
    }

    // request token
    var tokenClient = new TokenClient(disco.TokenEndpoint, txtROClient.Text, txtROSecret.Text);
    Task<TokenResponse> tokenTask = tokenClient.RequestResourceOwnerPasswordAsync(txtROUser.Text, txtROPwd.Text, txtROScopes.Text);
    tokenTask.Wait();
    var tokenResponse = tokenTask.Result;

    if (tokenResponse.IsError)
    {
        MessageBox.Show(tokenResponse.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        txtROResult.Text = string.Empty;
        txtAccessToken.Text = string.Empty;
        return;
    }

    txtROResult.Text = tokenResponse.Json.ToString();
    txtAccessToken.Text = tokenResponse.AccessToken;
}

調用Api

private void btnCallApi_Click(object sender, EventArgs e)
{
    // call api
    var client = new HttpClient();
    client.SetBearerToken(txtAccessToken.Text);

    var responseTask = client.GetAsync(txtCCApiUrl.Text);
    responseTask.Wait();
    var response = responseTask.Result;
    if (!response.IsSuccessStatusCode)
    {
        MessageBox.Show(response.StatusCode.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        txtApiResult.Text = string.Empty;
    }
    else
    {
        var contentTask = response.Content.ReadAsStringAsync();
        contentTask.Wait();
        var content = contentTask.Result;
        txtApiResult.Text = JArray.Parse(content).ToString();
    }
}

獲取token過程解析

Jwt形式獲取access_token、客戶端身份驗證兩種方式,參考上一篇獲取token過程解析。

Reference形式獲取access_token

將client的AccessTokenType設置為1

技術分享圖片

再次獲取的access_token不包含Claim信息。

技術分享圖片

此時獲取的access_token(加密後)對應PersistedGrants表中的key

技術分享圖片

調用Api資源服務過程解析

調用過程與上一篇調用Api資源服務過程解析一樣。

IdentityServer4之Resource Owner Password Credentials(資源擁有者密碼憑據許可)