構建一個包含 JWT(JSON Web Token)鑒權的 Web API 是一種常見的做法,用于保護 API 端點并驗證用戶身份。以下是一個基于 ASP.NET Core 的完整示例,展示如何實現 JWT 鑒權。
1. 創建 ASP.NET Core Web API 項目
使用 .NET CLI 或 Visual Studio 創建一個新的 Web API 項目:
dotnet new webapi -n JwtAuthApi
cd JwtAuthApi
2. 安裝必要的 NuGet 包
確保安裝了以下包(通常默認已包含):
Microsoft.AspNetCore.Authentication.JwtBearer
Microsoft.IdentityModel.Tokens
System.IdentityModel.Tokens.Jwt
如果未安裝,可以運行以下命令:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
3. 配置 JWT 鑒權
(1) 修改 appsettings.json
在 appsettings.json
中添加 JWT 配置:
{"Jwt": {"Key": "YourSecretKeyForJwtAuthentication", // 用于簽名的密鑰"Issuer": "YourIssuer", // 發行者"Audience": "YourAudience" // 受眾},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*"
}
(2) 配置服務 (Program.cs
)
在 Program.cs
中配置 JWT 鑒權服務:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;var builder = WebApplication.CreateBuilder(args);// 添加 JWT 鑒權
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.ASCII.GetBytes(jwtSettings["Key"]);builder.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 = jwtSettings["Issuer"],ValidAudience = jwtSettings["Audience"],IssuerSigningKey = new SymmetricSecurityKey(key)};
});builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();var app = builder.Build();if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseHttpsRedirection();// 使用鑒權中間件
app.UseAuthentication();
app.UseAuthorization();app.MapControllers();app.Run();
4. 創建用戶登錄和生成 JWT 的邏輯
(1) 創建模型類
創建一個簡單的用戶模型和返回的響應模型:
public class UserModel
{public string Username { get; set; }public string Password { get; set; }
}public class AuthResponse
{public string Token { get; set; }public DateTime Expiration { get; set; }
}
(2) 創建生成 JWT 的方法
在 Controllers/AuthController.cs
中實現登錄和生成 JWT 的邏輯:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{private readonly IConfiguration _configuration;public AuthController(IConfiguration configuration){_configuration = configuration;}[HttpPost("login")]public IActionResult Login([FromBody] UserModel user){// 模擬用戶驗證(實際應從數據庫中驗證)if (user.Username == "admin" && user.Password == "password"){var token = GenerateJwtToken(user.Username);return Ok(new AuthResponse{Token = token,Expiration = DateTime.UtcNow.AddMinutes(30) // 設置過期時間});}return Unauthorized(new { message = "Invalid username or password" });}private string GenerateJwtToken(string username){var jwtSettings = _configuration.GetSection("Jwt");var key = Encoding.ASCII.GetBytes(jwtSettings["Key"]);var tokenDescriptor = new SecurityTokenDescriptor{Subject = new ClaimsIdentity(new[]{new Claim(ClaimTypes.Name, username),new Claim(ClaimTypes.Role, "Admin") // 示例角色}),Expires = DateTime.UtcNow.AddMinutes(30), // 設置過期時間Issuer = jwtSettings["Issuer"],Audience = jwtSettings["Audience"],SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature)};var tokenHandler = new JwtSecurityTokenHandler();var securityToken = tokenHandler.CreateToken(tokenDescriptor);return tokenHandler.WriteToken(securityToken);}
}
5. 創建受保護的 API 端點
(1) 創建一個受保護的控制器
在 Controllers/SecureController.cs
中創建一個需要 JWT 鑒權的端點:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;[ApiController]
[Route("api/[controller]")]
[Authorize] // 要求鑒權
public class SecureController : ControllerBase
{[HttpGet]public IActionResult Get(){var username = User.Identity.Name;return Ok(new { message = $"Hello, {username}! This is a secure endpoint." });}
}
6. 測試 API
(1) 登錄獲取 JWT
發送 POST 請求到 /api/auth/login
,請求體如下:
{"username": "admin","password": "password"
}
響應會返回一個 JWT Token。
(2) 訪問受保護的端點
將獲取到的 Token 添加到請求頭中,格式為:
Authorization: Bearer <JWT_TOKEN>
然后訪問 /api/secure
,你將看到受保護的響應。
總結
通過以上步驟,我們實現了一個包含 JWT 鑒權的 Web API。這個示例展示了如何生成 JWT、驗證 JWT,以及如何保護 API 端點。你可以根據實際需求擴展功能,例如從數據庫驗證用戶、支持角色權限等。