Spring Security

스프링 시큐리티 중복로그인 안될 때 해결방법

dev.mk 2023. 11. 3. 10:44
반응형

일반적인 스프링시큐리티 중복로그인 설정을 하였지만 여러 문제가 발생

1. 서로 다른 브라우저로 동일회원 로그인로그인처리가 되는 문제 

2. 로그아웃하고 로그인하면 Maximum sessions of 1 for this principal exceeded 에러 발생

3. 브라우저를 강제로 종료후 다시 로그인하면 Maximum sessions of 1 for this principal exceeded 에러 발생

 

 

1.  시큐리티 설정파일에 ServletListenerRegistrationBean, SessionRegistry으로 등록한다.

 

SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig {

    //추가
    @Bean
    ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }
    
    //추가
    @Bean
    SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    
    .... 생략
    
    }
    //중복로그인 관련 설정
    .sessionManagement( sessionManagement -> 	
        sessionManagement
        .maximumSessions(1)
        .maxSessionsPreventsLogin(false)	
        .sessionRegistry(sessionRegistry())
    );
}

 

 

 

2. UserDetails를 구현한 구현체 에서 @EqualsAndHashCod 어노테이션 선언

//회원 DTO
@Data
@EqualsAndHashCode(of = "memberId")
public class MemberDTO implements UserDetails {

    private static final long serialVersionUID = 1L;
    private Long MemberNo;
    private String memberId;
    private String memberPwd;
...생략

}

 

UserDetails를 구현한 구현체 에서 (MemberDTO.java) @EqualsAndHashCod 어노테이션을 선언하고 loadUserByUsername 메소드에 조회 조건으로 사용하는 변수명으로 선언한다.

 

AuthenticationService.java

public UserDetails loadUserByUsername(String memberId) throws UsernameNotFoundException

 

그럼 중복로그인 설정으로 발생했던 온갖오류가 해결된다.

반응형