SecurityUtils.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package com.ruoyi.common.utils;
  2. import org.springframework.security.core.Authentication;
  3. import org.springframework.security.core.context.SecurityContextHolder;
  4. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  5. import com.ruoyi.common.constant.HttpStatus;
  6. import com.ruoyi.common.exception.CustomException;
  7. import com.ruoyi.framework.security.LoginUser;
  8. /**
  9. * 安全服务工具类
  10. *
  11. * @author ruoyi
  12. */
  13. public class SecurityUtils
  14. {
  15. /**
  16. * 获取用户账户
  17. **/
  18. public static String getUsername()
  19. {
  20. try
  21. {
  22. return getLoginUser().getUsername();
  23. }
  24. catch (Exception e)
  25. {
  26. throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
  27. }
  28. }
  29. /**
  30. * 获取用户
  31. **/
  32. public static LoginUser getLoginUser()
  33. {
  34. try
  35. {
  36. return (LoginUser) getAuthentication().getPrincipal();
  37. }
  38. catch (Exception e)
  39. {
  40. throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
  41. }
  42. }
  43. /**
  44. * 获取Authentication
  45. */
  46. public static Authentication getAuthentication()
  47. {
  48. return SecurityContextHolder.getContext().getAuthentication();
  49. }
  50. /**
  51. * 生成BCryptPasswordEncoder密码
  52. *
  53. * @param password 密码
  54. * @return 加密字符串
  55. */
  56. public static String encryptPassword(String password)
  57. {
  58. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  59. return passwordEncoder.encode(password);
  60. }
  61. /**
  62. * 判断密码是否相同
  63. *
  64. * @param rawPassword 真实密码
  65. * @param encodedPassword 加密后字符
  66. * @return 结果
  67. */
  68. public static boolean matchesPassword(String rawPassword, String encodedPassword)
  69. {
  70. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  71. return passwordEncoder.matches(rawPassword, encodedPassword);
  72. }
  73. /**
  74. * 是否为管理员
  75. *
  76. * @param userId 用户ID
  77. * @return 结果
  78. */
  79. public static boolean isAdmin(Long userId)
  80. {
  81. return userId != null && 1L == userId;
  82. }
  83. }