net 6 webapi jwt鉴权
时间: 2023-07-22 13:12:32 浏览: 197
.NET 6 Web API中的JWT鉴权可以通过以下步骤实现:
1. 在NuGet包管理器中安装所需的包:
- Microsoft.AspNetCore.Authentication.JwtBearer
- System.IdentityModel.Tokens.Jwt
2. 在appsettings.json文件中添加JWT配置:
```json
{
"JwtSettings": {
"Issuer": "your_issuer",
"Audience": "your_audience",
"SecretKey": "your_secret_key"
}
}
```
3. 在Startup.cs文件的ConfigureServices方法中进行配置:
```csharp
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
public void ConfigureServices(IServiceCollection services)
{
// 添加配置文件支持
services.AddOptions();
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
// 读取JWT配置
var jwtSettings = Configuration.GetSection("JwtSettings").Get<JwtSettings>();
// 添加JWT认证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
};
});
// 添加授权策略
services.AddAuthorization();
// 添加其他服务和中间件
}
```
4. 创建一个JwtSettings类来存储JWT配置:
```csharp
public class JwtSettings
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string SecretKey { get; set; }
}
```
5. 在需要进行JWT鉴权的控制器或方法上添加[Authorize]特性:
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[Authorize]
[HttpGet("protected")]
public IActionResult Protected()
{
// 受保护的路由,只有经过认证的用户才能访问
return Ok("You have accessed the protected route.");
}
// 其他方法和路由
}
```
以上步骤将会在.NET 6 Web API中实现JWT鉴权。确保将"your_issuer"、"your_audience"和"your_secret_key"替换为你的实际值。通过添加[Authorize]特性到需要鉴权的控制器或方法上,只有经过认证的用户才能访问受保护的路由。
阅读全文