C# 实现Jwtbearer Authentication (2)

新增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

1530672358385

用Postman访问:5000/api/Authroize 得到Token

1530672442132

通过Bearer访问成功

1530672572449

源代码 https://github.com/HisKingdom/JwtAuthSample

参考博客:https://www.jianshu.com/p/576dbf44b2ae

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyfzfs.html