HTTP 401 unauthorized ASP.NET Core Web API microservices

46 views Asked by At

I create two services in an ASP.NET Core Web API. One service is for Identity and generates a JWT token.

The second service gets the JWT token from Identity. These two services are connected using http.

This is the code from the second service which gets the JWT token from the Identity service

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["IdentityServiceUrl"];
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters.ValidateAudience = false;
        options.TokenValidationParameters.NameClaimType = "username";
        options.Configuration = new OpenIdConnectConfiguration();
    });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();
[Authorize]
[HttpPut("create-age-category")]
public async Task<ActionResult> CreateAgeCategory(AgeCategoryDto ageCategory)
{
    try
    {
        await _ageCategoryService.CreateAgeCategory(ageCategory);
        return Ok("success");
    }
    catch (Exception ex)
    {
        return BadRequest(ex);
    }
}

This is the part where I generate JWT token(IdentityService)

var key = Encoding.ASCII.GetBytes(builder.Configuration.GetSection("JwtConfig:Secret").Value);
var tokenValidationParams = new TokenValidationParameters()
{
  ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(key),
    ValidateIssuer = false, //for dev
    ValidateAudience = false, //for dev
    RequireAudience = false, //for dev -- needs to be updated when refresh token is added
    ValidateLifetime = true
};

builder.Services.AddAuthentication(options => {
  options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
  .AddJwtBearer(jwt => {
    jwt.SaveToken = true;
    jwt.TokenValidationParameters = tokenValidationParams;
  });
            ...........
app.UseAuthentication();
app.UseAuthorization();

When I try to access this private root, I get a http 401 unauthorized error, even though I sent the token in the authorize tab in Postman.

I'm new to micro services I don't know where to start to fix this issue.

First I change both service's url to http and I still receive the http 401.

This is how I send request to PostMan enter image description here

0

There are 0 answers