Graph API authenticate as a user programmatically

后端 未结 2 494
青春惊慌失措
青春惊慌失措 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: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 GetAccessToken()
    {
        string tokenEndpointUri = Authority + "oauth2/token";
    
        var content = new FormUrlEncodedContent(new []
            {
                new KeyValuePair("grant_type", "password"),
                new KeyValuePair("username", Username),
                new KeyValuePair("password", Password),
                new KeyValuePair("client_id", ClientId),
                new KeyValuePair("client_secret", ClientSecret),
                new KeyValuePair("resource", PowerBiResourceUri)
            }
        );
    
        using (var client = new HttpClient())
        {
            HttpResponseMessage res = await client.PostAsync(tokenEndpointUri, content);
    
            string json = await res.Content.ReadAsStringAsync();
    
            AzureAdTokenResponse tokenRes = JsonConvert.DeserializeObject(json);
    
            return tokenRes.AccessToken;
        }
    }
    

    In the request you must specify:

    1. Username
    2. Password
    3. Client ID
    4. Client secret
    5. The resource URI

提交回复
热议问题