代码之家  ›  专栏  ›  技术社区  ›  Dan Beaulieu

解决不一致OAuth令牌请求期间的“错误请求”

  •  0
  • Dan Beaulieu  · 技术社区  · 6 年前

    我正在尝试使用 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工作流的人。

    0 回复  |  直到 6 年前
        1
  •  1
  •   johnny 5    6 年前

    你的请求地址不对。创建代码流是为了防止泄漏客户端令牌。流程如下

    1. 客户机将该代码发送到服务器
    2. 你的服务器将代码和它的秘密一起传递给不一致的服务器

    注意:有2个重定向uri,1个解析代码,另一个解析令牌。

    您正试图直接向令牌终结点发出请求。您需要向授权终结点发出请求。获得令牌

    https://discordapp.com/api/oauth2/authorize?response_type=code&client_id=157730590492196864&scope=identify%20guilds.join&state=15773059ghq9183habn&redirect_uri=https%3A%2F%2Fnicememe.website&prompt=consent

    var state = Guid.NewGuid().ToString();
    var codeParams = new List<KeyValuePair<string, string>>();
    codeParams.Add(new KeyValuePair<string, string>("client_id", Constants.ClientId));
    codeParams.Add(new KeyValuePair<string, string>("redirect_uri", Constants.Redirect));
    codeParams.Add(new KeyValuePair<string, string>("scope", "identify email connections"));
    codeParams.Add(new KeyValuePair<string, string>("response_type", "code"));
    codeParams.Add(new KeyValuePair<string, string>("state", state))
    
    var req = new HttpRequestMessage(HttpMethod.Post, 
    "https://discordapp.com/api/oauth2/authorize") 
    { 
        Content = new FormUrlEncodedContent(nvc) 
    };
    var authTokenResponse = await this.Client.SendAsync(req).ConfigureAwait(false);
    

    不和谐就会回应你 redirect_uri 与法典和国家

    https://mywebsite.com/?code=NhhvTDYsFcdgNLnnLijcl7Ku7bEEeee&state=15773059ghq9183habn

    注意:大多数支持oauth的地方都要求您设置您的服务器重定向url。

    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);
    

    注意,在向令牌终结点发出请求时,请确保使用

        2
  •  3
  •   iwokal    6 年前

    好吧,经过一些研究,我可能知道发生了什么。您是否试图通过您创建的授权代码获取令牌?

    我相信正确的方法是 https://discordapp.com/api/oauth2/authorize

    您应该在获取令牌的步骤中使用此代码。