英文:
.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 addingapp.UseAuthorization()
in the application startup code. If there are calls toapp.UseRouting()
andapp.UseEndpoints(...)
, the call toapp.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<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?
答案1
得分: 0
当我在Modules.Personal.Core的API控制器中使用AuthorizeAttribute时,会抛出这个异常。我知道Configure方法实际上已经被调用了。我该怎么做?
实际上,根据您提供的代码和异常细节,看起来是您的中间件导致了错误或异常,因为当您使用app.UseAuthorization()
时,您需要按照正确的中间件顺序进行配置,否则就会导致您目前遇到的异常。
解决方案:
为了调用UseAuthorization
,它应该出现在UseRouting
和UseEndpoints
之间的调用之间。如果不按照中间件顺序的确切顺序进行配置,授权将不起作用并失败。
我们应该遵循以下顺序:
中间件顺序:
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:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论