๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/Spring

Spring Security ์ค‘๋ณต ๋กœ๊ทธ์ธ ๋ฐฉ์ง€ ์„ค์ •

by 1mj 2022. 3. 15.

WebSecurityConfigurerAdapter๋ฅผ ๊ตฌํ˜„ํ•œ Spring Security ์„ค์ • ํŒŒ์ผ ๋‚ด ์•„๋ž˜์™€ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

 

http
    .sessionManagement()
    .maximumSessions(1)
    .maxSessionsPreventsLogin(false)
    .expiredUrl("/login")
    .sessionRegistry(sessionRegistry());

 

- maximumSessions ์ตœ๋Œ€ ์œ ์ง€ ๊ฐ€๋Šฅํ•œ ์„ธ์…˜ ์ˆ˜๋Š” 1๋กœ ์„ค์ •

- maxSessionsPreventsLogin ์€ ์ค‘๋ณต ๋กœ๊ทธ์ธ์ด ๋˜์—ˆ์„ ๋•Œ ๋จผ์ € ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋ฅผ ์„ธ์…˜ ์•„์›ƒ ์‹œํ‚ค๋ ค๋ฉด false, ๋‚˜์ค‘์— ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๋ฅผ ํŠ•๊ธฐ๋ ค๋ฉด true๋กœ ์„ค์ •

 

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	(...)
	
    // logout ํ›„ loginํ•  ๋•Œ ์ •์ƒ๋™์ž‘์„ ์œ„ํ•œ ์„ธ์…˜ ๋ ˆ์ง€์ŠคํŠธ๋ฆฌ ์„ค์ •
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http
    		.sessionManagement()
    		.maximumSessions(1)
    		.maxSessionsPreventsLogin(false)
    		.expiredUrl("/login")
    		.sessionRegistry(sessionRegistry());
    	
        (...)
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // static ๋””๋ ‰ํ„ฐ๋ฆฌ์˜ ํ•˜์œ„ ํŒŒ์ผ ๋ชฉ๋ก์€ ์ธ์ฆ ๋ฌด์‹œ
        web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/webfont/**");
    }
}

 

์ค‘์š”ํ•œ ์ ์€ UserDetailService๋ฅผ ๊ตฌํ˜„ํ•œ ์„œ๋น„์Šค ๋‚ด ์ธ์ฆ์„ ๋‹ด๋‹นํ•  ๊ฐ์ฒด๋Š” equals์™€ hashcode๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•ด์ฃผ์–ด ๊ณ„์ •ID๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ๊ฐ™์€ ๊ฐ์ฒด๋กœ ์ธ์‹๋˜๋„๋ก ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

๋กฌ๋ณต ์‚ฌ์šฉ ์‹œ ์•„๋ž˜์™€ ๊ฐ™์€ ์–ด๋…ธํ…Œ์ด์…˜์œผ๋กœ ๊ฐ„๋‹จํ•˜๊ฒŒ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

@EqualsAndHashCode(of= {"user"})
public class UserPrincipal implements UserDetails { ... }

 

ํฌ๋กฌ์—์„œ ํ…Œ์ŠคํŠธ ํ•ด๋ณด๋ ค๋ฉด ์‹œํฌ๋ฆฟ ์ฐฝ์„ ํ•˜๋‚˜ ์—ด๊ณ  ์ฐจ๋ก€๋กœ ๋กœ๊ทธ์ธํ•ด๋ณด๋ฉด ์ค‘๋ณต ๋กœ๊ทธ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

๋Œ“๊ธ€