spring security 获取当前用户信息及权限

spring security 获取当前用户信息及权限

一、在程序中获取用户信息

UserDetails userDetails = (UserDetails);
SecurityContextHolder.getContext().getAuthentication().getPrincipal();

在程序中获取权限信息

 Collection authorities = userDetails.getAuthorities();

二、进行封装

UserService.java

public interface UserService {

	......

/**
     * 获取当前用户信息
     * @return
     */
    User getUser();

    /**
     * 获取当前用户的权限
     * @return
     */
    Collection getUserAuthorities();
	......

}

UserServiceImpl .java

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

	......

@Override
    public User getUser() {

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User)userDetails;
        return user;
    }

    @Override
    public Collection getUserAuthorities() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
															 .getAuthentication()
															 .getPrincipal();
        Collection authorities = userDetails.getAuthorities();
        return authorities;
    }
    ......
}

*用户登录根据角色跳转至不同页面

你可能感兴趣的:(spring,boot)