【问题标题】:Azure AD PostAuthentication add claimsAzure AD PostAuthentication 添加声明
【发布时间】:2016-02-14 10:42:20
【问题描述】:

我正在使用 Azure AD 对用户进行身份验证。我想添加一些特定于我的应用程序的用户声明。我应该在 global.asax 的 Application_PostAuthenticateRequest 中执行吗?有没有办法也可以缓存我的声明?

【问题讨论】:

  • 您能简单介绍一下您的应用吗?你用的是WIF吗?您如何获取和验证令牌?

标签: azure access-token azure-active-directory azure-ad-graph-api


【解决方案1】:

如果您使用的是 ASP.NET OWIN 中间件,则可以使用特定的通知来实现此目的。以这种方式添加的声明将最终出现在您的会话 cookie 中,这样您就不必在后续调用中重复声明扩充逻辑。详情请见http://www.cloudidentity.com/blog/2015/08/26/augmenting-the-set-of-incoming-claims-with-the-openid-connect-and-oauth2-middleware-in-katana-3-x/

【讨论】:

    【解决方案2】:

    顺便说一句,您可以添加自定义 cliams,但不能覆盖 Azure AD 添加的现有声明(到目前为止我所看到的可能是我错了)。你可以做的是像这样添加新的cliams

    AuthorizationCodeReceived = context =>
                         {
                             List<System.Security.Claims.Claim> allcustomClaims = new List<System.Security.Claims.Claim>();
                             allcustomClaims.Add(new System.Security.Claims.Claim("customClaim", "YourDefindedValue"));
                             context.AuthenticationTicket.Identity.AddClaims(allcustomClaims);
                             return Task.FromResult(0);
                         }`
    

    然后您就可以在控制器中的任何位置获取声明,例如

    @{ 
        var claimsIdentity = User.Identity as System.Security.Claims.ClaimsIdentity;
    
        if (claimsIdentity != null)
        {
            var c = claimsIdentity.FindFirst("customClaim").Value;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以像这样以编程方式扩充声明:

          public async Task<ActionResult> AuthenticateAsync()
          {
              ClaimsPrincipal incomingPrincipal = System.Threading.Thread.CurrentPrincipal as ClaimsPrincipal;
              if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
              {
                  ClaimsIdentity claimsIdentity = incomingPrincipal.Identity as ClaimsIdentity;
      
                  if (!claimsIdentity.HasClaim(ClaimTypes.Role, "Admin"))
                  {
                      claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "AADGuide"));
                      var ctx = Request.GetOwinContext();
                      var authenticationManager = ctx.Authentication;
      
                      AuthenticateResult authResult = await authenticationManager.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
                      authenticationManager.SignIn(authResult.Properties,claimsIdentity);
                  }
      
              }
              return RedirectToAction("Index", "Start");
      
          }
      

      此解决方案依赖 AuthenticationManager 的AuthenticationAsync 方法来检索原始AuthenticationProperties。检索到属性后,调用SignIn 方法将新的 ClaimsIdentity 持久化到 auth cookie 中。

      【讨论】:

        【解决方案4】:

        如果您正在使用:

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
              ...
        

        这就是我设法使用new OAuthBearerAuthenticationProvider 添加其他自定义声明的方式:

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
          // The id of the client application that must be registered in Azure AD.
          TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId },
          // Our Azure AD tenant (e.g.: contoso.onmicrosoft.com).
          Tenant = tenant,
          Provider = new OAuthBearerAuthenticationProvider
          {
            // In this handler we can perform additional coding tasks...
            OnValidateIdentity = async context =>
            {
              try
              {
                // Retrieve user JWT token from request.
                var authorizationHeader = context.Request.Headers["Authorization"].First();
                var userJwtToken = authorizationHeader.Substring("Bearer ".Length).Trim();
        
                // Get current user identity from authentication ticket.
                var authenticationTicket = context.Ticket;
                var identity = authenticationTicket.Identity;
        
                // Credential representing the current user. We need this to request a token
                // that allows our application access to the Azure Graph API.
                var userUpnClaim = identity.FindFirst(ClaimTypes.Upn);
                var userName = userUpnClaim == null
                  ? identity.FindFirst(ClaimTypes.Email).Value
                  : userUpnClaim.Value;
                var userAssertion = new UserAssertion(
                  userJwtToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
        
                  identity.AddClaim(new Claim(identity.RoleClaimType, "myRole"));
              }
              catch (Exception e)
              {
                throw;
              }
            }
          }
        });
        

        如需完整样本,请查看blog post

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 2020-10-21
          相关资源
          最近更新 更多