【问题标题】:Graph API authenticate as a user programmatically图形 API 以编程方式作为用户身份验证
【发布时间】:2017-04-30 04:43:34
【问题描述】:

我正在尝试使用 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_secret': config.client_secret,
            'grant_type': 'client_credentials',
            'resource':config.resource_endpoint}

return requests.post(authorize_endpoint, data=bodyvals)

上述代码有效,但代表应用程序生成一个令牌。
我似乎找不到传递用户凭据的方法,也没有任何相关文档。

通常我不在乎答案是用 Python 还是 Powershell 或只是一般解释,我只是似乎不明白如何使用 AAD 正确地做到这一点。

【问题讨论】:

    标签: python powershell azure oauth-2.0


    【解决方案1】:

    您可以手动完成,请在此处查看我的其他答案: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

    【讨论】:

    • 资源 = graph.windows.net?
    • hm,看起来比这更复杂,你知道如何获取响应码吗?类似于您访问类似 URL 时得到的结果:login.microsoftonline.com/common/oauth2/v2.0/…
    • 此流程中未使用授权码。您直接获得访问令牌。
    • 是的,我已经想通了,但是如何用代码模拟这个流程呢?好吧,不用模拟浏览器
    • 为什么需要这样做?相同的最终结果不是更难吗? :)
    【解决方案2】:

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

    如果您不想使用ADAL,则可以查看“资源”的使用代码。此场景已涵盖,因此请将 ADAL 视为一个大样本:)

    另外,msrestazure 有一个 UserPassCredentials 实例,它也适用于 GraphAPI。

    【讨论】:

    • adal 用于应用程序身份验证,而不是用户身份验证?
    • ADAL 是用于身份验证的通用库。无论 AD 提供什么,您都可以使用设备代码、用户/密码、服务主体等。有关详细信息,请参阅 ADAL 网站。
    猜你喜欢
    • 2017-08-15
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多