You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.2 KiB
44 lines
1.2 KiB
package com.project.ding.utils;
|
|
|
|
import org.springframework.security.core.Authentication;
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
import org.springframework.security.core.GrantedAuthority;
|
|
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
|
|
public class SecurityUtils {
|
|
/**
|
|
* 获取当前登录用户的 ID
|
|
*/
|
|
public static String getUserId() {
|
|
return getAuthentication()
|
|
.map(auth -> (String) auth.getPrincipal())
|
|
.orElse(null);
|
|
}
|
|
|
|
public static List<String> getUserRoles() {
|
|
return getAuthentication()
|
|
.map(auth -> auth.getAuthorities().stream()
|
|
.map(GrantedAuthority::getAuthority)
|
|
.toList())
|
|
.orElse(Collections.emptyList());
|
|
}
|
|
|
|
/**
|
|
* 判断当前用户是否拥有某个角色
|
|
* @param role 角色名称
|
|
*/
|
|
public static boolean hasRole(String role) {
|
|
return getUserRoles().contains(role);
|
|
}
|
|
|
|
|
|
/**
|
|
* 获取当前认证信息
|
|
*/
|
|
private static Optional<Authentication> getAuthentication() {
|
|
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
|
|
}
|
|
}
|
|
|