Java实战:Spring Boot实现无感刷新Token机制
    		       		warning:
    		            这篇文章距离上次修改已过425天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.Collection;
import java.util.Collections;
 
public class SecurityUtils {
 
    // 获取当前认证信息中的用户名
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            return authentication.getName();
        }
        return null;
    }
 
    // 获取当前用户的角色信息
    public static Collection<GrantedAuthority> getCurrentUserRoles() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof UsernamePasswordAuthenticationToken && !authentication.getAuthorities().isEmpty()) {
            return authentication.getAuthorities();
        }
        return Collections.singleton(new SimpleGrantedAuthority("GUEST"));
    }
 
    // 判断当前用户是否具有指定角色
    public static boolean hasCurrentUserThisRole(String role) {
        Collection<GrantedAuthority> userRoles = getCurrentUserRoles();
        return userRoles.stream().anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(role));
    }
}这个代码示例提供了一个简化版本的SecurityUtils类,用于在Spring Security环境中获取当前认证用户的用户名、角色信息以及判断用户是否具有特定角色。这个类可以被用在需要进行用户权限校验的服务中。
评论已关闭