FunctionCodeAttribute.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Bowin.Common.Cache;
  2. using Bowin.Common.JSON;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Security.Claims;
  8. namespace Bowin.Common.ServiceToken.Permission
  9. {
  10. public class FunctionCodeAttribute : ActionFilterAttribute
  11. {
  12. public List<string> FunctionCodes { get; set; }
  13. public FunctionCodeAttribute(params string[] functionCodes)
  14. {
  15. FunctionCodes = functionCodes.ToList();
  16. }
  17. public override void OnActionExecuting(ActionExecutingContext context)
  18. {
  19. base.OnActionExecuting(context);
  20. if (JwtHelper.GetFunctionCodeMethod != null)
  21. {
  22. var userClaim = context.HttpContext.User.FindFirst(ClaimTypes.Name); //context.HttpContext.User.FindFirst(ClaimTypes.Role);
  23. if (userClaim == null)
  24. {
  25. throw new Exception("未授权的操作。");
  26. }
  27. var roleCache = (string)CacheHelper.Get("rinfo_" + userClaim.Value);
  28. if (roleCache == null)
  29. {
  30. roleCache = JwtHelper.GetFunctionCodeMethod.Invoke(userClaim.Value).ToJson();
  31. CacheHelper.Add("rinfo_" + userClaim.Value, roleCache);
  32. }
  33. var userFunctionCodes = roleCache.ToObject<List<string>>();
  34. if (userFunctionCodes.Intersect(FunctionCodes).Count() == 0)
  35. {
  36. throw new Exception("未授权的操作。");
  37. }
  38. }
  39. }
  40. }
  41. }