Sabby62
Sabby62

Reputation: 1717

Azure AD PostAuthentication add claims

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 ?

Upvotes: 6

Views: 3807

Answers (4)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102448

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.

Upvotes: 0

Mian Almas
Mian Almas

Reputation: 174

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

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52867

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.

Upvotes: 0

vibronet
vibronet

Reputation: 7394

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.

Upvotes: 5

Related Questions