SecurityUtils.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2019-2020 Zheng Jie
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package me.zhengjie.utils;
  17. import cn.hutool.json.JSONArray;
  18. import cn.hutool.json.JSONObject;
  19. import cn.hutool.json.JSONUtil;
  20. import lombok.extern.slf4j.Slf4j;
  21. import me.zhengjie.exception.BadRequestException;
  22. import org.springframework.http.HttpStatus;
  23. import org.springframework.security.core.Authentication;
  24. import org.springframework.security.core.context.SecurityContextHolder;
  25. import org.springframework.security.core.userdetails.UserDetails;
  26. import java.util.List;
  27. /**
  28. * 获取当前登录的用户
  29. * @author Zheng Jie
  30. * @date 2019-01-17
  31. */
  32. @Slf4j
  33. public class SecurityUtils {
  34. /**
  35. * 获取当前登录的用户
  36. * @return UserDetails
  37. */
  38. public static UserDetails getCurrentUser() {
  39. final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  40. if (authentication == null) {
  41. throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
  42. }
  43. if (authentication.getPrincipal() instanceof UserDetails) {
  44. UserDetails userDetails = (UserDetails) authentication.getPrincipal();
  45. return userDetails;
  46. }
  47. throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");
  48. }
  49. /**
  50. * 获取系统用户名称
  51. *
  52. * @return 系统用户名称
  53. */
  54. public static String getCurrentUsername() {
  55. UserDetails userDetails = getCurrentUser();
  56. return userDetails.getUsername();
  57. }
  58. /**
  59. * 获取当前用户的数据权限
  60. * @return /
  61. */
  62. public static List<Long> getCurrentUserDataScope(){
  63. UserDetails userDetails = getCurrentUser();
  64. JSONArray array = JSONUtil.parseArray(new JSONObject(userDetails).get("dataScopes"));
  65. return JSONUtil.toList(array,Long.class);
  66. }
  67. }