.NET Core 2 JWT认证迁移至ASP.NET Web API 2的适配咨询
Absolutely feasible! Your existing JwtTokenBuilder, JwtToken, and JwtSecurityKey classes are 100% reusable between .NET Core 2 and ASP.NET Web API 2. These classes handle token creation and cryptographic key management—logic that’s framework-agnostic, so you won’t need to touch them at all. The only changes required are to your OWIN Startup configuration, since Web API 2 uses a different OWIN middleware setup than .NET Core.
Here’s exactly what you need to do:
1. Install Required NuGet Packages
First, make sure your Web API 2 project has the necessary OWIN JWT packages (these aren’t included by default like in .NET Core):
Install-Package Microsoft.Owin.Security.Jwt Install-Package Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Host.SystemWeb is needed if your Web API 2 project is hosted on IIS (the most common scenario).
2. Rewrite the OWIN Startup Class
Unlike .NET Core’s Startup that uses IApplicationBuilder and dependency injection, Web API 2’s OWIN startup uses IAppBuilder and configures middleware directly. Replace your existing Core-style startup with this:
using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Jwt; using Owin; using System.Configuration; using YourNamespace; // Replace with the namespace containing your JwtSecurityKey class [assembly: OwinStartup(typeof(YourWebApiProject.Startup))] namespace YourWebApiProject { public class Startup { public void Configuration(IAppBuilder app) { // Configure Web API routing (add this if you haven't already) var webApiConfig = new HttpConfiguration(); WebApiConfig.Register(webApiConfig); // Configure JWT authentication var jwtAuthOptions = new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, TokenValidationParameters = new TokenValidationParameters { // Match these settings exactly to your .NET Core 2 configuration ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = ConfigurationManager.AppSettings["JwtIssuer"], ValidAudience = ConfigurationManager.AppSettings["JwtAudience"], // Reuse your existing JwtSecurityKey class here! IssuerSigningKey = JwtSecurityKey.Create(ConfigurationManager.AppSettings["JwtSecretKey"]) } }; // Enable JWT authentication middleware app.UseJwtBearerAuthentication(jwtAuthOptions); // Wire up Web API app.UseWebApi(webApiConfig); } } }
3. Sync Configuration Values
Ensure your Web API 2 project’s web.config has the same JWT settings as your .NET Core 2 project’s appsettings.json:
<appSettings> <add key="JwtIssuer" value="YourIssuerName" /> <add key="JwtAudience" value="YourAudienceName" /> <add key="JwtSecretKey" value="YourSuperSecretKeyHere" /> </appSettings>
Mismatched values here are the #1 cause of "invalid token" errors, so double-check these!
4. Troubleshoot Common Errors
- "Invalid signature": Verify your
JwtSecurityKey.Createmethod generates the same cryptographic key in both projects (e.g., ensure you’re using the same encoding for the secret key). - "Authorization has been denied for this request": Confirm your request includes an
Authorizationheader in the formatBearer {your-token}, and that the[Authorize]attribute is applied correctly to your controllers/actions. - OWIN middleware not firing: Add
<add key="owin:AutomaticAppStartup" value="true" />to yourweb.config’sappSettingsto force OWIN to initialize your startup class.
Your core JWT logic will work exactly as it did in .NET Core 2—you’re just swapping out how the framework validates incoming tokens.
内容的提问来源于stack exchange,提问作者Hasan Fathi

