.net 6 webapi jwt授权鉴权代码
时间: 2023-07-22 12:12:33 浏览: 171
.net core webapi jwt 更为清爽的认证详解
以下是使用.NET 6 Web API进行JWT授权鉴权的示例代码:
1. 首先,安装所需的NuGet包:
```
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
```
2. 在Program.cs文件中进行配置:
```csharp
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// 添加JWT认证服务
builder.Services.AddAuthentication(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")) // 密钥
};
});
// 注册授权策略
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
```
3. 创建一个控制器来处理认证请求:
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(string username, string password)
{
// 假设这里是验证用户名和密码的逻辑
// 如果验证通过,创建一个JWT token并返回给客户端
var token = GenerateToken(username);
return Ok(new { token });
}
[Authorize]
[HttpGet("protected")]
public IActionResult Protected()
{
// 受保护的路由,只有经过认证的用户才能访问
return Ok("You have accessed the protected route.");
}
private string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
// 可以添加其他自定义的claims
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: claims,
expires: DateTime.Now.AddMinutes(30), // token过期时间
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
```
以上示例代码演示了如何使用.NET 6 Web API和JWT进行授权鉴权。请注意替换示例中的"your_issuer"、"your_audience"和"your_secret_key"为适合你的实际情况的值。
阅读全文