Rya*_*ite 3 c# asp.net azure azure-active-directory azure-web-app-service
我是 Azure 的新手,我正在使用 ASP.NET MVC 4 模板项目。
我的目标是将 Azure AD 中的所有用户提取到一个可枚举列表中,然后我可以在以后进行搜索。
目前,我收到此错误:
Server Error in '/' Application
Object reference not set to an instance of an object
...
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
或者这个,取决于.Where(...)我注释掉的条款:
The token for accessing the Graph API has expired. Click here to sign-in and get a new access token.
单击链接调用此 URL:
https://login.microsoftonline.com/<MY TENANT GUID>/oauth2/authorize?client_id=<MY APP ID>&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%<Bunch of alphanumeric gibberish>&nonce=<More alphanumeric gibberish>-client-SKU=ID_NET&x-client-ver=1.0.40306.1554
单击该链接会尝试一些操作,但只会让我返回同一页面并出现相同的错误,并且不会执行任何其他操作。
用户配置文件控制器.cs
private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private string graphResourceID = "https://graph.windows.net";
public async Task<Collection<IUser>> GetAllUsers()
{
var userList = new Collection<IUser>();
try
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await GetTokenForApplication());
// use the token for querying the graph to get the user details
var result = await activeDirectoryClient.Users
//.Where(u => u.JobTitle.Equals("Cool Dudes")) // Works fine when uncommented, otherwise gives me a server error
.ExecuteAsync();
while (result.MorePagesAvailable)
{
userList = userList.Concat(result.CurrentPage.ToList()) as Collection<IUser>;
await result.GetNextPageAsync();
}
}
catch (Exception e)
{
if (Request.QueryString["reauth"] == "True")
{
// Send an OpenID Connect sign-on request to get a new set of tokens.
// If the user still has a valid session with Azure AD, they will not
// be prompted for their credentials.
// The OpenID Connect middleware will return to this controller after
// the sign-in response has been handled.
HttpContext.GetOwinContext()
.Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
return userList;
}
return userList;
}
public async Task<ActionResult> Admin()
{
try
{
var user = await GetAllUsers();
return View(user
//.Where(u => u.JobTitle.Equals("Cool Dudes")) // When this is uncommented and the one in GetAllUsers is commented out, I get an error saying "The token for accessing the Graph API has expired. Click here to sign-in and get a new access token."
);
}
catch (AdalException)
{
// Return to error page.
return View("Error");
}
// if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/UserProfile" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
public async Task<string> GetTokenForApplication()
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return authenticationResult.AccessToken;
}
Run Code Online (Sandbox Code Playgroud)
管理.cshtml
@using Microsoft.Azure.ActiveDirectory.GraphClient
@model IEnumerable<IUser>
@{
ViewBag.Title = "Admin";
}
<h2>@ViewBag.Title.</h2>
<table class="table table-bordered table-striped">
@foreach (var user in Model)
{
<tr>
<td>Display Name</td>
<td>@user.DisplayName</td>
<td>Job Title</td>
<td>@user.JobTitle</td>
</tr>
}
</table>
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?我的while循环逻辑错了吗?我是否可能使用现在过时的方式来阅读这些信息?是权限问题吗?
编辑:
缩小范围:
GetAllUsers(和可选Admin)有Where子句时,Admin返回一个空页,但没有错误Admin有Where条款,则返回一个错误图Where子句时,返回服务器错误所以我认为GetAllUsers没有正确返回数据。
根据Jonathan Huss 的这篇博文,我能够将这部分代码从项目Azure AD Graph API中的默认值转换为更新的Microsoft Graph API
在我的 Models 文件夹中(可能放在 Utility 文件夹或其他东西中),我添加了以下代码:
AzureAuthenticationProvider.cs
using System.Configuration;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace <PROJECT_NAME>.Models
{
class AzureAuthenticationProvider : IAuthenticationProvider
{
private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
// get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential creds = new ClientCredential(clientId, appKey);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
}
}
}
Run Code Online (Sandbox Code Playgroud)
回到UserProfileController.cs我们有:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient; // Will eventually be removed
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using <PROJECT_NAME>.Models;
using Microsoft.Graph;
using User = Microsoft.Graph.User; // This is only here while I work on removing references to Microsoft.Azure.ActiveDirectory.GraphClient
namespace <PROJECT_NAME>.Controllers
{
[Authorize]
public class UserProfileController : Controller
{
public async Task<List<User>> GetAllUsers()
{
List<User> userResult = new List<User>();
GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().Top(500).GetAsync(); // The hard coded Top(500) is what allows me to pull all the users, the blog post did this on a param passed in
userResult.AddRange(users);
while (users.NextPageRequest != null)
{
users = await users.NextPageRequest.GetAsync();
userResult.AddRange(users);
}
return userResult;
}
// Return all users from Azure AD as a proof of concept
public async Task<ActionResult> Admin()
{
try
{
var user = await GetAllUsers();
return View(user
);
}
catch (AdalException)
{
// Return to error page.
return View("Error");
}
// if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我原帖中的RefreshSession和GetTokenForApplication方法仍然存在,但AzureAuthenticationProvider在我重新编写代码时可能会被类替换
最后在Admin.cshtml中做了一个小改动,我改了
@using Microsoft.Azure.ActiveDirectory.GraphClient
@model IEnumerable<IUser>
Run Code Online (Sandbox Code Playgroud)
到
@using Microsoft.Graph
@model List<User>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6821 次 |
| 最近记录: |