图形API以编程方式进行用户身份验证

2024-10-01 22:35:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用httppost请求获取一个特定的用户OAuth2承载令牌,但似乎没有任何工作。在

login_url = 'https://login.microsoftonline.com/'
authorize_endpoint = '{0}{1}{2}'.format(login_url,config.tenant_id,'/oauth2/authorize')

bodyvals = {'client_id': config.client_id,
            'client_secret': config.client_secret,
            'grant_type': 'client_credentials',
            'resource':config.resource_endpoint}

return requests.post(authorize_endpoint, data=bodyvals)

上述代码正常工作,但代表应用程序生成一个令牌。
我似乎找不到一种方法来传递用户的凭证,也没有任何关于这方面的文档。在

一般来说,我不在乎答案是用Python还是Powershell,或者只是一个一般的解释,我只是不明白如何正确地使用AAD。在


Tags: 用户httpsclientidconfigurlsecretlogin
2条回答

您可以手动完成,请参阅我的另一个答案:https://stackoverflow.com/a/40844983/1658906。在

必须使用grant_type=password并调用oauth2/token端点。以下是用于身份验证的C版本:

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

在请求中,您必须指定:

  1. 用户名
  2. 密码
  3. 客户端ID
  4. 客户机密
  5. 资源URI

对于GraphAPI,资源是“https://graph.windows.net/

如果您不想使用ADAL,那么您可以看看使用“resource”的代码。我们已经讨论了这个场景,所以将ADAL作为一个大样本:)

另外,msrestazure有一个UserPassCredentials实例,它也可以在GraphAPI上运行。在

相关问题 更多 >

    热门问题