.NET Core 7,使用不同的程序集进行授权中间件。

huangapple go评论65阅读模式
英文:

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

问题

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"));
    });

    // Add authentication
    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?

英文:

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&lt;SecuWebModulesAuthenticateContext&gt;(options =&gt;
        {
            options.UseSqlServer(configuration.GetConnectionString(&quot;Modules.Authenticate&quot;));
        });

        // Agrega autenticaci&#243;n
        services.AddAuthentication()
            .AddCookie(&quot;Cookies&quot;, options =&gt;
            {
                options.LoginPath = &quot;/Account/Login&quot;;
                options.LogoutPath = &quot;/Account/Logout&quot;;
                options.AccessDeniedPath = &quot;/Account/AccessDenied&quot;;
                options.ReturnUrlParameter = &quot;ReturnUrl&quot;;
            })
            .AddJwtBearer(x =&gt;
            {
                x.RequireHttpsMetadata = true;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = configuration[&quot;Modules:Authenticate:AuthJwt:Issuer&quot;],
                    ValidateAudience = true,
                    ValidAudience = configuration[&quot;Modules:Authenticate:AuthJwt:Audience&quot;],
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration[&quot;Modules:Authenticate:AuthJwt:Key&quot;] ?? 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&lt;SecuWebModulesPersonalContext&gt;(options =&gt;
        {
            options
                .UseSqlServer(configuration.GetConnectionString(&quot;Modules.Personal&quot;));
        });

        services.AddAuthorization();
    }

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

I know that the Configure method is actually being called.

How can I do this?

答案1

得分: 0

当我在Modules.Personal.Core的API控制器中使用AuthorizeAttribute时,会抛出这个异常。我知道Configure方法实际上已经被调用了。我该怎么做?

实际上,根据您提供的代码和异常细节,看起来是您的中间件导致了错误或异常,因为当您使用app.UseAuthorization()时,您需要按照正确的中间件顺序进行配置,否则就会导致您目前遇到的异常。

解决方案:

为了调用UseAuthorization,它应该出现在UseRoutingUseEndpoints之间的调用之间。如果不按照中间件顺序的确切顺序进行配置,授权将不起作用并失败。

我们应该遵循以下顺序:

中间件顺序:

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

    app.UseRouting();

    app.UseCors(MyAllowSpecificOrigins);

    app.UseAuthentication();

    app.UseAuthorization();

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

**注意:**如果您想了解更多关于授权中间件配置的详细信息,可以在这里查看我们的官方文档

英文:

> 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:

.NET Core 7,使用不同的程序集进行授权中间件。

Middleware Order:

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

        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =&gt;
        {
            endpoints.MapControllers();
        });
		
    }

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

huangapple
  • 本文由 发表于 2023年5月25日 02:55:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定