c# - UserPasswordCredential .Net 标准

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

我想调用图形 API,https://graph.windows.net为此,我正在为 token 使用如下委托(delegate)权限

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 函数。

最佳答案

is there a workaround for this in .net standard?

是的,我们可以使用 rest API 直接获取 token 。

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}

以下是获取access token的demo代码

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 native 应用程序。

关于c# - UserPasswordCredential .Net 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191713/

相关文章:

c# - 从 VS 2012 设置 AutoGenerateColumns 属性

c# - 创建 TreeView 绑定(bind) wpf

c# - .net 中的 JWT 生成和验证抛出 "Key is not supported"

c# - .NET SSLStream : How to extract session key?

powershell - 如何使用 PowerShell 打开 Azure Active Directory OAuth 授权代码授予流程的授权对话框并接收响应

c# - 使用 Microsoft.AspNetCore.Authentication.AzureADB2C.UI 时如何覆盖/替换错误页面处理?

c# - 从 Entity Framework 中删除具有多对多关系的对象?

c# - 如何创建一个结合了CheckedListBox和详细ListView的显示?

c# - 如何使用具有多个属性的集合在 Dapper 中进行过滤?

c# - Azure Functions 中的 Azure AD 身份验证