要在ASP.NET Core 2.2中实现JWT身份验证,你可以按照以下步骤进行操作:
首先,确保你的应用程序已经添加了以下NuGet包:
在Startup.cs文件中,添加以下代码来配置JWT身份验证:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
// 配置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 = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});
// ...
}
// ...
}
在上面的代码中,你需要将 "your-issuer"
、"your-audience"
和 "your-secret-key"
替换为你自己的值。这些值将用于验证和生成JWT令牌。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
// 启用身份验证
app.UseAuthentication();
// ...
}
[Authorize]
特性来限制访问:[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult Get()
{
// 这个操作方法需要身份验证才能访问
// ...
}
// ...
}
在上面的代码中,[Authorize]
特性将确保只有经过身份验证的用户才能访问 Get
操作方法。
这就是在ASP.NET Core 2.2中实现JWT身份验证的基本步骤。通过配置身份验证中间件和使用 [Authorize]
特性来限制访问,你可以确保只有经过身份验证的用户才能访问你的应用程序的特定部分。