繁体   English   中英

需要使用C#Rest调用生成Azure AD承载令牌

[英]Need to generate Azure AD bearer token using C# rest call

我想通过C#REST调用生成Azure AD承载令牌。 我想在API调用中编写用户注册逻辑。 我正在使用它作为令牌端点:

https://login.windows.net/[tenant-id]/oauth2/token

我也跟着中所述相同的步骤文章。

我正在使用的用户凭据是“全局管理员”。

但是我仍然收到“未经授权”错误。 请在下面找到代码段和响应正文-

using (HttpClient client = new HttpClient())
        {
            var tokenEndpoint = @"https://login.windows.net/<tanent-name>/oauth2/token";
            var accept = "application/json";

            client.DefaultRequestHeaders.Add("Accept", accept);
            string postBody = @"resource=https%3A%2F%2Fgraph.microsoft.com%2F
              &client_id=<client-id>
              &grant_type=password
              &username=<admin-user-name>
              &password=<admin-pass>
              &scope=openid";

            using (var 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"];
                    return token;
                }
                else
                    return null;
            }
        }

反应体

{ StatusCode: 401, ReasonPhrase: 'Unauthorized',
  Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Content-Type-Options: nosniff
  x-ms-request-id: cabefe46-ff73-4659-80a2-2f4136200900
  Cache-Control: no-store, no-cache
  P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
  Set-Cookie: esctx=AQABAAAAAADX8GCi6Js6SK82TsD2Pb7...
  Set-Cookie: x-ms-gateway-slice=004; path=/; secure; HttpOnly
  Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
  Server: Microsoft-IIS/10.0
  X-Powered-By: ASP.NET
  Date: Thu, 24 May 2018 13:43:39 GMT
  Content-Length: 457
  Content-Type: application/json; charset=utf-8
  Expires: -1
}}

PS-还请指出是否还有其他方法可以在不执行REST调用的情况下添加新用户。 我不想在客户端应用程序中进行用户注册。

[更新]请找到添加的权限和角色的屏幕快照。 权限和角色

正如汤姆(Tom)所述,您的问题应由用户无权访问您的应用程序引起。

由于您使用的是ROPC授权流程,因此请确保用户是该客户端/ AAD应用的所有者。

您可以将onwer添加到AAD应用程序中:

转到Azure门户> Azure Acitve目录>应用程序注册>应用程序>设置>所有者>添加所有者>选择该用户。

此外,如果用户启用了MFA,则此流程将无效。

让我知道是否有帮助!

还请指出是否还有其他方法可以在不执行REST调用的情况下添加新用户。 我不想在客户端应用程序中进行用户注册。

如果要创建用户,我们可以使用Microsoft.Graph来完成。

在此之前,我们需要注册Azure AD应用程序 并添加Microsoft图形权限。 有关更多详细信息,请参考Create User API

我使用Directory.ReadWrite.All权限对其进行测试。 不要忘记授予权限。

在此处输入图片说明

演示代码。

string graphResourceId = "https://graph.microsoft.com/";
string authority = "https://login.microsoftonline.com/{0}";
string tenantId = "tenant Id";
string clientId = "client Id";
string secret = "secret";
authority = String.Format(authority, tenantId);
AuthenticationContext authContext = new AuthenticationContext(authority);
var accessToken = authContext.AcquireTokenAsync(graphResourceId, new ClientCredential(clientId, secret)).Result.AccessToken;
            var graphserviceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    requestMessage =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                        return Task.FromResult(0);
                    }));
var user = new User
         {
             UserPrincipalName = "tomaccount1@xxxxx.onmicrosoft.com",
             AccountEnabled = true,
             DisplayName = "tom1",
             PasswordProfile = new PasswordProfile
             {
                 ForceChangePasswordNextSignIn = true,
                 Password = "1234qweA!@#$%6"
             },
              MailNickname = "tomaccount1"
            };
 var addUserResult = graphserviceClient.Users.Request().AddAsync(user).Result;

测试结果:

在此处输入图片说明

从Azure AD检查

在此处输入图片说明

Packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Graph" version="1.9.0" targetFramework="net471" />
  <package id="Microsoft.Graph.Core" version="1.9.0" targetFramework="net471" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.19.4" targetFramework="net471" />
  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net471" />
  <package id="System.IO" version="4.3.0" targetFramework="net471" />
  <package id="System.Net.Http" version="4.3.3" targetFramework="net471" />
  <package id="System.Runtime" version="4.3.0" targetFramework="net471" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net471" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net471" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net471" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="net471" />
</packages>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM