我正在尝试使用
PKCE
. 我能够成功地使用DiscordAPI进行身份验证,并且我收到一个
code
从服务器返回。
但是,当我试图打电话给
https://discordapp.com/api/oauth2/token
终点我持续得到
Bad Request
结果。
我试过几种方法来获得我的代币,但都失败了。
尝试(1)使用HttpClient:
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("client_id", Constants.ClientId));
nvc.Add(new KeyValuePair<string, string>("client_secret", Constants.Secret));
nvc.Add(new KeyValuePair<string, string>("code_verifier", codeVerifier)); // method param
nvc.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("code", authCode)); // method param
nvc.Add(new KeyValuePair<string, string>("redirect_uri", Constants.Redirect));
nvc.Add(new KeyValuePair<string, string>("scope", "identify email connections"));
var req = new HttpRequestMessage(HttpMethod.Post, "https://discordapp.com/api/oauth2/token")
{
Content = new FormUrlEncodedContent(nvc)
};
var authTokenResponse = await this.Client.SendAsync(req).ConfigureAwait(false);
// results in BadRequest
我也试过用
StringContent
像这样的对象:
var stringContent = new StringContent($"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={codeVerifier}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", Encoding.UTF8, "application/x-www-form-urlencoded");
这两个结果
var client = new RestSharp.RestClient($"{this.Client.BaseAddress}/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={code}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
我仔细检查了所有的值,并确保我的客户Id和密码是正确的。我试过发送请求时不带
code_verifier
. 没有
代码验证器
我明白了
Unauthorized
.
问题
为了遵守PKCE,我需要一个
代码验证器
. 这就是我生成代码的方式。(注意,我是
尝试将其用作身份验证代码。)
Random rng = new Random();
byte[] code = new byte[32];
rng.NextBytes(code);
CodeVerifier = Base64UrlEncoder.Encode(rng.ToString());
然后我使用了一个从
c-sharpcorner.com
,如下所示:
using (SHA256 sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
var builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
我把结果当作
code_challenge
同时获得我的身份验证码。
这就是我知道需要PKCE的地方。
https://github.com/discordapp/discord-api-docs/issues/450
PKCE讨论在此继续:
https://github.com/discordapp/discord-api-docs/issues/1296
好吧,基于
iwokal's
Custom Scheme Redirect
,如果您只是使用
http
代码验证器
出去你就可以走了。
也就是说,这个
PKCE工作流未记录
. 因为我花了500分,所以我将把这些分奖励给能够解决PKCE OAuth工作流的人。