1

Project: .net core 2.1 APIs

In my project I have a requirement to include 2 JWT bearer authentication.

a) We create token JWT internally and use it for authentication

b) We get JWT token from external third party and need to get this authenticated as well.

I tried following code in start up:

 services.AddAuthentication( )
 .AddJwtBearer("InteralBearer", options =>
 {
     SymmetricSecurityKey key = TokenGenerator.GenerateKey();
     options.Audience = "***************";
     options.TokenValidationParameters = new TokenValidationParameters
     {
         ValidateIssuer = true,
         ValidIssuer = "***************",
         ValidateAudience = true,
         ValidAudience = "***************",
         ValidateIssuerSigningKey = true,
         IssuerSigningKey = key,
         ValidateLifetime = true
     };
 })
 .AddJwtBearer("ExternalBearer", options =>
 {
     options.Audience = "***************";
     options.Authority = "***************";
 });



services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("ExternalBearer", "InteralBearer")
.Build();

options.AddPolicy("Applicant", new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .AddAuthenticationSchemes("ExternalBearer", "InteralBearer")
    .RequireClaim("role", "Applicant")
    .Build());
});

In my controller I have:

[ApiController]
[Authorize(Policy = "Applicant")]
public class ApplicantController : ApplicantAbstract
{
}

I also have custom autorization filter:

public class SelfAuthorizationFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        ClaimsPrincipal principal = context.HttpContext.User;
        ........
    }
}

When I above set up, issue is, context.HttpContext.User does not return any claims as part of "Identity" object in the request. I am expecting "Claims" object to have different claims which is already configured.

Every thing works fine if I have either "InternalBearer" or "ExternalBearer", but not both.

What am I doing wrong here?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Create a controller where you validate the token from external party then swap that token for your API token. – fuzzybear Feb 20 '19 at 23:12
  • Please leave good edits as they are, Madhukar. – halfer Apr 02 '20 at 09:20
  • Possible answer: https://stackoverflow.com/questions/46990509/how-to-set-multiple-audiences-in-asp-net-core-2-0-addjwtbearer-middleware – elfico May 13 '21 at 04:22

0 Answers0