将基于OWIN的ASP.NET Web API JWT认证转换为ASP.NET Core 3.1 Web API的指南
从ASP.NET Web API(OWIN)迁移JWT认证到ASP.NET Core 3.1 Web API
没问题,我来给你梳理一套清晰的迁移步骤,完全对应你当前的OWIN JWT实现,适配ASP.NET Core 3.1的架构:
第一步:替换NuGet包
先移除旧的OWIN相关包(比如Microsoft.Owin.Security.Jwt、Microsoft.Owin.Cors等),然后安装ASP.NET Core专用的JWT和Cors包:
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Install-Package Microsoft.AspNetCore.Cors Install-Package Microsoft.AspNetCore.SignalR
第二步:重构Startup.cs(Core版本)
ASP.NET Core把服务注册和中间件管道配置整合到了Startup.cs的两个核心方法里,下面是对应你原有逻辑的完整代码:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System.Text; namespace solution { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // 注册服务(对应OWIN里的服务初始化) public void ConfigureServices(IServiceCollection services) { // 注册SignalR服务 services.AddSignalR(); // 配置Cors(允许所有跨域请求,和你原来的AllowAll一致) services.AddCors(options => { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // 配置JWT认证服务 var issuer = "issuer"; var audience = "audience"; var secretKey = "SecurityKey"; // 和你原来的密钥一致 var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Bearer"; options.DefaultChallengeScheme = "Bearer"; }) .AddJwtBearer("Bearer", options => { options.TokenValidationParameters = new TokenValidationParameters { // 对应你原来的Issuer和Audience验证 ValidIssuer = issuer, ValidAudience = audience, IssuerSigningKey = symmetricKey, // 开启必要的验证规则(默认部分开启,这里明确配置更清晰) ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidateLifetime = true }; }); // 注册Web API控制器(支持属性路由) services.AddControllers(); } // 配置中间件管道(对应OWIN里的Configuration方法) public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); // 启用Cors(要放在认证之前) app.UseCors("AllowAll"); // 启用认证和授权(顺序很重要:先认证后授权) app.UseAuthentication(); app.UseAuthorization(); // 配置路由 app.UseRouting(); // 映射端点:包括API控制器和SignalR Hub app.UseEndpoints(endpoints => { endpoints.MapControllers(); // 对应原来的MapHttpAttributeRoutes endpoints.MapHub<YourHubClass>("/signalr"); // 替换成你的SignalR Hub类 }); } } }
关键对应点说明
我特意把你原来的OWIN逻辑一一对应到Core的架构里:
- JWT配置:原来的
JwtBearerAuthenticationOptions被整合到AddJwtBearer的配置中,通过TokenValidationParameters集中管理所有验证规则,替代了原来的AllowedAudiences和IssuerSecurityTokenProviders。 - 认证模式:ASP.NET Core默认就是主动验证模式,不需要像OWIN那样显式设置
AuthenticationMode.Active。 - 中间件顺序:Core对中间件的顺序要求很严格,
UseCors要放在UseAuthentication之前,UseAuthentication要放在UseAuthorization之前,最后才是路由和端点映射。 - SignalR:原来的
app.MapSignalR()被替换成AddSignalR(服务注册)和MapHub(端点映射)的组合,这是Core版本SignalR的标准用法。
额外注意事项
- 确保你的密钥
SecurityKey长度符合算法要求:如果用HS256(默认),密钥至少要16字节(128位),否则会抛出验证错误。 - 如果你原来有生成JWT的逻辑,Core里可以继续用
System.IdentityModel.Tokens.Jwt包的JwtSecurityTokenHandler来生成,API和OWIN版本几乎一致。 - 属性路由在Core里默认是启用的,只要你的控制器加了
[Route]或[ApiController]属性就可以正常工作,对应原来的config.MapHttpAttributeRoutes()。
内容的提问来源于stack exchange,提问作者user584018
相关产品推荐
相关产品推荐

