使用 ASP.NET Core 封装的 JWT
一、用NuGet安装 :Microsoft.AspNetCore.Authentication.JwtBearer
二、在appsetting中添加配置节点
"JWT": { "SigningKey": "", "ExpireSeconds": "" }
public class JWTOptions { public string SigningKey { get; set; } public string ExpireSeconds { get; set; } }
三、注册服务
//配置JWT services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(x => { var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>(); byte[] keyBytes=Encoding.UTF8.GetBytes(jwtOpt.SigningKey); var secKey=new SymmetricSecurityKey(keyBytes); x.TokenValidationParameters = new() { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKey = secKey }; });
services.AddScoped<JwtHelper,JwtHelper>();
app.UseAuthentication(); app.UseAuthorization();
使用
using CAPWebApplication.Config; using CAPWebApplication.Entities; using CAPWebApplication.Tools; using CAPWebApplication.ViewModel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Security.Claims; namespace CAPWebApplication.Controllers { [Route("api/[controller]")] [ApiController] public class UserRoleController : ControllerBase { private readonly ILogger<UserRoleController> m_logger; private readonly UserManager<User> m_userManager; private readonly RoleManager<Role> m_roleManager; private readonly IOptions<JWTOptions> m_JWTOptions; private readonly JwtHelper m_JwtHelper; public UserRoleController(ILogger<UserRoleController> logger, UserManager<User> userManager, RoleManager<Role> roleManager, IOptions<JWTOptions> jWTOptions = null, JwtHelper jwtHelper = null) { m_logger = logger; m_userManager = userManager; m_roleManager = roleManager; m_JWTOptions = jWTOptions; m_JwtHelper = jwtHelper; } [Route(nameof(CreateUserRole))] [HttpPost] public async Task<ActionResult> CreateUserRole() { bool roleExists = await m_roleManager.RoleExistsAsync("admin"); if (!roleExists) { Role role = new Role { Name = "Admin" }; var r = await m_roleManager.CreateAsync(role); if (!r.Succeeded) { return BadRequest(r.Errors); } } User user = await m_userManager.FindByNameAsync("yyy"); if (user == null) { user = new User { UserName = "yyy", Email = "flyingdream8@163.com", EmailConfirmed = true }; var r = await m_userManager.CreateAsync(user, "123456"); if (!r.Succeeded) { return BadRequest(r.Errors); } r = await m_userManager.AddToRoleAsync(user, "admin"); if (!r.Succeeded) { return BadRequest(r.Errors); } } return Ok(); } [Route(nameof(Login))] [HttpPost] public async Task<ActionResult> Login(UserViewModel model) {//验证用户名和密码 if (model == null || string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.Password)) { return BadRequest(); } var user = await m_userManager.FindByNameAsync(model.UserName); if (user == null) { return NotFound($"用户名不存在{model.UserName}"); } if (await m_userManager.IsLockedOutAsync(user)) return BadRequest("LockedOut"); var success = await m_userManager.CheckPasswordAsync(user, model.Password); if (success) {//登录成功返回Token string jwtToken = await m_JwtHelper.GenerateJWT(user, m_JWTOptions.Value.SigningKey, m_JWTOptions.Value.ExpireSeconds); return Ok(jwtToken); } else { await m_userManager.AccessFailedAsync(user); return BadRequest("密码错误"); } } [Authorize] [Route(nameof(GetUserRole))] [HttpGet] public async Task<ActionResult> GetUserRole() {//读取当前登录用户User的信息 string id = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value; string userName = this.User.FindFirst(ClaimTypes.Name)!.Value; IEnumerable<Claim> roleClaims = this.User.FindAll(ClaimTypes.Role); string roleNames = string.Join(',', roleClaims.Select(c => c.Value)); return Ok($"Id={id},UserName={userName},Roles={roleNames}"); } } }
JWTHelper参见: https://www.cnblogs.com/friend/p/16757914.html