.NET Core 7, using a different assembly for authorization middleware

jstuardo

I have a project called Modules.Authenticate.Core which contains all the logic to configure authentication and authorization.

The Startup class contains this code:

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<SecuWebModulesAuthenticateContext>(options =>
        {
            options.UseSqlServer(configuration.GetConnectionString("Modules.Authenticate"));
        });

        // Agrega autenticación
        services.AddAuthentication()
            .AddCookie("Cookies", options =>
            {
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";
                options.AccessDeniedPath = "/Account/AccessDenied";
                options.ReturnUrlParameter = "ReturnUrl";
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = true;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = configuration["Modules:Authenticate:AuthJwt:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = configuration["Modules:Authenticate:AuthJwt:Audience"],
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Modules:Authenticate:AuthJwt:Key"] ?? string.Empty))
                };
            });

        services.AddAuthorization();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthentication();
        app.UseAuthorization();
    }

On the other hand, I have another project called Modules.Personal.Core. That project contains an api controller that should be authorized using the token provided by Modules.Authenticate.Core.

The token request works perfectly, however, when I use the AuthorizeAttribute in the api controller of Modules.Personal.Core, this exception is thrown:

System.InvalidOperationException: Endpoint Modules.Personal.Core.Controllers.Api.PersonaController.Get (Modules.Personal.Core) contains authorization metadata, but a middleware was not found that supports authorization. Configure your application startup by adding app.UseAuthorization() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them. at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint) at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Modules.Personal.Core has its own Startup class with this code:

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<SecuWebModulesPersonalContext>(options =>
        {
            options
                .UseSqlServer(configuration.GetConnectionString("Modules.Personal"));
        });

        services.AddAuthorization();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthorization();
    }

I know that the Configure method is actually being called.

How can I do this?

Md Farid Uddin Kiron

when I use the AuthorizeAttribute in the api controller of Modules.Personal.Core, this exception is thrown. I know that the Configure method is actually being called. How can I do this?

Actully, based on your shared code and exception details it's been appeared that, your middleware causing the error or exception because, when you would use app.UseAuthorization() you would need to follow the middleware order accordingly instead it will ended up with the exception which you are getting now.

Solution:

In order to the call to UseAuthorization should appear between the calls to UseRouting and UseEndpoints. If the middleware order doesn't followed exactly then the authorization will not act and get failed.

We should follow below order:

enter image description here

Middleware Order:

public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
        
    }

Note: If you would like to know more details on Authorization middleware configuration you could check our official document here.

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 middleware or OWIN middleware?

Changing the name of the output assembly and package using dnx/.net core

.NET Core EndRequest Middleware

Use Authorization middleware instead of AuthorizationAttribute ASPNET Core

Start Background Task using ASP.Net Core Middleware

Using .NET Core Session in middleware

ASP.NET Core Identity Authorization using Parameter for Team Membership

.NET Core 2.1 MVC Identity Authorization - Different user roles for different parts

Authentication & Authorization in .Net Core 2.1 WepAPI using JWT

ServiceStack and .NET Core Middleware

ASP.NET Core ViewComponents in different assembly can not be found

Using Basic Authorization as Middleware PSR-7 PSR-15

Role authorization in .net core 2.0 using Identity

ServiceStack on .NET Core using Authorization Policies

Authorization - Claimset in .net core

Get a 403 when using dual authorization (Bearer & Basic) in .net core

How to insert HTML into Response body using .NET Core Middleware

Role based authorization using Keycloak and .NET core

Net core order of middleware

Which authorization policy is used if multiple policies are specified (e.g. middleware configuration, controller/action attribute,) in Asp.Net Core?

Modify response using middleware in ASP.NET Core 3

asp.net core w/ cookie middleware - accessing request data on authorization

.NET Core Middleware is not invoked

Using Authorization filters to Implement permission based authorization in asp.net core

.net core 3 middleware or authorization attribute ? and how to?

Relation between Authorization middleware and filter Asp.net core

ASP.NET core Authorization Middleware

.NET Core Options pattern config registration using assembly scanning

Authorization middleware exception in ASP.NET Core with Angular project