Azure AD PostAuthentication add claims
Asked Answered
S

4

6

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 ?

Stuckup answered 12/11, 2015 at 22:38 Comment(1)
Can you tell a little bit about your app. Are you using WIF? How are you getting and validating the token?Harpsichord
R
5

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.

Rodneyrodolfo answered 16/11, 2015 at 18:4 Comment(0)
Y
1

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;
    }
}
Yeomanly answered 17/7, 2017 at 12:36 Comment(0)
S
0

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.

Stannum answered 1/8, 2017 at 3:41 Comment(0)
N
0

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.

Newmark answered 6/6, 2019 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.