【问题标题】:Azure app oauth2 generating wrong access token in Client Credentials grant typeAzure 应用程序 oauth2 在客户端凭据授予类型中生成错误的访问令牌
【发布时间】:2020-03-20 09:41:57
【问题描述】:

我是使用 Azure AD 和 OAuth2 的初学者。我在 Azure AD 中部署了一个示例 WEB API。我通过 Postman 应用程序使用我的 WEB API。在 Postman 中使用 WEB API 之前,我需要生成访问令牌。但是当我在邮递员中生成访问令牌时,它总是接受Grant Type - Authentication Code。当我将值更改为Client Credentials 时,API 不接受生成的访问令牌。它显示UnAuthorized 消息。

在 Azure 门户 - 应用程序设置“证书和机密”窗口中,我创建了一个描述为“邮递员”的客户端机密。我没有在此应用中上传证书。

我想生成具有“授予类型”值“客户端凭据”的访问令牌。有什么额外的配置吗?

【问题讨论】:

标签: azure asp.net-core asp.net-web-api oauth-2.0 azure-active-directory


【解决方案1】:

Is there any additional configuration for this ?

不,没有用于生成令牌的其他设置 client_credentials.

你都需要以下参数:

  1. client_id
  2. client_secret
  3. resource (For v2.0 scope)
  4. grant_type

你将如何在 PostMan 中请求令牌:

Your Token Endpoint:

https://login.microsoftonline.com/YourTenent.onmicrosoft.com/oauth2/token Method Type:POST

Request Body:

grant_type:client_credentials

client_id:00ab01_Your_Azure-Ad_Application_Id_fbbf8e

client_secret:XNk2zgXx_Your_Azure-Ad_Application_Secret_vjdz2Q

resource:https://graph.microsoft.com/

看截图:

代码片段:

  //Token Request End Point
    string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/token";
    var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

    //I am Using client_credentials as It is mostly recommended
    tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["grant_type"] = "client_credentials",
        ["client_id"] = "b6695c7be_YourClient_Id_e6921e61f659",
        ["client_secret"] = "Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=",
        ["resource"] = "https://graph.microsoft.com/" 
    });

    dynamic json;
    AccessTokenClass results = new AccessTokenClass();
    HttpClient client = new HttpClient();

    var tokenResponse = await client.SendAsync(tokenRequest);

    json = await tokenResponse.Content.ReadAsStringAsync();
    results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

使用的类:

public class AccessTokenClass
   {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
   }

希望这会有所帮助。如果您仍有任何疑虑,请随时分享。

【讨论】:

  • 非常感谢您的宝贵回答。这对我真的很有帮助。现在我可以生成具有“客户端凭据”授权类型的访问令牌。但是当我将此访问令牌添加到我的请求标头中时,它会显示 401 Unauthorized 错误。
  • 哦,我明白了,您尝试使用令牌访问哪个 API?请添加您的代码 sn-p 以更快地调查它。当您的令牌没有您尝试访问的权限 API 时,通常会发生 401。因此,您必须在令牌上设置权限才能访问您尝试访问的 URL。希望你明白我的意思
  • 对于迟到的回复,我真的很抱歉,现在我不在办公室,因为我在科钦喀拉拉邦,在我们的城市,由于 COVID 19,情况真的很糟糕。我会尽快回复可能。
猜你喜欢
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 2019-05-11
  • 2020-02-25
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多