asp.net-core - 在我的 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”
当我为应用程序 权限分配权限时
请注意,该应用程序说读写目录数据“未授予默认目录”,我使用的是默认目录,这是问题吗?
解决方案
推荐阅读
- laravel - Laravel 面包屑有问题
- angularjs - 我可以同时运行一个 AngularJS 组件和一个 Angular 组件吗?
- python - wxpython中的按钮和刷新显示区域
- jquery - JQuery 只返回包含特定字符串的值
- git - Git:从master中删除以前合并的提交
- javascript - 如何将数组数据绑定到选择选项
- html - H1标签隐藏在滚动固定背景
- python - 如何在 Python 中对原始二进制数据使用按位运算符进行 CRC 检查?
- java - MPAndroid 图表库,通过 setValueFormatter 设置标签时遇到问题
- python-3.x - 使用python删除csv文件相同行上的相同值