华恒Mes鼎捷代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.3 KiB

5 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Http;
  6. using System.Web.Http.Controllers;
  7. using JWT;
  8. using WebApplication1;
  9. using ICSSoft.Frame.Data.Entity;
  10. using System.Net.Http;
  11. using Newtonsoft.Json;
  12. using System.Web.Http.Filters;
  13. namespace WebApplication1.Attributes
  14. {
  15. public class ApiAuthorize : AuthorizeAttribute
  16. {
  17. public override void OnAuthorization(HttpActionContext actionContext)
  18. {
  19. var authorization = actionContext.Request.Headers.Authorization;
  20. if ((authorization != null) && (authorization.Parameter != null))
  21. {
  22. //校验Token是否合法
  23. try
  24. {
  25. if (JwtHelper.Validate(authorization.Parameter))
  26. {
  27. base.IsAuthorized(actionContext);
  28. }
  29. }
  30. catch (Exception ex)
  31. {
  32. HttpContext.Current.Items.Add("error", ex.Message);
  33. HandleUnauthorizedRequest(actionContext);
  34. }
  35. }
  36. //接口需要权限认证,但无Token,返回拒绝响应此请求
  37. else
  38. {
  39. var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
  40. bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
  41. if (isAnonymous) base.OnAuthorization(actionContext);
  42. else
  43. {
  44. HttpContext.Current.Items.Add("error", "请传入tocken值!");
  45. HandleUnauthorizedRequest(actionContext);
  46. }
  47. }
  48. }
  49. protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
  50. {
  51. base.HandleUnauthorizedRequest(actionContext);
  52. actionContext.Response.StatusCode = System.Net.HttpStatusCode.Forbidden;
  53. var result = new Result()
  54. {
  55. code = "400",
  56. msg = HttpContext.Current.Items["error"].ToString()
  57. };
  58. actionContext.Response.Content = new StringContent(JsonConvert.SerializeObject(result));
  59. }
  60. }
  61. }