最近写了一个小工具用了JWT作为验证,下面是一个简单的JWT Demo,包含用户注册和登录获取Token
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Moment.Shared;
using Moment.Shared.DBModel;
namespace Moment.Core.Controllers;
/// <summary>
/// JWT令牌授权控制器
/// </summary>
[Route("[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly IFreeSql _db;
public AuthController(IConfiguration configuration, IFreeSql db)
{
_configuration = configuration;
_db = db;
}
/// <summary>
/// 注册用户
/// </summary>
/// <param name="email">用户邮箱</param>
/// <param name="password">用户密码</param>
/// <returns></returns>
[HttpPost("Register")]
public async Task<ActionResult<Result>> Register(string email, string password)
{
// 检查邮箱是否存在
var item = await _db.Select<User>().Where(x => x.Email == email).FirstAsync();
if (item is not null)
{
return BadRequest(new Result("邮箱已经注册!"));
}
// 注册用户
var user = new User
{
Email = email,
PasswordHash = BCrypt.Net.BCrypt.HashPassword(password)
};
await _db.Insert<User>().AppendData(user).ExecuteAffrowsAsync();
return Ok(new Result(msg: "注册成功!", content: user));
}
/// <summary>
/// 用户登录获取Token
/// </summary>
/// <param name="email">用户邮箱</param>
/// <param name="password">用户密码</param>
/// <returns>Token值</returns>
[HttpPost("Login")]
public async Task<ActionResult<User>> Login(string email, string password)
{
var user = await _db.Select<User>().Where(x => x.Email == email).FirstAsync();
// 检查用户存在
if (user is null)
return BadRequest(new Result("用户不存在!"));
var res = BCrypt.Net.BCrypt.Verify(password, user.PasswordHash);
// 检查密码正确
if (!res)
return BadRequest(new Result("密码错误!"));
return Ok(new Result("登录成功!", CreateToken(user)));
}
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Role, user.Role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
_configuration.GetSection("AppSettings:Token").Value!));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
}
发表回复