如何使用PKCE进行授权和访问令牌请求

时间:2020-08-26 12:11:52

标签: authentication oauth-2.0 authorization azure-functions pkce

您能指出我正确的方法并将参数设置为:

  1. 使用PKCE向Postman中的身份端点(https://.../login)发出授权请求 附件中有发送的参数列表。 作为Grant_type值,我使用->授权码 不幸的是,我收到了“错误的请求”,邮递员中的Invalid_grant enter image description here

  2. 发出访问令牌请求。在此请求中,我收到无效请求。我想我错过了参数刷新令牌,但我不知道如何获取/生成它: enter image description here

我编写了Azure函数的代码来请求访问令牌,但不幸的是,我从令牌端点收到了{“ error”:“ invalid_request”}。 这是我的代码,您能告诉我我在做什么错吗?

[FunctionName("GetAccessToken")]
    public async Task<IActionResult> GetAccessToken(
  [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
  ILogger log)
    {
        try
        {
            log.LogInformation("C# HTTP trigger function ''GetAccessToken'' processed a request.");

            string clientSecret = "some secret";

            string accessToken = "";     

            RequestAccessToken rT = new RequestAccessToken();
            rT.Code = req.Form["code"];
            rT.RedirectUri = req.Form["redirect_uri"];
            rT.GrantType = req.Form["grant_type"];
            rT.ClientId = req.Form["client_id"];
            rT.CodeVerifier = req.Form["code_verifier"];

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://<access_token_endpoint_base_uri>");
                client.DefaultRequestHeaders
                .Accept
                .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

                var body = new { EntityState = new {
                    code = rT.Code,
                    redirect_uri = rT.RedirectUri,
                    grant_type = rT.GrantType,
                    client_id = rT.ClientId,
                    client_secret = clientSecret,
                    code_verifier = rT.CodeVerifier

                } };
                var result = await client.PostAsJsonAsync(
                               "/login",
                               body);
                accessToken = await result.Content.ReadAsStringAsync();
            }             

            return new OkObjectResult(accessToken);

        }
        catch (Exception ex)
        {
            log.LogInformation(ex.ToString());

            return new ObjectResult(ex.ToString()) { StatusCode = 500 };
        }
    }

1 个答案:

答案 0 :(得分:0)

Steps 4 and 8 of my blog post显示标准PKCE参数。

但是通过Postman之类的工具重现整个流程非常棘手,因为通常还需要遵循重定向并管理用户名和密码的表单发布。