Graph API authenticate as a user programmatically

后端 未结 2 492
青春惊慌失措
青春惊慌失措 2020-12-12 03:50

I\'m trying to get a specific user OAuth2 bearer token using HTTP POST request, and nothing seems to work.

login_url = \'https://login.microsoftonline.com/\         


        
相关标签:
2条回答
  • 2020-12-12 04:23

    For GraphAPI, resource is "https://graph.windows.net/"

    If you don't want to use ADAL, you might however take a look at the code for usage of "resource". This scenario is covered, so consider ADAL as a big sample :)

    Also, msrestazure has a UserPassCredentials instance that works too on GraphAPI.

    0 讨论(0)
  • 2020-12-12 04:24

    You can do it manually, see my other answer here: https://stackoverflow.com/a/40844983/1658906.

    You must use grant_type=password and call the oauth2/token endpoint. Here is the C# version for authenticating:

    private async Task<string> GetAccessToken()
    {
        string tokenEndpointUri = Authority + "oauth2/token";
    
        var content = new FormUrlEncodedContent(new []
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", Username),
                new KeyValuePair<string, string>("password", Password),
                new KeyValuePair<string, string>("client_id", ClientId),
                new KeyValuePair<string, string>("client_secret", ClientSecret),
                new KeyValuePair<string, string>("resource", PowerBiResourceUri)
            }
        );
    
        using (var client = new HttpClient())
        {
            HttpResponseMessage res = await client.PostAsync(tokenEndpointUri, content);
    
            string json = await res.Content.ReadAsStringAsync();
    
            AzureAdTokenResponse tokenRes = JsonConvert.DeserializeObject<AzureAdTokenResponse>(json);
    
            return tokenRes.AccessToken;
        }
    }
    

    In the request you must specify:

    1. Username
    2. Password
    3. Client ID
    4. Client secret
    5. The resource URI
    0 讨论(0)
提交回复
热议问题