首页 > 解决方案 > 在我的 NetCore 应用程序中添加 AzureAD 用户时出错?

问题描述

.net Core WebApp 的新手,我正在尝试利用下面的代码,但在尝试检查用户时出现错误。我检查了两次,第一次使用存在的帐户

这是代码...

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JBSTestAdLoginVSApp.Controllers
{
    public class NewAccountController : Controller
    {
        public IActionResult Index()
        //public String Index()
        {
            return View();
            //return "This is my default action...";
        }
        [HttpPost]
        public async void Index(string userPrincipal, string displayName, string mailNickName, string password)
        {
            ViewBag.Name = string.Format("Name: {0} {1} {2} {3}", userPrincipal, displayName, mailNickName, password);
            await Test();
            return;// View();
        }
        private static async Task<string> AppAuthenticationAsync()
        {
            //  Constants
            var tenant = "**************.onmicrosoft.com";  //grabbed from Azure AD
            var resource = "https://graph.microsoft.com/";
            var clientID = "62***********";  //created app and grand read write perms
            var secret = "******";  //added secret to app id

            //  Ceremony
            var authority = $"https://login.microsoftonline.com/{tenant}";
            var authContext = new AuthenticationContext(authority);
            var credentials = new ClientCredential(clientID, secret);
            var authResult = await authContext.AcquireTokenAsync(resource, credentials);

            return authResult.AccessToken;
        }
        private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user)
        {
            try
            {
                var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}");//fails here with Exception thrown: 'System.Net.Http.HttpRequestException' in System.Private.CoreLib.dll

                return true;
            }
            catch (HttpRequestException)
            {
                return false;
            }
        }
        private static async Task<string[]> GetUserGroupsAsync(HttpClient client, string user)
        {
            var payload = await client.GetStringAsync(
                $"https://graph.microsoft.com/v1.0/users/{user}/memberOf");
            var obj = JsonConvert.DeserializeObject<JObject>(payload);
            var groupDescription = from g in obj["value"]
                                   select g["displayName"].Value<string>();

            return groupDescription.ToArray();
        }
        private static async Task CreateUserAsync(HttpClient client, string user, string domain)
        {
            using (var stream = new MemoryStream())
            using (var writer = new StreamWriter(stream))
            {
                var payload = new
                {
                    accountEnabled = true,
                    displayName = user,
                    mailNickname = user,
                    userPrincipalName = $"{user}@{domain}",
                    passwordProfile = new
                    {
                        forceChangePasswordNextSignIn = true,
                        password = "tempPa$$w0rd"
                    }
                };
                var payloadText = JsonConvert.SerializeObject(payload);

                writer.Write(payloadText);
                writer.Flush();
                stream.Flush();
                stream.Position = 0;

                using (var content = new StreamContent(stream))
                {
                    content.Headers.Add("Content-Type", "application/json");

                    var response = await client.PostAsync("https://graph.microsoft.com/v1.0/users/", content);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new InvalidOperationException(response.ReasonPhrase);
                    }
                }
            }
        }
        private static async Task Test()
        {
            //var token = await AppAuthenticationAsync();

            var token = await AppAuthenticationAsync();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                var userA = "Test@*****.onmicrosoft.com";//this account exists
                var userExistA = await DoesUserExistsAsync(client, userA);

                var user = "NewUser1@********.onmicrosoft.com";//this account doesnt
                var userExist = await DoesUserExistsAsync(client, user);

                Console.WriteLine($"Does user exists?  {userExist}");

                if (userExist)
                {
                    var groups = await GetUserGroupsAsync(client, user);

                    foreach (var g in groups)
                    {
                        Console.WriteLine($"Group:  {g}");
                    }


                } else
                {
                    await CreateUserAsync(client, "newuser", "******.onmicrosoft.com");
                }
            }
        }
    }
}

不确定我是否正确创建了应用程序注册,因为当 DoesUserExistsAsync 运行时它会抛出异常:System.Private.CoreLib.dll 中的“System.Net.Http.HttpRequestException”

当我为应用程序 权限分配权限时

请注意,该应用程序说读写目录数据“未授予默认目录”,我使用的是默认目录,这是问题吗?

标签: asp.net-coreazure-ad-graph-api

解决方案


授予应用程序权限后,您必须单击默认目录按钮的授予管理员同意。否则将不起作用,如果您不同意,则图形 api 权限将无权读取任何用户。

在此处输入图像描述

如果用户不存在,这是正确的行为,因为如果您没有成功,则会调用 httprequestexception,例如 404 .. 如果您尝试使用不存在的用户点击图形端点,它将返回 404,这将触发如您所见,httpexception。此外,如果您没有读取所有用户的权限(因为您没有同意),那么它将表现得好像什么也没找到,这将再次返回 404。

一旦您同意该组织并搜索存在的用户,它应该返回 true。


推荐阅读