【问题标题】:UserPasswordCredential .Net StandardUserPasswordCredential .Net 标准
【发布时间】:2018-11-07 14:42:39
【问题描述】:

我想调用图形 api,https://graph.windows.net,因为我正在使用如下授权的令牌

UserPasswordCredential credentials = new UserPasswordCredential("username", "password");
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", "mytenant.onmicrosoft.com"));
var accessToken = authContext.AcquireTokenAsync("https://graph.windows.net", clientId, credentials).Result.AccessToken;

我不是租户管理员,并且在 AAD 中,我无法将特定应用程序添加为应用程序身份验证的所有者。这是在完整的 .net 中工作的,在 .net 标准中是否有解决方法?因为在这种情况下我不能使用应用程序身份验证。

我正在尝试将 webjob 转换为 Azure 函数。

【问题讨论】:

标签: c# .net-core azure-active-directory azure-functions .net-standard


【解决方案1】:

.net 标准中有解决此问题的方法吗?

是的,我们可以使用其余 API 直接获取令牌。

Post  https://login.windows.net/<tenant-id>/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=password
&resource={resource}
&username={username}
&password={password}
&client_id={client-id}

以下是获取访问令牌的演示代码

var tenantId = "xxx.onmicrosoft.com";
var userName = "xxx@xxxx.onmicrosoft.com";
var password = "xxxxxx";
var clientId = "xxxxxxx";
using (HttpClient client = new HttpClient())
            {
                var tokenEndpoint = $"https://login.windows.net/{tenantId}/oauth2/token";
                var accept = "application/json";

                client.DefaultRequestHeaders.Add("Accept", accept);
                string postBody = $"resource=https://graph.windows.net/&client_id={clientId}&grant_type=password&username={userName}&password={password}";
                using (HttpResponseMessage response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
                        var  token = (string)jsonresult["access_token"];
                    }
                }
            }

注意:需要 Azure AD 本机应用程序。

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2016-11-08
    • 2017-10-20
    • 2016-12-27
    • 2019-06-20
    • 2017-03-19
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多