Azure app oauth2 generating wrong access token in

2020-04-21 08:21发布

I am a beginner in using Azure AD with OAuth2. I deployed a sample WEB API in my Azure AD. I consume my WEB API through the Postman application. Before consume the WEB API in Postman I need to generate the access token. But when i generate the access token in post man it's always accept the Grant Type - Authentication Code. When i change the value to Client Credentials the generated access token is not accepted in the API. it's shows UnAuthorized message.

In Azure portal - app settings 'Certificates & Secrets' window i create a client secret with description 'postman'. I didn't upload the certificate in this app.

I want to generate the access token with 'Grant Type' value 'Client Credentials'. Is there any additional configuration for this ?

1条回答
Juvenile、少年°
2楼-- · 2020-04-21 08:37

Is there any additional configuration for this ?

No, there is no additional settings for generating token using client_credentials.

You all need following parameter:

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

How Would You Request Token In 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/

See the screenshot:

enter image description here

Code Snippet:

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

Class Used:

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

Hope that would help. If you still have any concern feel free to share.

查看更多
登录 后发表回答