0

Startup.cs:

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = jwtSettings.Issuer,
            ValidAudience = jwtSettings.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key)),
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
        };
    });

app.UseMiddleware<ErrorHandlerMiddleware>();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(options =>
        {
            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
            }
        });
    }

    app.UseCors();
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

Token generation:

    string CreateToken()
    {
        var jwtSettings = configuration.GetSection(nameof(AppSettings.Jwt)).Get<AppSettings.Jwt>();

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key));

        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Name, loginDto.Username)

        };

        var jwtSecurityToken = new JwtSecurityToken(
            expires: DateTime.Now.AddMinutes(30),
            claims: claims,
            signingCredentials: credentials,
            issuer: jwtSettings.Issuer,
            audience: jwtSettings.Audience);

        var jwt = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return jwt;
    }

Controller:

[ApiController]
[ApiVersion("1.0")]
[Route("api/[controller]")]
public class CustomerEnvironmentsController : ControllerBase
{
    #region Fields

    private readonly ICustomerEnvironmentsRepository customerEnvironmentsRepository;
    private readonly IMapper mapper;
    private readonly IDtoValidatorFactory apiValidatorFactory;
    private readonly IHttpHeaderParser httpHeaderParser;

    #endregion

    #region Constructor

    public CustomerEnvironmentsController(ICustomerEnvironmentsRepository customerEnvironmentsRepository, IMapper mapper, IDtoValidatorFactory apiValidatorFactory, IHttpHeaderParser httpHeaderParser)
    {
        this.customerEnvironmentsRepository = customerEnvironmentsRepository ?? throw new ArgumentNullException(nameof(customerEnvironmentsRepository));
        this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        this.apiValidatorFactory = apiValidatorFactory ?? throw new ArgumentNullException(nameof(apiValidatorFactory));
        this.httpHeaderParser = httpHeaderParser ?? throw new ArgumentNullException(nameof(httpHeaderParser));
    }

    #endregion

    [Authorize]
    [HttpGet]
    public async Task<ActionResult<List<CustomerEnvironmentDto>>> GetCustomerEnvironments()
    {
        //Ommitted
    }
}

And I only want this for specific endpoints so I've added [Authorize] only on one endpoint. I've tried setting my token as auth in swagger, and I've also tried manually sending my token from an external app with an Authorization header with value bearer token.

I just don't know what else to check.

schh
  • 311
  • 3
  • 16
  • I'd start with loosening all the requirements you specify for your token validation parameters, you set everything to `true` and one of there possibly fails. – Wiktor Zychla Jun 27 '23 at 09:34
  • iveset all of them to false aswell, no change. And i know the issuer, audience and key are these same when creating my token. – schh Jun 27 '23 at 09:43
  • I don't see any claims added to your token in `CreateToken`. You can try to [follow one of my tutorials](https://www.wiktorzychla.com/2022/01/net-6-webapi-with-jwt-bearer-token.html). – Wiktor Zychla Jun 27 '23 at 11:12
  • I have added this previously, i removed it for testing and forgot to add it again, it still complains about the same thing. See my updated code with the use claim included. – schh Jun 27 '23 at 11:23
  • i also tried replacing the JwtSecurityToken with a TokenDescriptor like in your example but no change. – schh Jun 27 '23 at 11:28
  • Can you show minimal but yet complete client code and controller code? Something has to be different than in the example, the example obviously works. – Wiktor Zychla Jun 27 '23 at 14:28
  • And, can you try the `JwtRegisteredClaimNames.Name` instead of `ClaimTypes.Name`? These should be two different values. – Wiktor Zychla Jun 27 '23 at 14:29
  • Console still spits out [16:52:35 INF] Authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user. – schh Jun 27 '23 at 14:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/254271/discussion-between-schh-and-wiktor-zychla). – schh Jun 27 '23 at 15:02

1 Answers1

0

Ok so apparently adding System.IdentityModel.Tokens.Jwt nuget package solved it. This has to be a bug, nothing anywhere indicates that this package is missing. No error, no warnings, no nothing. If its needed it should be a dependency for the main jwt package.

Thanks to this answer from user bsebe i finally solved it.

schh
  • 311
  • 3
  • 16