Why is ASP.NET Core Identity 2.0 Authorize filter causing me to get a 404?

Daniel S.

I have a controller that I want to restrict only to a specific role, let's say admin. After setting a user with the admin role, I can validate that he's on that role using the IsInRoleAsync method (which returns true). When setting the attribute with [Authorize(Roles = "admin")] I get a 404 with that very same user . I'm using bearer tokens (I don't think that is relevant but anyway) and here's what I've done to try debugging:

Controller w/o [Authorize] : the resource is returned. [OK]

Controller with [Authorize] : the resource is returned only when I use the Authentication: Bearer [access token] [OK]

Controller with [Authorize(Roles = "admin")] : even after logging in with the user that has the role set, I get the 404 [NOK]

I don't know if I'm missing some configuration, but here's my ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        options.UseOpenIddict();
    });
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddOpenIddict(opt =>
    {
        opt.AddEntityFrameworkCoreStores<ApplicationDbContext>();
        opt.AddMvcBinders();
        opt.EnableTokenEndpoint("/api/token");
        opt.AllowPasswordFlow();
        opt.DisableHttpsRequirement(); //for dev only!
        opt.UseJsonWebTokens();
        opt.AddEphemeralSigningKey();
        opt.AllowRefreshTokenFlow();
        opt.SetAccessTokenLifetime(TimeSpan.FromMinutes(5));
    });

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = OAuthValidationConstants.Schemes.Bearer;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
       .AddJwtBearer(options =>
       {
           options.Authority = "http://localhost:44337/";
           options.Audience = "resource_server";
           options.RequireHttpsMetadata = false;
           options.TokenValidationParameters = new TokenValidationParameters
           {
               NameClaimType = OpenIdConnectConstants.Claims.Subject,
               RoleClaimType = OpenIdConnectConstants.Claims.Role
           };                   
       });
    services.Configure<IdentityOptions>(options =>
    {
        // Password settings
        options.Password.RequireDigit = true;
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = true;
        options.Password.RequireLowercase = false;

        // Lockout settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
        options.Lockout.MaxFailedAccessAttempts = 10;
        // User settings
        options.User.RequireUniqueEmail = true;
        // Add application services.
        options.ClaimsIdentity.UserNameClaimType= OpenIdConnectConstants.Claims.Name;
        options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
        options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
    });

    services.AddSingleton(typeof(RoleManager<ApplicationUser>));
    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
Kévin Chalet

You likely get a 404 response because Identity - which is automatically configured as the default authentication, sign-in/sign-out and challenge/forbidden scheme by services.AddIdentity() - tries to redirect you to the "access denied page" (Account/AccessDenied by default), that probably doesn't exist in your application.

Try to override the default challenge/forbidden scheme to see if it fixes your issue:

services.AddAuthentication(options =>
{
    // ...
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
});

To fix your second issue, make sure the JWT claims mapping feature is disabled. If it's not, the JWT handler will "convert" all your role claims to ClaimTypes.Role, which won't work as you configured it to use role as the role claim used by ClaimsPrincipal.IsInRole(...) (RoleClaimType = OpenIdConnectConstants.Claims.Role).

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    // ...
    options.SecurityTokenValidators.Clear();
    options.SecurityTokenValidators.Add(new JwtSecurityTokenHandler
    {
        // Disable the built-in JWT claims mapping feature.
        InboundClaimTypeMap = new Dictionary<string, string>()
    });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Asp.Net Core Identity - Authorize attribute with roles and caching?

Override global authorize filter in ASP.NET Core 1.0 MVC

Why ASP.NET Core MVC 3.1 project wont let me sign in with a register user using Identity

.net core identity 2.1 role authorize not working

Why is my ASP.NET Web API with Identity 2 not granting me access to protected resources?

Not Found for actions with Authorize attribute while using identity in asp.net core

Adding [Authorize] to controller failing to redirect to Identity Login route. ASP.NET CORE 3.1 MVC

Authorize Register Page in ASP.NET Core 2.1 with Identity UI as a library

Using Asp.Net Core Identity in MVC, Authorize attribute is rebouncing to login page after succesfull login

ASP.Net Core 2.1/WebAPI app: "HTTP 404 not found" calling a REST url with [Authorize]

ASP.NET core Web API Authorize Attribute return 404 Error & force redirect

Use asp.net authorize in .net core

Why Asp.Net Core 2.1 Identity Use Razor Pages?

Get property of applicationuser from the asp.net core identity

ASP.NET Core Identity - get current user

JS get cookie ASP.NET Core Identity

How to get Asp.net Core Identity User in View

Get accessToken in Identity Server ASP.NET Core

Asp.net Core Authorize Redirection Not Happening

Custom Authorize attribute - ASP .NET Core 2.2

ASP .NET Core Identity SignInManager

Why is asp.net core microservice returning 404?

ASP.NET core 2 how to skip identity association form?

ASP.NET Core 2 - Identity - DI errors with custom Roles

.NET Core 3.0 using Identity + JWT fails to authorize

Why is my ASP.NET MVC route configuration causing an HTTP 404 error?

How to use Authorize without ASP.NET Identity

Authorize with Claims instead of Policies in ASP.Net Identity

How do I get Configuration, Cookie and DBContext in Action Filter in ASP.Net Core 2.x