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

.NET Core 1.1.4迁移至2.0:JWT身份认证配置变更咨询

迁移.NET Core 1.1到2.0:身份认证服务配置从Configure移至ConfigureServices的解决方案

我刚帮几个项目完成过类似的.NET Core版本迁移,这个调整其实是2.0对身份认证中间件的标准化优化,咱们一步步来把原来的配置平滑迁移过去:

核心变化说明

在.NET Core 1.1中,我们通常在Configure方法里直接注册认证中间件并配置参数;而2.0版本要求将认证服务的配置移至ConfigureServices方法,同时统一了中间件的注册方式,让整个认证体系更贴合依赖注入的设计理念。

具体代码迁移步骤

1. 原来的.NET Core 1.1配置(参考)

你之前的代码大概是这样在Configure里配置的:

public void Configure(IApplicationBuilder app)
{
    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = /* 你的密钥对象 */,
            ValidAudience = "你的Audience值",
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true
        }
    });

    app.UseMvc();
}

2. 迁移到.NET Core 2.0的配置

在ConfigureServices中配置认证服务

把所有认证相关的配置移到这里,注意使用AddAuthentication和AddJwtBearer的链式调用:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public void ConfigureServices(IServiceCollection services)
{
    // 先添加MVC服务(如果你的项目用MVC的话)
    services.AddMvc();

    // 配置身份认证服务,指定默认的认证方案为JWT Bearer
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            // 注意:.NET Core 2.0开始,AutomaticAuthenticate和AutomaticChallenge已标记为过时
            // 取而代之的是通过全局默认认证方案来实现相同效果,无需单独设置这两个属性

            // 直接迁移原来的TokenValidationParameters配置,参数完全兼容
            options.TokenValidationParameters = new TokenValidationParameters
            {
                // 替换成你实际的密钥
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-strong-secret-key-here")),
                ValidAudience = "your-audience-identifier",
                ValidateIssuerSigningKey = true,
                ValidateLifetime = true,
                // 如果原来还有其他验证参数,比如ValidIssuer,继续添加即可
                // ValidIssuer = "your-issuer-identifier",
                // ValidateIssuer = true
            };
        });
}

在Configure中注册认证中间件

原来的UseJwtBearerAuthentication要替换成统一的UseAuthentication,注意这个中间件要放在UseMvc之前:

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

    // 注册身份认证中间件,必须在UseMvc之前
    app.UseAuthentication();

    app.UseMvc();
}

关键注意点

  • 过时属性处理:AutomaticAuthenticate和AutomaticChallenge在2.0中已过时,通过AddAuthentication(JwtBearerDefaults.AuthenticationScheme)设置全局默认认证方案后,系统会自动处理认证和挑战逻辑,效果和原来一致。
  • 参数兼容性:TokenValidationParameters下的所有属性(IssuerSigningKey、ValidAudience等)都可以直接迁移,无需修改。
  • 中间件顺序:UseAuthentication必须放在UseMvc之前,否则MVC控制器的认证策略会无法生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:07:24