使用IdentityModel client_credentials请求OpenID Connect令牌

时间:2020-07-08 07:59:53

标签: c# openid-connect dotnet-httpclient bearer-token identitymodel

我正在遵循https://identitymodel.readthedocs.io/en/latest/client/token.html#requesting-a-token-using-the-client-credentials-grant-type上的IdentityModel教程,在此我专门尝试使用client_credentials授予类型来请求令牌。

我正在使用.NET Framework 4.7.2和IdentityModel 4.3.0

我从邮递员发出此POST请求

POST https://example.com/cas/oauth2/token?grant_type=client_credentials&requested_token_type=urn:ietf:params:oauth:token-type:cas_ticket&resource=https%3A%2F%2Ftest.com%2Fesig_rs%2Fapi%2Frest%2Fv1%2Fsign%2Fremote%2Fuser%3FuserId%3Duser01&client_assertion=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJmOGtDT3pwa0pqMXM2b0tsUHpWRk9wV2J6d203Tnp0SnpSS0UxUm82RWVQOUhvYVRqWmRGeEtoc3J3akdRcXJaZTNmOWVHUkc0czR1a0FyN2F6b2hNWTNHLU5hQWMyM0NxQVNlR3RLMms0b2t0YTgiLCJhdWQiOiJodHRwczovL2VjYXMuYWNjZXB0YW5jZS5lYy5ldXJvcGEuZXUvY2FzL29hdXRoMi90b2tlbiIsImlzcyI6ImY4a0NPenBrSmoxczZvS2xQelZGT3BXYnp3bTdOenRKelJLRTFSbzZFZVA5SG9hVGpaZEZ4S2hzcndqR1FxclplM2Y5ZUdSRzRzNHVrQXI3YXpvaE1ZM0ctTmFBYzIzQ3FBU2VHdEsyazRva3RhOCIsImV4cCI6MTU5NDE5MzczOTg4MCwianRpIjoiNtYTg5My1iMmNlLNWRkM2MxMjExZjJkIn0.Hrw4TXfvZZwh0R6wh-qfkjMzFHeuStLznvvVpvFjfMSC2R0glMs0irdaD2RgsGc_5Nnz-YQ2A&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer HTTP/1.1
Content-Type: application/x-www-form-urlencoded
charset: UTF-8
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: f36b49b0-ba4a-4c93-a51f-2e43a6cc141d
Host: example.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 0

并成功获得此响应:

{
    "access_token":"PT-728-TzTu87bPxohNMUi0ur4VquzXpzvnL7OzfZy8EYKC9XXS9wC1VsXEsA3y5CltWJsOGIbaKYcXlC4xzLUNle3JagQ-NaAc23CqASe1XCPO6fxJsG-FCNsvYHzy2e1TtzlyExAnOJazWTlXwd6JzUpiuusDMkzwEuQAjqo85q5RRI5veAbQP61m6U1RHjNfwk6q1bdkFzW",
    "issued_token_type":"urn:ietf:params:oauth:token-type:cas_ticket",
    "token_type":"cas_ticket",
    "expires_in":300
}

我正在通过.NET控制台应用程序

var client = new HttpClient();

JwtHeader header = new JwtHeader { { "alg", "HS512" } };

var payload = new JwtPayload
{
    {"iss", ConfigurationManager.AppSettings["client_id"].ToString()},
    {"sub", ConfigurationManager.AppSettings["client_id"].ToString()},
    {"aud", $"https://example.com/cas/oauth2/token"},
    {"jti", Guid.NewGuid().ToString("N")},
    {"exp", (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + 5 * 60}
};

var securityToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(securityToken);

ClientAssertion assertion = new ClientAssertion();
assertion.Type = ClientAssertionTypes.JwtBearer;
assertion.Value = tokenString;

ClientCredentialsTokenRequest cctRequest = new ClientCredentialsTokenRequest
{
    Address = "https://example.com/cas/oauth2/token",
    Method = HttpMethod.Post,
    ClientAssertion = assertion,
    GrantType = GrantTypes.ClientCredentials,
    ClientId = ConfigurationManager.AppSettings["client_id"].ToString(),
    ClientSecret = ConfigurationManager.AppSettings["client_secret"].ToString(),
    Scope = "openid",
                
    Parameters = { 
        { "resource", "https://test.com/esig_rs/api/rest/v1/sign/remote/user?userId=user01" },
        { "requested_token_type", "urn:ietf:params:oauth:token-type:cas_ticket" } 
    }
};

var response = await client.RequestClientCredentialsTokenAsync(cctRequest);
if (response.IsError)
{
    throw new Exception(response.Error);
}

并立即收到异常:

System.Exception
  HResult=0x80131500
  Message=An error occurred while sending the request.
  Source=Console-application
  StackTrace:
   at Console-application.MyClass.<GetTicketAsync>d__0.MoveNext() in C:\...\MyClass.cs:line 121
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Console-application.Program.<Main>d__0.MoveNext() in C:\...\Program.cs:line 20

  This exception was originally thrown at this call stack:
    Console-application.MyClass.GetTicketAsync() in a.cs
    [External Code]
    Console-application.Program.Main(string[]) in Program.cs

C#请求出了什么问题?

0 个答案:

没有答案