SecurityUtils.java 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package com.ruoyi.common.utils;
  2. import java.nio.charset.StandardCharsets;
  3. import java.security.MessageDigest;
  4. import java.util.Base64;
  5. import java.util.Collection;
  6. import java.util.List;
  7. import java.util.stream.Collectors;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.context.SecurityContextHolder;
  10. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  11. import org.springframework.util.PatternMatchUtils;
  12. import com.ruoyi.common.constant.Constants;
  13. import com.ruoyi.common.constant.HttpStatus;
  14. import com.ruoyi.common.core.domain.entity.SysRole;
  15. import com.ruoyi.common.core.domain.model.LoginUser;
  16. import com.ruoyi.common.exception.ServiceException;
  17. /**
  18. * 安全服务工具类
  19. *
  20. * @author ruoyi
  21. */
  22. public class SecurityUtils
  23. {
  24. /**
  25. * 用户ID
  26. **/
  27. public static Long getUserId()
  28. {
  29. try
  30. {
  31. return getLoginUser().getUserId();
  32. }
  33. catch (Exception e)
  34. {
  35. throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
  36. }
  37. }
  38. /**
  39. * 获取部门ID
  40. **/
  41. public static Long getDeptId()
  42. {
  43. try
  44. {
  45. return getLoginUser().getDeptId();
  46. }
  47. catch (Exception e)
  48. {
  49. throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
  50. }
  51. }
  52. /**
  53. * 获取用户账户
  54. **/
  55. public static String getUsername()
  56. {
  57. try
  58. {
  59. return getLoginUser().getUsername();
  60. }
  61. catch (Exception e)
  62. {
  63. throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
  64. }
  65. }
  66. /**
  67. * 获取用户
  68. **/
  69. public static LoginUser getLoginUser()
  70. {
  71. try
  72. {
  73. return (LoginUser) getAuthentication().getPrincipal();
  74. }
  75. catch (Exception e)
  76. {
  77. throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
  78. }
  79. }
  80. /**
  81. * 获取Authentication
  82. */
  83. public static Authentication getAuthentication()
  84. {
  85. return SecurityContextHolder.getContext().getAuthentication();
  86. }
  87. // 可选的加盐密钥,可以从配置文件中读取
  88. private static final String SM3_SECRET = "your-sm3-secret-key";
  89. /**
  90. * 生成BCryptPasswordEncoder密码
  91. *
  92. * @param password 密码
  93. * @return 加密字符串
  94. */
  95. public static String encryptPassword(String password)
  96. {
  97. /* BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  98. return passwordEncoder.encode(password);*/
  99. try {
  100. // 密码+密钥进行SM3哈希
  101. String passwordToEncode = password + SM3_SECRET;
  102. MessageDigest sm3 = MessageDigest.getInstance("SM3", "BC");
  103. byte[] hash = sm3.digest(passwordToEncode.getBytes(StandardCharsets.UTF_8));
  104. // Base64编码存储
  105. return Base64.getEncoder().encodeToString(hash);
  106. } catch (Exception e) {
  107. throw new RuntimeException("SM3密码加密失败", e);
  108. }
  109. }
  110. /**
  111. * 判断密码是否相同
  112. *
  113. * @param rawPassword 真实密码
  114. * @param encodedPassword 加密后字符
  115. * @return 结果
  116. */
  117. public static boolean matchesPassword(String rawPassword, String encodedPassword)
  118. {
  119. /* BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  120. return passwordEncoder.matches(rawPassword, encodedPassword);*/
  121. if (rawPassword == null || encodedPassword == null) {
  122. return false;
  123. }
  124. try {
  125. // 使用相同的逻辑计算输入密码的哈希值
  126. String passwordToCheck = rawPassword + SM3_SECRET;
  127. MessageDigest sm3 = MessageDigest.getInstance("SM3", "BC");
  128. byte[] hash = sm3.digest(passwordToCheck.getBytes(StandardCharsets.UTF_8));
  129. String checkEncoded = Base64.getEncoder().encodeToString(hash);
  130. return encodedPassword.equals(checkEncoded);
  131. } catch (Exception e) {
  132. return false;
  133. }
  134. }
  135. /**
  136. * 是否为管理员
  137. *
  138. * @param userId 用户ID
  139. * @return 结果
  140. */
  141. public static boolean isAdmin(Long userId)
  142. {
  143. return userId != null && 1L == userId;
  144. }
  145. /**
  146. * 验证用户是否具备某权限
  147. *
  148. * @param permission 权限字符串
  149. * @return 用户是否具备某权限
  150. */
  151. public static boolean hasPermi(String permission)
  152. {
  153. return hasPermi(getLoginUser().getPermissions(), permission);
  154. }
  155. /**
  156. * 判断是否包含权限
  157. *
  158. * @param authorities 权限列表
  159. * @param permission 权限字符串
  160. * @return 用户是否具备某权限
  161. */
  162. public static boolean hasPermi(Collection<String> authorities, String permission)
  163. {
  164. return authorities.stream().filter(StringUtils::hasText)
  165. .anyMatch(x -> Constants.ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, permission));
  166. }
  167. /**
  168. * 验证用户是否拥有某个角色
  169. *
  170. * @param role 角色标识
  171. * @return 用户是否具备某角色
  172. */
  173. public static boolean hasRole(String role)
  174. {
  175. List<SysRole> roleList = getLoginUser().getUser().getRoles();
  176. Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
  177. return hasRole(roles, role);
  178. }
  179. /**
  180. * 判断是否包含角色
  181. *
  182. * @param roles 角色列表
  183. * @param role 角色
  184. * @return 用户是否具备某角色权限
  185. */
  186. public static boolean hasRole(Collection<String> roles, String role)
  187. {
  188. return roles.stream().filter(StringUtils::hasText)
  189. .anyMatch(x -> Constants.SUPER_ADMIN.equals(x) || PatternMatchUtils.simpleMatch(x, role));
  190. }
  191. }