Python 图形API以编程方式作为用户进行身份验证
我正在尝试使用HTTP POST请求获取特定用户OAuth2承载令牌,但似乎没有任何效果Python 图形API以编程方式作为用户进行身份验证,python,powershell,azure,oauth-2.0,Python,Powershell,Azure,Oauth 2.0,我正在尝试使用HTTP POST请求获取特定用户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_secr
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来实现这一点。对于GraphAPI,资源是“” 如果您不想使用,您可以查看一下“资源”使用的代码。这个场景被涵盖了,所以把ADAL看作一个大样本:
另外,还有一个UserPassCredentials实例也可以在GraphAPI上运行。您可以手动执行,请参见我的其他答案: 您必须使用
grant\u 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;
}
}
private异步任务GetAccessToken()
{
字符串tokenEndpointUri=Authority+“oauth2/token”;
var content=newformurlencodedcontent(new[]
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,用户名),
新的KeyValuePair(“密码”,password),
新的KeyValuePair(“客户端id”,客户端id),
新的KeyValuePair(“客户端密码”,ClientSecret),
新的KeyValuePair(“资源”,PowerBiResourceUri)
}
);
使用(var client=new HttpClient())
{
HttpResponseMessage res=wait client.PostAsync(令牌端点URI,内容);
string json=等待res.Content.readasstringsync();
AzureAdTokenResponse tokenRes=JsonConvert.DeserializeObject(json);
返回tokenRes.AccessToken;
}
}
在请求中,您必须指定:
adal用于应用程序身份验证,而不是用户身份验证?adal是用于身份验证的通用库。您可以使用设备代码、用户/通行证、服务主体等广告提供的任何内容。查看ADAL网站了解详细信息。resource=graph.windows.net?嗯,似乎比这更复杂,您知道如何获取响应代码吗?与转到类似URL时得到的类似:此流中不使用授权代码。你直接获得访问令牌。是的,我已经弄明白了,但是如何用代码模拟这个流程呢?如果不模仿浏览器,你为什么要这么做?如果最终结果相同,不是更难吗?:)