简体   繁体   English

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

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

I want to generate a Azure AD bearer token via C# REST call. 我想通过C#REST调用生成Azure AD承载令牌。 I want to write the user registration logic inside an API call. 我想在API调用中编写用户注册逻辑。 I am using this as token endpoint : 我正在使用它作为令牌端点:

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

I followed the same procedure as described in this article. 我也跟着中所述相同的步骤文章。

The user credential I am using is a "Global Administrator". 我正在使用的用户凭据是“全局管理员”。

But I am still getting 'Unauthorized' error. 但是我仍然收到“未经授权”错误。 Please find the code snippet and response body below- 请在下面找到代码段和响应正文-

Code

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

Response Body 反应体

{ 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- Also please point out if there is any other way of adding new user without doing the REST call. PS-还请指出是否还有其他方法可以在不执行REST调用的情况下添加新用户。 I don't want to have user registration in the client application. 我不想在客户端应用程序中进行用户注册。

[Update] Please find the screenshot of added permissions and roles. [更新]请找到添加的权限和角色的屏幕快照。 权限和角色

As Tom mentioned, your issue shoud be caused by the user doesn't have permission to your App. 正如汤姆(Tom)所述,您的问题应由用户无权访问您的应用程序引起。

Since you're using ROPC grant flow, make sure that the user is the owner of that Client/AAD App. 由于您使用的是ROPC授权流程,因此请确保用户是该客户端/ AAD应用的所有者。

You can add onwer to the AAD app: 您可以将onwer添加到AAD应用程序中:

Go to Azure portal > Azure Acitve Directory > Application Registration > The App > Settings > Owners > Add owner > Select that user. 转到Azure门户> Azure Acitve目录>应用程序注册>应用程序>设置>所有者>添加所有者>选择该用户。

Additonal, if the user has enabled MFA, this flow won't work. 此外,如果用户启用了MFA,则此流程将无效。

Let me know if it helps! 让我知道是否有帮助!

Also please point out if there is any other way of adding new user without doing the REST call. 还请指出是否还有其他方法可以在不执行REST调用的情况下添加新用户。 I don't want to have user registration in the client application. 我不想在客户端应用程序中进行用户注册。

If you want to create user, we could use the Microsoft.Graph to do that. 如果要创建用户,我们可以使用Microsoft.Graph来完成。

Before that we need to registry the Azure AD application . 在此之前,我们需要注册Azure AD应用程序 And add the Microsoft graph permission. 并添加Microsoft图形权限。 For more details we could refer to the Create User API . 有关更多详细信息,请参考Create User API

I test it with Directory.ReadWrite.All permission. 我使用Directory.ReadWrite.All权限对其进行测试。 Don't forget to Grant permissions. 不要忘记授予权限。

在此处输入图片说明

Demo code. 演示代码。

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;

Test Result: 测试结果:

在此处输入图片说明

Check from Azure AD 从Azure AD检查

在此处输入图片说明

Packages.config 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