ApiTokenAttribute.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.AspNetCore.Mvc.Filters;
  3. using TEAMModelOS.SDK.Extension;
  4. using System;
  5. using TEAMModelOS.Models;
  6. using Microsoft.Extensions.Options;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using System.Linq;
  10. namespace TEAMModelOS.Filter
  11. {
  12. public class ApiTokenAttribute : Attribute, IFilterFactory
  13. {
  14. public bool IsReusable => true;
  15. //public string Roles { get; set; }
  16. //public string Permissions { get; set; }
  17. public IFilterMetadata CreateInstance(IServiceProvider services)
  18. {
  19. var option = services.GetService<IOptions<Option>>();
  20. return new InternalAuthTokenFilter(option);
  21. }
  22. private class InternalAuthTokenFilter : IResourceFilter
  23. {
  24. private readonly Option _option;
  25. //private readonly string _roles;
  26. //private readonly string _permissions;
  27. public InternalAuthTokenFilter(IOptions<Option> option)
  28. {
  29. _option = option.Value;
  30. //_roles = roles;
  31. //_permissions = permissions;
  32. }
  33. public void OnResourceExecuting(ResourceExecutingContext context)
  34. {
  35. bool pass = false;
  36. string id = string.Empty, name = string.Empty, school = string.Empty,jti=string.Empty;
  37. var authtoken = context.HttpContext.GetXAuth("ApiToken");
  38. if (!string.IsNullOrWhiteSpace(authtoken) && JwtAuthExtension.ValidateApiToken(authtoken, _option.JwtSecretKey))
  39. {
  40. var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
  41. id = jwt.Payload.Sub;
  42. school = jwt.Payload.Azp;
  43. jti = jwt.Payload.Jti;
  44. name = jwt.Claims.FirstOrDefault(claim => claim.Type == "name")?.Value;
  45. //处理限流问题
  46. if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(school) && !string.IsNullOrEmpty(name)&& !string.IsNullOrEmpty(jti))
  47. {
  48. pass = true;
  49. }
  50. else {
  51. }
  52. }
  53. if (pass)
  54. {
  55. context.HttpContext.Items.Add("ID", id);
  56. context.HttpContext.Items.Add("Name", name);
  57. context.HttpContext.Items.Add("School", school);
  58. }
  59. else
  60. context.Result = new UnauthorizedResult();
  61. }
  62. public void OnResourceExecuted(ResourceExecutedContext context)
  63. {
  64. }
  65. }
  66. }
  67. }