接到上篇文章
安装扩展插件nuget package方法安装包
使用 ctrl+shift+p打开命令面板
增加这个包, Microsoft.AspNetCore.Authentication.JwtBearer
增加完后, 保存安装的包
生成Token
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Options; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.JwtBearer; using System.IdentityModel.Tokens.Jwt; namespace JwtAuthSample.Controllers { [Route("api/[controller]")] public class AuthorizeController : ControllerBase { private Models.JwtSettings _jwtSettings{get;set;} public AuthorizeController(IOptions<Models.JwtSettings> _jwtSettings){ this._jwtSettings = _jwtSettings.Value; } public IActionResult Token(LoginViewModel loginViewModel){ if(ModelState.IsValid) { if(loginViewModel.User!="qinzb" && loginViewModel.Password!="123"){ return BadRequest(); } var claims = new Claim[]{ new Claim(ClaimTypes.Name,"qinzb"), new Claim(ClaimTypes.Role,"admin") }; var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey (System.Text.Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)); var creds = new Microsoft.IdentityModel.Tokens.SigningCredentials (key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256); var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken( _jwtSettings.Issure, _jwtSettings.Audience, claims, null, DateTime.Now.AddMinutes(30), creds ); return Ok(new {token = new JwtSecurityTokenHandler().WriteToken(token)}); } return BadRequest(); } } }
我们就可以根据 http://localhost:5000/api/Authorize?User=qinzb&Password=123获取返回的token
根据获取到的token就可以访问之前的网址了,我们也可以去https://jwt.io/去校验我们的toekn