本文以一个完整的示例,展示如何在.NET 6.0 Web API项目中实现基于Token的身份验证。这个例子包括了如何创建和验证JWT Token,以及如何在控制器中使用这些Token。
步骤 1: 创建Web API项目
首先,用Visual Studio 2022创建一个基于.NET6.0的 Web API项目。
步骤 2: 安装必要的NuGet包
安装Microsoft.AspNetCore.Authentication.JwtBearer
包。
步骤 3: 配置身份验证服务
在Program.cs
中配置身份验证服务:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;var builder = WebApplication.CreateBuilder(args);// 添加身份验证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuer = true,ValidateAudience = true,ValidateLifetime = true,ValidateIssuerSigningKey = true,ValidIssuer = builder.Configuration["Jwt:Issuer"],ValidAudience = builder.Configuration["Jwt:Audience"],IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))};});// 添加授权服务
builder.Services.AddAuthorization();var app = builder.Build();// 使用身份验证和授权中间件
app.UseAuthentication();
app.UseAuthorization();// 其他配置和路由设置app.MapControllers();
app.Run();
步骤 4: 配置JWT设置
在appsettings.json
中配置JWT的相关设置:
{"Jwt": {"Issuer": "YourIssuer","Audience": "YourAudience","Key": "YourVerySecretKey"}
}
步骤 5: 创建Token生成控制器
创建一个控制器来生成Token:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{private readonly IConfiguration _configuration;public AuthController(IConfiguration configuration){_configuration = configuration;}[HttpPost("login")]public IActionResult Login([FromBody] LoginModel model){// 假设这里有一个验证逻辑,验证用户名和密码if (model.Username == "test" && model.Password == "password"){var tokenDescriptor = new SecurityTokenDescriptor{Subject = new ClaimsIdentity(new Claim[]{new Claim(ClaimTypes.Name, model.Username)}),Expires = DateTime.UtcNow.AddMinutes(5),SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])), SecurityAlgorithms.HmacSha256Signature),Issuer = _configuration["Jwt:Issuer"],Audience = _configuration["Jwt:Audience"]};var tokenHandler = new JwtSecurityTokenHandler();var token = tokenHandler.CreateToken(tokenDescriptor);return Ok(new { token = tokenHandler.WriteToken(token) });}else{return Unauthorized();}}
}public class LoginModel
{public string Username { get; set; }public string Password { get; set; }
}
步骤 6: 创建受保护的控制器
创建一个控制器,只有持有有效Token的用户才能访问:
[ApiController]
[Route("[controller]")]
public class SecretController : ControllerBase
{[Authorize][HttpGet]public IActionResult Get(){return Ok("This is a secret message.");}
}
步骤 7: 调用API
要调用API,首先需要获取Token。可以使用Postman或类似的工具发送一个POST请求到/Auth/login
,并提供用户名和密码。然后,使用返回的Token在Authorization头部中发送一个GET请求到/Secret
。
POST /Auth/login HTTP/1.1
Host: localhost:5000
Content-Type: application/json{"Username": "test","Password": "password"
}
GET /Secret HTTP/1.1
Host: localhost:5000
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdCIsImV4cCI6MTYxODI3MzYwNSwiaXNzIjoiWW91ciJJc3N1ZXIiLCJhdWQiOiJZb3VyQXV0aGVudGljYXRpb24ifQ.6_3QXxZ3VzZvjZ7RnV5NQz-7y_93fY0Y7Y6jV7-XzQ
确保在实际应用中实现安全的用户验证逻辑,并且不要在代码中硬编码敏感信息。此外,根据你的具体需求,可能还需要实现用户注册、Token刷新等功能