HttpSecurity 객체를 사용한 configure 함수 이해 및 requests 커스터마이징하기

서재환·2021년 12월 9일
0

SpringSecurity

목록 보기
3/5

Spring Security 기본골격

첫번째 Spring Security의 기본 함수를 살펴보고자 한다. 아래의 코드가 Spring Security
를 시작할 때 대개 접하게 되는 기본 코드이다. 코드를 보면 추상클래스를 상속받아서 클래스를
만든다.

해당 클래스 안에는 configure라는 method가 있고 HttpSecurity 객체를 DI로 받고 있다.
configure라는 method를 들어가 보면 아래와 같은 형태로 생겼는데 해석하면 이런 의미이다.

스프링 시큐리티는 기본적으로 모든 requests에 대해 인증을 받도록 설정이되어 있다. 다시말해
모든 requests가 막혀있다.

formLogin은 JSPs/HTMLs 의 requests를 의미하고 httpBasic() requests Postman으로부
터 오는 REST API 요청 같은 것이 해당된다.
@Configuration
public class ProjectSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
	http.authorizeReuqests().anyRequest().authenticated()
        .and().formLogin()
        .and().httpBasic();
    }
}

기본골격을 수정해서 특정 경로 인증을 설정하기

위의 코드 같은 경우 스프링시큐리티의 기본골격으로 모든 requests에 대한 인증을 요구하고 있다.
우리는 Override한 method를 일부 수정해서 특정 url로의 requests에 대해서만 인증을 처리하도
록 코드를 수정할 수 있다.

방법은 다음과 같다. 인증을 요구하는 특정 url에 대해 .antMatchers("/myBoard").authenticated()
과 같이 작성해 주면 된다.

또 어떤 url에 대해서는 인증을 요구를 배제하고 싶을 경우 .antMatchers("/contact").permitAll()
설정해 주면 된다.

@Configuration
public class ProjectSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
	http
    	.authorizeReuqests().anyRequest()
        .antMatchers("/myBoard").authenticated()
        .antMatchers("/contact").permitAll()
        .and().formLogin()
        .and().httpBasic();
    }
}

모든 requests를 거부하고 싶을 때

마지막으로 웹 어플리케이션 내에 있는 특정 api로의 요청을 거부하고 싶을 때에는 다음과 같이 작성하면
된다.

@Configuration
public class ProjectSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
	http
    	.authorizeReuqests().anyRequest()
        .denyAll()
    }
}

0개의 댓글

관련 채용 정보