본문 바로가기

SpringBoot

스프링 시큐리티 기본인증 + Rest API 테스트 예제

스프링 시큐리티 사용을 위한 설정 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package blue.coding.security.conf;
 
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
 
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
    // 시큐리티 설정
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests() // 요청 인증 관련 설정
                .anyRequest().authenticated() // 모든 요청은 인증되어야한다.
                .and()
                .httpBasic(); // 인증방법은 httpBasic을 사용한다.
                
    }
 
    
    // 인증 방법에 대한 설정
    @Autowired // AuthenticationManagerBuilder bean을 주입하기 위해 선언
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication() 
                .withUser("user")
                .password(passwordEncoder().encode("pw") )
                .authorities("ROLE_USER");
    }
    // 인증 알고리즘 설정
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 인증 알고리즘에 사용할 객체 세팅
    }
    
}
 
cs


스프링 시큐리티는 모든 요청에 대해 사용자에 대한 인증/권한을 설정 할 수 있다.

WebSecurityConfigurerAdapter 를 상속받은은 클래스에서 

@EnableWebSecurity를 사용해 기본 시큐리티 설정을 모두 끈뒤

configure메서드를 오버라이드 하여 어떤 요청이 인증되어야하는지, 인증방식은 무엇인지를 설정한다.

인증 방식을 어떻게 할것인가는 configureGlobal 메서드에서 설정을하며 인증을 위한 Bean을 주입받기위해 @Autowired를 사용한다.

예제 에서는 테스트를위해 inMemoryAuthentication인증방식을 사용하여 아이디/비밀번호/권한 직접 입력했다. 

패스워드를 암호화 하기위해 passwordEncoder메서드를 Bean으로 등록하고 인증 알고리즘을 사용하기위해 BCryptPasswordEncoder객체를 생성한다.


RestAPI 테스트를 위한 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package blue.coding.security.api;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class TestController {
    
    @GetMapping("/getTest")
    public String getTest() {
        return "성공";
    }
    
    @PostMapping("/postTest")
    public String postTest() {
        return "성공";
    }
}
 
cs


POSTMAN테스트

Get 테스트
ㅇㅇㅇ

아이디와 비밀번호를 입력하지 않았으므로 401 에러가 발생


아이디/비밀번호 입력후 200 ok 상태 반환


Post테스트


아이디와 비밀번호를 제대로 입력했는데도 403 에러가 발생한다.

403에러는 서버에 요청이 도달했으나 서버가 접근을 거부할때 발생하는 에러이다.

POST방식의 경우 크로스사이트 요청 위조 방지를 위해 데이터 전송시 csrf 토큰값이 없으면 접근을 거부한다.

폼 전송시 <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> 코드를 추가입력 해야한다.


하지만 테스트를 위한 view가 없으므로 아래와 같이 csrf 설정을 꺼둔뒤 테스트


1
2
3
4
5
6
7
8
9
10
11
12
 
    // 시큐리티 설정
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests() // 요청 인증 관련 설정
                .anyRequest().authenticated() // 모든 요청은 인증되어야한다.
                .and()
                .csrf().disable() // 크로스 사이트 요청 공격을 막기위한 토큰값에 관한 설정. 실제사용시 form에서 설정을 통해 값을 넘겨줘야함. 
                .httpBasic(); // 인증방법은 httpBasic을 사용한다.
                
    }
cs



참고

백기선님의 유투브(https://www.youtube.com/watch?v=zANzxwy4y3k)

https://www.baeldung.com/spring-security-basic-authentication