3

In an ASP.NET Core 3 application, I need to process information from id_token along with access_token.

The id_token has membership information that is sometimes required to build a policy. Since the membership information can be large, making it part of the access_token is not possible (token exceeds maximum allowed size).

The clients send id_token in x-id-token header and I am looking for a way to extract it and use the claims within.

Right now I have JwtBearer auth configured which works seamlessly with Authorization: Bearer access_token header.

public void ConfigureServices(IServiceCollection services) {
      services.AddAuthentication(options =>
      {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
      })
      .AddJwtBearer(options =>
      {
        options.Authority = $"https://{Configuration["auth:Domain"]}/";
        options.Audience = Configuration["auth:Audience"];
      });
...
}
nilobarp
  • 3,190
  • 2
  • 23
  • 32
  • Looks like you need to create a custom auth. Please see an example https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core – Basil Kosovan Nov 18 '19 at 14:38
  • 1
    @BasilKosovan thanks for pointing me towards the solution. – nilobarp Nov 19 '19 at 06:27

1 Answers1

3

AS stated in the question, I needed a step in authorization flow to validate id_token and a membership_id supplied in custom headers. I ended up creating a custom auth requirement handler in the following form

  internal class MembershipRequirement : AuthorizationHandler<MembershipRequirement>, IAuthorizationRequirement
  {
    public MembershipRequirement(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MembershipRequirement requirement)
    {
      var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
      string idToken = authFilterCtx.HttpContext.Request.Headers["x-id-token"];
      string membershipId = authFilterCtx.HttpContext.Request.Headers["x-selected-membership-id"];

      if (idToken != null && membershipId != null)
      {
        var identity = ValidateIdToken(idToken).Result;

        if (identity != null)
        {
          var subscriptions = identity.Claims.ToList().FindAll(s => s.Type == "https://example.com/subs").ToList();
          var assignments = subscriptions.Select(s => JsonSerializer.Deserialize<Subscription>(s.Value)).ToList();

          var membership = assignments.Find(a => a.id == membershipId);

          if (membership != null)
          {
            // assign the id token claims to user identity
            context.User.AddIdentity(new ClaimsIdentity(identity.Claims));

            context.Succeed(requirement);
          }
          else { context.Fail(); }
        }
        else
        {
          context.Fail();
        }
      }

      return Task.FromResult<object>(null);
    }

    private async Task<ClaimsPrincipal> ValidateIdToken(string token)
    {
      try
      {
        IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"https://{Configuration["Auth:Domain"]}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
        OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);

        TokenValidationParameters validationParameters =
                      new TokenValidationParameters
                      {
                        IssuerSigningKeys = openIdConfig.SigningKeys,
                        ValidateIssuer = false,
                        ValidateAudience = false
                      };

        var validator = new JwtSecurityTokenHandler();
        SecurityToken validatedToken;
        var identity = validator.ValidateToken(token, validationParameters, out validatedToken);

        return identity;

      }
      catch (Exception e)
      {
        Console.Writeline($"Error occurred while validating token: {e.Message}");
        return null;
      }
    }
  }

  internal class Subscription
  {
    public string name { get; set; }
    public string id { get; set; }
  }

Then in the public void ConfigureServices(IServiceCollection services) method added a policy to check for membership in the id_token

      services.AddAuthorization(options =>
      {
        options.AddPolicy("RequiredCompanyMembership", policy => policy.Requirements.Add(new MembershipRequirement(Configuration)));
      });

For us, this policy is globally applied for all Authorized endpoints.

nilobarp
  • 3,190
  • 2
  • 23
  • 32