我是Azure AD Graph和身份验证过程的新手 . 我能够使用Azure AD Graph客户端合并单一登录,如本例中使用.NET MVC应用程序所示:https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web
我的困境是,即使我已经对我的会话进行了身份验证,它仍然要求我再次登录以执行下面控制器中的操作:
public ActionResult Test()
{
if (Request.QueryString["reauth"] == "True")
{
//Send an OpenID Connect sign -in 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);
}
// Access the Azure Active Directory Graph Client
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
// Obtain the current user's AD objectId
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Query and obtain the current user object from the Azure AD Graph Client
User user = (User)client.Users.
Where(u => u.ObjectId
.Equals(userObjectID, StringComparison.CurrentCultureIgnoreCase)).
ExecuteSingleAsync().
Result;
// Get the employee Id from Azure AD (via a directory extension)
IReadOnlyDictionary<string, object> extendedProperty = user.GetExtendedProperties();
object extendedProp = extendedProperty["extension_ExtensionId_employeeID"];
// Hash the employee Id
var empId = PasswordHash.ArgonHashString(extendedProp.ToString(), PasswordHash.StrengthArgon.Moderate);
// Send to the view for testing only
ViewBag.EmployeeName = user.DisplayName;
ViewBag.EmployeeEmail = user.Mail;
ViewBag.EmployeeId = empId;
return View();
}
我得到的错误是:
“/”应用程序授权中的服务器错误
在黄色框中使用以下代码行:
Line 22: if (token == null || token.IsEmpty())
Line 23: {
Line 24: throw new Exception("Authorization Required.");
Line 25: }
Line 26: return token;
由于我对身份验证部分还不熟悉,因此我需要一些关于如何获取当前会话令牌的指导,以便我不会收到此错误 .
我正在使用Azure AD Graph,因为我在Azure中获得了一个特定的目录扩展,我无法通过Microsoft Graph获取(目前基于我目前的截止日期) .
任何建议都会有所帮助 .
1 回答
如果令牌为null,则用户需要重新授权 . 如code sample所示,您可以使用try catch语句来处理异常:
向用户显示消息(例如,用户视图文件夹中的Index.cshtml):
如果您想直接发送OpenID Connect登录请求以获取一组新令牌而不是向用户显示错误消息,您可以使用:
如果用户仍与Azure AD进行有效会话,则不会提示他们提供凭据 . 在处理登录响应后,OpenID Connect中间件将返回当前控制器 .