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

时间:2018-05-24 13:58:22

标签: c# azure azure-active-directory bearer-token azure-security

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

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

我遵循this文章中描述的相同程序。

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

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

代码

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
}}

P.S .- 另请指出是否有其他方式添加新用户而不进行REST调用。我不想在客户端应用程序中进行用户注册。

[更新]请查看添加的权限和角色的屏幕截图。 Permissions and Roles

2 个答案:

答案 0 :(得分:0)

正如汤姆所说,你的问题应该是因为用户没有你的应用程序的许可。

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

您可以在AAD应用中添加onwer:

转到Azure门户&gt; Azure Acitve目录&gt;申请注册&gt;该应用&gt;设置&gt;业主&gt;添加所有者&gt;选择该用户。

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

让我知道它是否有帮助!

答案 1 :(得分:0)

  

另请指出是否有任何其他方式添加新用户而不进行REST调用。我不想在客户端应用程序中进行用户注册。

如果您想创建用户,我们可以使用Microsoft.Graph来执行此操作。

在此之前我们需要registry the Azure AD application。并添加Microsoft图表权限。有关详细信息,请参阅Create User API

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

enter image description here

演示代码。

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;

测试结果:

enter image description here

从Azure AD检查

enter image description here

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>