接到上篇文章api
安裝擴展插件nuget package方法安裝包this
使用 ctrl+shift+p打開命令面板spa
生成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獲取返回的token3d
根據獲取到的token就能夠訪問以前的網址了,咱們也能夠去https://jwt.io/去校驗咱們的toekncode