新增AuthroizeController控制器,并添加如下代码
[HttpPost] public ActionResult Post([FromBody]LoginViewModel loginViewModel) { if (!ModelState.IsValid) { return BadRequest(); } if (loginViewModel.Name == "jack" && loginViewModel.Password == "rose") { var claims = new Claim[] { new Claim(ClaimTypes.Name,"jack"), new Claim(ClaimTypes.Role,"admin") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSeetings.SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _jwtSeetings.Issuer, _jwtSeetings.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(30), creds ); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } return BadRequest(); }给ValuesController控制器打上[Authorize]特性
用Postman直接访问:5000/api/Values 返回401
用Postman访问:5000/api/Authroize 得到Token
通过Bearer访问成功
源代码 https://github.com/HisKingdom/JwtAuthSample
参考博客:https://www.jianshu.com/p/576dbf44b2ae