【问题标题】:Azure AD getting Access token - Bad RequestAzure AD 获取访问令牌 - 错误请求
【发布时间】:2022-01-05 19:56:23
【问题描述】:

我有一个注册了 User.read 和 User.ReadBasicAll API 权限的应用,我正在尝试通过授权码授予获取访问令牌。在用户同意后我得到了授权码,但是当我尝试获取访问令牌时,我总是得到“400 Bad Request”。

以下是获取验证码的网址:

https://login.microsoftonline.com/common/oauth2/authorize
?response_type=code
&client_id=my_client_id
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default+openid+offline_access+
&redirect_uri=https%3A%2F%2Fzzzzzzzzzzzz.azurewebsites.net%2Flogin%2Fauthorized
&response_mode=query
&sso_reload=true

下面是从上面的身份验证代码中获取访问令牌的 C# 函数,这里我得到的是 HTTP 400 错误请求。在这里引用错误的任何帮助都会非常有帮助。请注意,为了更好地理解,我对示例值进行了硬编码。

public string GetAccessToken(string authCode)
        {
            string result = string.Empty;
            try
            {
                var client = new HttpClient();
                
                var uri = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
                var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("client_id", "my_client_id"),
                new KeyValuePair<string, string>("grant_type", "authorization_code"),
                new KeyValuePair<string, string>("redirect_uri", "https://zzzzzzzzzzzz.azurewebsites.net/"),
                new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default openid offline_access"),
                new KeyValuePair<string, string>("code", authCode),
                new KeyValuePair<string, string>("client_secret", "mysecret")
             };

                var content = new FormUrlEncodedContent(pairs);

                var response = client.PostAsync(uri, content).Result;


                string paramsForAccessToken = string.Empty;
                foreach (var item in pairs)
                {
                    paramsForAccessToken += item.Key + " = " + item.Value + "<br>";
                }
                result += "Request Content : " + content + "<br><br> <br>";
                result += "Status code " + response.StatusCode.ToString() + "<br><br>";
                result += "Response Reason Phrase" + response.ReasonPhrase + "<br><br>";
                result += "Response content" + response.Content.ToString()+ "<br><br>";
                result += "Response headers" + response.Headers + "<br><br>";
                result += "Request message" + response.RequestMessage+ "<br><br>";
                result += paramsForAccessToken;
                if (response.IsSuccessStatusCode)
                {

                    result += response.Content.ReadAsStringAsync().Result;
                }
                


            }

            catch (Exception ex)
            {
                lblAccessToken.Text = ex.ToString();
            }
            return result;

        }

下面建议的answer 有同样的问题

这是 response.ToString() 的输出

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Cache-Control: no-store, no-cache
  Pragma: no-cache
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Content-Type-Options: nosniff
  P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
  x-ms-request-id: da55d4ba-3ccb-45f9-81c9-9f7394f12402
  x-ms-ests-server: 2.1.12231.8 - EUS ProdSlices
  Set-Cookie: fpc=AudRQ4x4W7RBpZY5YwJyyR_kb8VOAQAAAA_4NtkOAAAA; expires=Wed, 29-Dec-2021 16:34:25 GMT; path=/; secure; HttpOnly; SameSite=None
  Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; httponly
  Set-Cookie: stsservicecookie=estsfd; path=/; secure; httponly
  Date: Mon, 29 Nov 2021 16:34:24 GMT
  Content-Type: application/json; charset=utf-8
  Expires: -1
  Content-Length: 477
}

【问题讨论】:

  • 你试过邮递员吗?您可以参考此线程以使用 c# 从身份验证代码中获取访问令牌:stackoverflow.com/questions/69738536/…
  • 400 bad request 表示正在使用的 Auth 代码无效。 Postman 的相同测试是否成功?

标签: c# oauth-2.0 azure-active-directory authorization access-token


【解决方案1】:

我已经在我的环境中测试过。

我能够成功获取访问令牌。

您可以使用以下代码获取访问令牌:

using System;
using System.Collections.Generic;
using System.Net.Http;

namespace GetAccessToken
{
    class Program
    {

        public static void Main(string[] args)
        {
            Console.WriteLine(getToken());
        }
        public static string getToken()
        {
            string result = string.Empty;
            try
            {
                var client = new HttpClient();
                var uri = "https://login.microsoftonline.com/common/oauth2/token?api-version=1.0";
                var pairs = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("client_id", "my_client_id"),
                    new KeyValuePair<string, string>("client_secret", "mysecret")
                    new KeyValuePair<string, string>("grant_type", "authorization_code"),
                    new KeyValuePair<string, string>("code", "authCode"),
                    new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default openid offline_access")
                };

                var content = new FormUrlEncodedContent(pairs);

                var response = client.PostAsync(uri, content).Result;

                
                string paramsForAccessToken = string.Empty;
                foreach (var item in pairs)
                {
                    paramsForAccessToken += item.Key + " = " + item.Value + "<br>";
                }
                result += "Request Content : " + content + "<br><br> <br>";
                result += "Status code " + response.StatusCode.ToString() + "<br><br>";
                result += "Response Reason Phrase" + response.ReasonPhrase + "<br><br>";
                result += "Response content" + response.Content.ToString() + "<br><br>";
                result += "Response headers" + response.Headers + "<br><br>";
                result += "Request message" + response.RequestMessage + "<br><br>";
                result += paramsForAccessToken;

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            
            return result;
        }
    }
}

【讨论】:

  • 谢谢。你的有什么不同?
  • 我在uri中添加了版本。还使用 System.Collections.Generic;使用 System.Net.Http;
  • 同样的问题。请查看我更新后的问题以及您的函数输出。
  • 你能打印响应,看看它是否为空或有任何数据吗?
  • 已在问题中更新。
猜你喜欢
  • 1970-01-01
  • 2016-12-03
  • 2020-07-05
  • 1970-01-01
  • 2023-03-23
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
相关资源
最近更新 更多