Authorization.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.aizuda.boot.config;
  2. import com.aizuda.boot.system.service.ISysResourceApiService;
  3. import com.aizuda.service.web.UserSession;
  4. import com.baomidou.kisso.SSOAuthorization;
  5. import com.baomidou.kisso.security.token.SSOToken;
  6. import com.github.benmanes.caffeine.cache.Cache;
  7. import com.github.benmanes.caffeine.cache.Caffeine;
  8. import jakarta.annotation.Resource;
  9. import org.apache.commons.collections.CollectionUtils;
  10. import org.springframework.stereotype.Component;
  11. import java.util.List;
  12. import java.util.concurrent.TimeUnit;
  13. /**
  14. * 权限授权处理器
  15. *
  16. * @author 青苗
  17. * @since 2021-11-16
  18. */
  19. @Component
  20. public class Authorization implements SSOAuthorization {
  21. @Resource
  22. private ISysResourceApiService sysResourceApiService;
  23. /**
  24. * 用户权限编码列表缓存 15 分钟
  25. */
  26. protected Cache<Long, List<String>> codeListCache = Caffeine.newBuilder()
  27. .expireAfterWrite(15, TimeUnit.MINUTES)
  28. .maximumSize(1000)
  29. .build();
  30. /**
  31. * 用户权限编码校验缓存 5 分钟
  32. */
  33. protected Cache<String, Boolean> codeCache = Caffeine.newBuilder()
  34. .expireAfterWrite(5, TimeUnit.MINUTES)
  35. .maximumSize(6000)
  36. .build();
  37. @Override
  38. public boolean isPermitted(SSOToken token, String permission) {
  39. Long userId = Long.valueOf(token.getId());
  40. if (UserSession.isAdmin(userId)) {
  41. // 超级管理员免鉴权
  42. return true;
  43. }
  44. final String key = userId + permission;
  45. Boolean legalKey = codeCache.getIfPresent(key);
  46. if (null != legalKey) {
  47. return legalKey;
  48. }
  49. List<String> codeList = codeListCache.getIfPresent(userId);
  50. if (CollectionUtils.isEmpty(codeList)) {
  51. codeList = sysResourceApiService.listCodesByUserId(userId);
  52. codeListCache.put(userId, codeList);
  53. }
  54. // 判断当前权限编码是否存在
  55. legalKey = codeList.contains(permission);
  56. codeCache.put(key, legalKey);
  57. return legalKey;
  58. }
  59. }