You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 7跨程序集授权中间件异常问题求助

问题分析

异常提示“端点包含授权元数据但无支持的授权中间件”,本质是Modules.Personal.Core项目仅配置了授权基础服务,但未引入认证中间件的具体配置——授权依赖认证来识别用户身份,而你把Cookie/JWT的认证配置单独放在了Modules.Authenticate.Core里,Personal项目并没有加载这些认证逻辑。

解决方案

1. 复用Authenticate项目的认证配置

把Modules.Authenticate.Core里的认证逻辑封装成可复用的扩展方法,避免重复代码:

// 在Modules.Authenticate.Core中创建扩展类
public static class AuthenticationServiceExtensions
{
    public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration config)
    {
        // 原有Cookie和JWT认证配置逻辑
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = config["Jwt:Issuer"],
                ValidAudience = config["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]))
            };
        })
        .AddCookie(options =>
        {
            options.Cookie.Name = "AuthCookie";
            options.ExpireTimeSpan = TimeSpan.FromHours(2);
        });

        return services;
    }
}

2. 在Personal项目中加载认证配置

在Modules.Personal.Core的Startup类里,先调用扩展方法添加认证,再配置授权:

public void ConfigureServices(IServiceCollection services)
{
    // 复用Authenticate项目的认证配置
    services.AddCustomAuthentication(Configuration);
    // 添加授权服务
    services.AddAuthorization();

    // 其他服务配置
    services.AddControllers();
}

3. 严格控制中间件顺序

在Configure方法中,中间件顺序必须遵循:UseRouting → UseAuthentication → UseAuthorization → UseEndpoints,顺序错误会直接导致授权失效:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseRouting();

    // 先启用认证中间件
    app.UseAuthentication();
    // 再启用授权中间件
    app.UseAuthorization();

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

4. 验证授权策略(可选)

如果你的AuthorizeAttribute指定了特定策略,要确保授权配置中存在对应策略:

services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
关键注意点
  • 授权中间件依赖认证中间件提供的用户身份信息,二者必须配套使用。
  • 确保两个项目的配置文件包含JWT/Cookie所需的配置项(如密钥、Issuer等),或从统一配置源读取。
  • 不要在多个项目重复编写认证配置,通过扩展方法复用可降低维护成本。

内容的提问来源于stack exchange,提问作者jstuardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:57:13