본문 바로가기

웹 개발/스프링

[스프링 부트 심화] 스프링 시큐리티

0. 일단 우선 구현하기

- build.gradle에 스프링 시큐리티 dependency 추가 : 

    // 스프링 시큐리티
    implementation 'org.springframework.boot:spring-boot-starter-security'

- src > main > java > com.example > security > WebSecurityConfig

@Configuration
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // 이미지 폴더, CSS 폴더 관련된 리소스는 login 없이 허용합니다.
                .antMatchers("/images/**").permitAll().antMatchers("/css/**").permitAll()
                // 어떤 요청이든 '인증'
                .anyRequest().authenticated().and()
                // 로그인 기능 허용
                .formLogin().loginPage("/user/login").defaultSuccessUrl("/").failureUrl("/user/login?error").permitAll().and()
                // 로그아웃 기능 허용
                .logout().permitAll();
    }
}

 

1. 스프링 시큐리티 동작구조

 

2. 이해하기

- @Configuration : 스프링 설정 파일로서 @Component을 내부적으로 포괄하기 때문에  Bean으로 등록됩니다. 주로 @Bean과 함께 쓰여 수동으로 Bean을 등록할 때 사용됩니다.(싱글톤 보장, 참고1 , 참고2) 컴포넌트는 서버 시작 전 스프링 ComponentScan에의해 전부 읽혀 컨테이너에 POJO로 등록됩니다. 

 

- 스플링 시큐리티 설정 파일은 WebSecurirtyConfigurerAdapter 를 상속 받습니다. WebSecurityConfigurerAdapter 클래스는 스프링 시큐리티의 웹 보안 기능, 초기화, 설정 등을 담당합니다. 내부적으로 getHttp() 메서드가 실행될 때 HttpSecurity 클래스가 생성됩니다. 이 때 HttpSecurity는 인증/인가 API의 설정을 제공합니다. 

//WebSecurityConfigureAdapter.java파일의 일부

    protected final HttpSecurity getHttp() throws Exception {
		if (this.http != null) {
			return this.http;
		}    
		.....
        
        	if (!this.disableDefaults) {
			applyDefaultConfiguration(this.http); // defualt conf icuration적용		
            		.....   
                    
		}
		configure(this.http);
        // 이곳의 configure 메서드를 override하면 우리가 원하는 보안체계를 만들 수 있습니다.
		return this.http;
	}

	// 기본적으로 적용되는 filter들을 포함한 configuration 대한 메서드입니다.
	private void applyDefaultConfiguration(HttpSecurity http) throws Exception {
		http.csrf();
		http.addFilter(new WebAsyncManagerIntegrationFilter());
		http.exceptionHandling();
		http.headers();
		http.sessionManagement();
		http.securityContext();
		http.requestCache();
		http.anonymous();
		http.servletApi();
		http.apply(new DefaultLoginPageConfigurer<>());
		http.logout();
	}

즉, WebSecurityConfigurerAdapter는 내부적으로 getHttp() 메서드를 통해 인증, 인가 정보를 지닌 HttpSecurity를 반환하며 applyDefaultConfiguration과 configure를 거쳐 설정이 적용 됩니다. 따라서 우리는 인증/인가 설정이 담긴 HttpSecurity 정보를 바꿔주기위해 configure(HttpSecurity http) 메서드를 override 합니다. 

 

- 우리가 Override한 HttpSecurity 정책은 두 가지를 설정하고 있습니다. 인가 정책과 인증 정책입니다.

// 인가정책
http.authorizeRequests() // 요청에 보안 검사를 실행
        // 이미지 폴더, CSS 폴더 관련된 리소스는 login 없이 허용합니다.
        .antMatchers("/images/**").permitAll().antMatchers("/css/**").permitAll()
        // 어떤 요청이든 '인증'
        .anyRequest().authenticated();

// 인증정책 - 로그인
http.formLogin()
        .loginPage("/user/login").defaultSuccessUrl("/").failureUrl("/user/login?error").permitAll();
// 인증정책 - 로그아웃
http.logout().permitAll();

인가 정책을 살펴보도록 하겠습니다.

HttpSecurity 객체인 http에 인가와 관련된 여러 메소드들을 호출하고 있습니다. 

 

3. @EnableWebSecurity 

 

EnableWebSecurity (Spring Security 4.2.20.RELEASE API)

debug public abstract boolean debug Controls debugging support for Spring Security. Default is false. Returns: if true, enables debug support with Spring Security Default: false

docs.spring.io

Add this annotation to an @Configuration class to have the Spring Security configuration defined in any WebSecurityConfigurer or more likely by extending the WebSecurityConfigurerAdapter base class and overriding individual methods:

@EnableWebSecurity 어노테이션이 더해진 @Configuration 클래스는 Spring Security 설정을 활성화 합니다. WebSecurityConfigurer나 WebSecurityConfigurerAdapter를 기반으로한 클래스에서 개별적인 메소드들을 overriding해 줌으로서 설정들을 적용할 수 있습니다.