본문 바로가기
Back-end

[Spring Security] 로그인한 사용자의 아이디와 권한(Role) 가져오기

by yeobi 2024. 5. 20.

 

로그인한 사용자 아이디

String id = SecurityContextHolder.getContext().getAuthentication().getName();

 

 

로그인한 사용자의 권한 구하기

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
Iterator<? extends GrantedAuthority> iter = authorities.iterator();
GrantedAuthority auth = iter.next();

String role = auth.getAuthority();

 

 

위 방식으로 로그인한 사용자가 쓴 글인지 일치여부를 확인할 수 있고,

특정 접근 권한이 있는 사용자만 특정 페이지에 접근할 수 있도록 설정할 수 있다.