首页 文章

如果已经过身份验证,请获取Azure AD图表令牌

提问于
浏览
1

我是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 回答

  • 1

    如果令牌为null,则用户需要重新授权 . 如code sample所示,您可以使用try catch语句来处理异常:

    try
                {
    
                }
                catch (Exception e)
                {                        
                    //
                    // The user needs to re-authorize.  Show them a message to that effect.
                    //
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    return View(userList);
                }
    

    向用户显示消息(例如,用户视图文件夹中的Index.cshtml):

    @if (ViewBag.ErrorMessage == "AuthorizationRequired")
    {
        <p>You have to sign-in to see Users. Click @Html.ActionLink("here", "Index", "Users", new { reauth = true }, null) to sign-in.</p>
    }
    

    如果您想直接发送OpenID Connect登录请求以获取一组新令牌而不是向用户显示错误消息,您可以使用:

    catch (Exception e)
                {
                  ....
    
                 HttpContext.GetOwinContext()
                    .Authentication.Challenge(new AuthenticationProperties {RedirectUri = "/"},
                        OpenIdConnectAuthenticationDefaults.AuthenticationType);
                   .....
                }
    

    如果用户仍与Azure AD进行有效会话,则不会提示他们提供凭据 . 在处理登录响应后,OpenID Connect中间件将返回当前控制器 .

相关问题