Azure AD PostAuthentication add claims

强颜欢笑 提交于 2019-12-10 14:25:26

问题


I am using Azure AD to authenticate the users. I want to add few user claims specific to my application. Should I do it in Application_PostAuthenticateRequest` in global.asax ?. Is there a way I can cache my claims too ?


回答1:


If you are using the ASP.NET OWIN middleware, there are specific notifications you can use for that purpose. Claims added in that way will end up in your session cookie, so that you won't have to repeat the claims augmentation logic in subsequent calls. See 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/ for details.




回答2:


BTW you can add your custom cliams but you cannot override the existing claims added by the Azure AD (what i have seen so far might be i am wrong). what you can do is to add the new cliams like this

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);
                     }`

and then you can get the claim anywhere in controller like

@{ 
    var claimsIdentity = User.Identity as System.Security.Claims.ClaimsIdentity;

    if (claimsIdentity != null)
    {
        var c = claimsIdentity.FindFirst("customClaim").Value;
    }
}



回答3:


You can augment the claims programmatically like this:

    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");

    }

This solution relies on AuthenticationAsync method of AuthenticationManager to retrieve the original AuthenticationProperties. After retrieving the properties, call the SignIn method to persist the new ClaimsIdentity in the auth cookie.




回答4:


If you're making use of:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
      ...

This is how I managed to add additional custom claims using 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;
      }
    }
  }
});

For a full sample, check this blog post.



来源:https://stackoverflow.com/questions/33682771/azure-ad-postauthentication-add-claims

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!