티스토리 뷰

 

build.gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

 

SpringBoot 2.7.0이상

 

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig{

    @Bean
    public BCryptPasswordEncoder encodePwd(){
        return new BCryptPasswordEncoder(); // password를 인코딩 해줄때 쓰기 위함
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .httpBasic().disable()
                .csrf().disable()
                .cors().and()
                .authorizeRequests()
                .antMatchers("/api/v1/users/join", "api/v1/users/login").permitAll() // join, login은 언제나 가능
                .antMatchers("/api/**").authenticated() // 다른 api는 인증 필요
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt사용하는 경우 씀
                .and().build();
    }
}

 

적용 순서

통제 정책들이 위에서 아래 순서로 적용이 됩니다.

위에서 .antMatchers("/api/**")에 .authenticated()를 .permitAll()로 바꿔서 모든 endpoint에 인증을 하지 않도록 처리 하고 싶은 경우 순서를 바꾸지 않고 .permitAll()로만 바꾸는 경우 계속 DENY가 나옵니다. 그래서 순서를 아래와 같이 처리 해주어야 합니다.

 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .httpBasic().disable()
                .csrf().disable()
                .cors().and()
                .authorizeRequests()
                .antMatchers("/api/**").permitAll() // 다른 api는 인증 필요
                .antMatchers("/api/v1/users/join", "/api/v1/users/login").permitAll() // join, login은 언제나 가능
//                .antMatchers("/api/**").authenticated() // 다른 api는 인증 필요
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt사용하는 경우 씀
                .and().build();
    }

여기에서 문제는 아래에 있는 .antMatchers("/api/v1/users/join", "/api/v1/users/login").permitAll() 는 의미가 없어집니다. 이미 앞에서 모두 허용하기 때문입니다.

 

 

POST만 인증된 사용자인지 Check

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity
            .httpBasic().disable()
            .csrf().disable()
            .cors().and()
            .authorizeRequests()
            .antMatchers("/api/v1/users/join", "/api/v1/users/login").permitAll() // join, login은 언제나 가능
            .antMatchers(HttpMethod.POST, "/api/**").authenticated() // 모든 post요청을 인증된사용자인지 check합니다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함