[Spring Boot] 세션 기반 유저 정보

Coco Park·2024년 1월 10일
0

Spring_Boot

목록 보기
8/13

현재 메인 페이지에 구현되어 있는 정보로써 DB에서 데이터를 받아오는 것이 아닌 세션에서 현재 로그인된 세션을 받아오는 방법을 소개하고자 한다.

현재 세션에 등록되어 있는 유저의 정보를 받는 방법은 다음 코드로 구현할 수 있다.

// id
String id = SecurityContextHolder.getContext().getAuthentication().getName();
// role
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> collection = auth.getAuthorities();
Iterator<? extends GrantedAuthority> iterator = collection.iterator();
GrantedAuthority grantedAuthority = iterator.next();
String role = grantedAuthority.getAuthority();

추가적으로 세션에 대한 설정도 할 수 있다.

해당 내용은 SecurityConfig에서 설정할 수 있고 다음과 같다.

http.sessionManagement((auth) -> auth
						.maximumSessions(1) // 최대 중복 로그인 수
                        .maxSessionsPreventsLogin(true));
                        /*
                            최대 세션을 초과하는 경우 기존 계정을 처리하는 방법
                            TRUE : 새로운 로그인을 차단
                            FALSE : 기존 로그인 중인 세션 하나를 로그아웃
                        */
http.sessionManagement((auth) -> auth.sessionFixation().changeSessionId());
                       /*
                          none : 세션 정보 변경 안함
                          newSession : 세션 정보를 변경
                          changeSessionId : 세션은 동일하나 id 값을 변경함
                       */
profile
ヽ(≧□≦)ノ

0개의 댓글