【发布时间】:2021-04-06 14:58:52
【问题描述】:
我正在使用 REST API,并且正在 C# 中从 Docusign 的 Postman 集合中实现“02 JWT 访问令牌”。我生成了 RSA 密钥对,标头和正文已准备好 (Header.Body) 为 Base64 格式。
long d1 = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
long d2 = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 1800;
string header = "{ \"alg\": \"RS256\", \"typ\": \"JWT\"}";
string body = "{ \"iss\": \"" + integrationKey + "\", \"sub\": \"" + apiUsername + "\", \"aud\": \"" + environment + "\", \"iat\": " + d1.ToString() + ", \"exp\": " + d2.ToString() + ", \"scope\": \"signature impersonation\"}";
string base64 = Base64Encode(header) + "." + Base64Encode(body);
Base64 编码器:
public string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
我已使用以下代码进行签名,它似乎可以工作:
private string Sign(string message, string privateKey)
{
try
{
byte[] r = Encoding.UTF8.GetBytes(message);
StringReader strReader = new StringReader(privateKey);
PemReader pemReader = new PemReader(strReader);
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
RsaKeyParameters privateRSAKey = (RsaKeyParameters)keyPair.Private;
ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");
sig.Init(true, privateRSAKey);
sig.BlockUpdate(r, 0, r.Length);
byte[] signedBytes = sig.GenerateSignature();
return Convert.ToBase64String(signedBytes);
}
catch (Exception ex)
{
throw ex;
}
}
然后我提交。断言(下面代码中的标记)格式为“Header.Body.Signature”:
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://" + environment + "/oauth/token"))
{
var contentList = new List<string>();
contentList.Add($"assertion={token}");
contentList.Add($"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedKeys);
HttpResponseMessage response = null;
try
{
using (HttpClient client = new HttpClient())
{
response = await client.SendAsync(request);
}
if (response != null)
return await response.Content.ReadAsStringAsync();
else
throw new Exception();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
throw ex;
}
}
我在提交时遇到错误,{"error":"Invalid_request"}。
更多信息: https://developers.docusign.com/platform/auth/jwt/jwt-get-token/
【问题讨论】:
标签: c# docusignapi bouncycastle