MVC进行jwt认证

1、JWT

1.1 基于 Token 的身份验证方法

使用基于 Token 的身份验证方法,在服务端不需要存储用户的登录记录。大概的流程是这样的:

  1. 客户端使用用户名跟密码请求登录
  2. 服务端收到请求,去验证用户名与密码
  3. 验证成功后,服务端会签发一个 Token,再把这个 Token 发送给客户端
  4. 客户端收到 Token 以后可以把它存储起来,比如放在 Cookie 里或者 Local Storage 里
  5. 客户端每次向服务端请求资源的时候需要带着服务端签发的 Token
  6. 服务端收到请求,然后去验证客户端请求里面带着的 Token,如果验证成功,就向客户端返回请求的数据

1.2 JWT

JWT 标准的 Token 有三个部分:

  • header
  • payload
  • signature

2、安装JWT.NET

 

 

3、使用JWT

3.1 JWT帮助类

 

 
  1. public class JwtHelper

  2. {

  3. private string m_Secret = "BFE7E27E-C1F3-41E0-AAD5-7D14AFC6CD2C";

  4. public string EncodeJwt(LoginInfo userInfo)

  5. {

  6. IJwtAlgorithm algorithm = new HMACSHA256Algorithm();

  7. IJsonSerializer serializer = new JsonNetSerializer();

  8. IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

  9. IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

  10. return encoder.Encode(userInfo, m_Secret);

  11. }

  12.  
  13. public LoginInfo DecodeJwt(string token)

  14. {

  15. IJsonSerializer serializer = new JsonNetSerializer();

  16. IDateTimeProvider provider = new UtcDateTimeProvider();

  17. IJwtValidator validator = new JwtValidator(serializer, provider);

  18. IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

  19. IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

  20. var userInfo = decoder.DecodeToObject<LoginInfo>(token, m_Secret, verify: true);//token为之前生成的字符串

  21. return userInfo;

  22. }

  23. }

3.2 获取JWT的接口

 

 
  1. public ActionResult CreateToken(string UserName, string PassWord)

  2. {

  3. if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))

  4. throw new Exception("参数为空");

  5.  
  6. JwtResult jwtResult;

  7. try

  8. {

  9. //var param = HttpContext.Request["UserName"];

  10. //param = HttpContext.Request["PassWord"];

  11. if (!UserName.Equals("test") || !PassWord.Equals("test"))

  12. {

  13. throw new Exception("用户密码不正确。");

  14. }

  15.  
  16. LoginInfo pUserLoginInfo = new LoginInfo() { Name = UserName, Password = PassWord };

  17. JwtHelper pHelper = new JwtHelper();

  18. string sJwt = pHelper.EncodeJwt(pUserLoginInfo);

  19. jwtResult = new JwtResult()

  20. {

  21. JwtCode = sJwt,

  22. StatusCode = "200",

  23. Message = "success"

  24. };

  25. return Json(jwtResult);

  26. }

  27. catch (Exception ex)

  28. {

  29. jwtResult = new JwtResult()

  30. {

  31. JwtCode = "",

  32. StatusCode = "403",

  33. Message = ex.Message

  34. };

  35. }

  36.  
  37. return Json(jwtResult);

  38. }

3.3 .Net身份认证

AuthorizeAttribute类有两个重要的方法:AuthorizeCore和HandleUnauthorizedRequest。其中AuthorizeCore函数是用来判断一个请求是否通过用户验证,它的返回结果是一个bool。HandleUnauthorizedRequest函数则是在AuthorizeCore返回结果是false时会调用的函数。

AuthorizeAttribute属性置于Action前,在调用Action前会进行验证。

AuthorizeAttribute属性置于Controller类前,在调用Controller中任何Action前会进行验证。

 
  1. public class AppAuthorizeAttribute: AuthorizeAttribute

  2. {

  3. /// <summary>

  4. /// 验证入口

  5. /// </summary>

  6. /// <param name="filterContext"></param>

  7. public override void OnAuthorization(AuthorizationContext filterContext)

  8. {

  9. base.OnAuthorization(filterContext);

  10. }

  11.  
  12.  
  13. protected override bool AuthorizeCore(HttpContextBase httpContext)

  14. {

  15. JwtHelper pHelper = new JwtHelper();

  16. try

  17. {

  18. //前端请求api时会将token存放在名为"auth"的请求头中

  19. var authHeader = httpContext.Request.Headers["auth"];

  20. if (authHeader == null)

  21. {

  22. httpContext.Response.StatusCode = 403;

  23. return false;

  24. }

  25.  
  26.  
  27. var userinfo = pHelper.DecodeJwt(authHeader);

  28. if (userinfo != null)

  29. return true;

  30.  
  31. httpContext.Response.StatusCode = 403;

  32. return false;

  33. }

  34. catch

  35. {

  36. httpContext.Response.StatusCode = 403;

  37. return false;

  38. }

  39. }

  40.  
  41. /// <summary>

  42. /// 验证失败处理

  43. /// </summary>

  44. /// <param name="filterContext"></param>

  45. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)

  46. {

  47.  
  48. base.HandleUnauthorizedRequest(filterContext);

  49. if (filterContext.HttpContext.Response.StatusCode == 403)

  50. {

  51. filterContext.Result = new RedirectResult("/Error");

  52. filterContext.HttpContext.Response.Redirect("/Home/Error");

  53. }

  54. }

  55. }

 

3.4 页面请求

 
  1. [AppAuthorize]

  2. public class PagingController : Controller

  3. {

  4. // GET: Home

  5. public ActionResult Index()

  6. {

  7. Models.UserInfo pUser = new Models.UserInfo()

  8. {

  9. Name = "Test",

  10. Age = 18

  11. };

  12. ViewBag.Name = "Xq_lureker";

  13. ViewBag.Age = "18";

  14. return View(pUser);

  15. }

  16. }

 

3.5 测试

3.5.1 生成Token

 

 

 

3.5.2 不带Token的页面请求

 

3.5.3 带Token的请求

 

参考:

https://blog.csdn.net/lxrj2008/article/details/75088780

https://www.cnblogs.com/xiaobai123/p/9242828.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值