ASP.NET Core 8.0 WebApi 从零开始学习JWT登录认证
在现代Web应用程序中,安全性是一项至关重要的考虑。JSON Web Token(JWT)是一种常用的认证方案,它允许你在Web应用程序中实现无状态的用户认证。本文将详细介绍如何在ASP.NET Core 8.0 WebAPI中实现JWT登录认证。
1. 创建ASP.NET Core 8.0 WebAPI项目
首先,我们需要创建一个新的ASP.NET Core WebAPI项目。打开命令行工具,运行以下命令:
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
2. 安装必要的NuGet包
为了使用JWT,我们需要安装Microsoft.AspNetCore.Authentication.JwtBearer
NuGet包。运行以下命令:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
3. 配置JWT
在appsettings.json
中添加JWT设置:
{
"Jwt": {
"Key": "ThisIsASecretKeyForJwtToken",
"Issuer": "JwtAuthDemo",
"Audience": "JwtAuthDemoUsers",
"ExpireMinutes": 60
}
}
4. 创建模型
创建一个用户模型和一个身份验证请求模型。在Models
文件夹中创建User.cs
和LoginRequest.cs
:
// Models/User.cs
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
// Models/LoginRequest.cs
public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
5. 设置JWT认证
在Program.cs
中配置JWT认证:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = jwtSettings.GetValue<string>("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.GetValue<string>("Issuer"),
ValidAudience = jwtSettings.GetValue<string>("Audience"),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
6. 创建认证控制器
在Controllers
文件夹中创建AuthController.cs
:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JwtAuthDemo.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest loginRequest)
{
// 在这里验证用户名和密码,这里简单示例
if (loginRequest.Username == "test" && loginRequest.Password == "password")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, loginRequest.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(double.Parse(_configuration["Jwt:ExpireMinutes"])),
signingCredentials: creds
);
return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token) });
}
return Unauthorized();
}
[Authorize]
[HttpGet("protected")]
public IActionResult GetProtected()
{
return Ok("This is a protected route!");
}
}
}
7. 测试API
启动应用程序,并使用Postman或其他API测试工具发送请求来验证JWT功能。
-
发送POST请求到
https://localhost:{port}/api/auth/login
,请求体为:json { "username": "test", "password": "password" }
如果用户名和密码正确,将返回JWT token。 -
使用返回的token访问受保护的路由,例如GET请求到
https://localhost:{port}/api/auth/protected
,在Headers中添加:Authorization: Bearer {your_token_here}
此时,您应该能够成功访问该路由。
总结
在本文中,我们从创建ASP.NET Core 8.0 WebAPI项目开始,逐步实现JWT登录认证。通过使用JWT,我们实现了无状态的用户认证,确保了API的安全性。希望这篇文章能帮助您理解并实现JWT认证。