Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 7 Web API - authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user

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.

like image 716
schh Avatar asked Dec 31 '25 15:12

schh


1 Answers

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.

like image 73
schh Avatar answered Jan 02 '26 05:01

schh