Azure app oauth2 generating wrong access token in Client Credentials grant type

后端 未结 1 408
情书的邮戳
情书的邮戳 2021-01-27 20:42

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 Po

相关标签:
1条回答
  • 2021-01-27 21:17

    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:

    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.

    0 讨论(0)
提交回复
热议问题