403 Forbidden [spinrg security]

jbong·2024년 8월 11일
0

스프링부트

목록 보기
3/15

403 Forbidden

백엔드 기능 구현 중 스프링 시큐리티를 구현하면서 403 에러가 발생하였다.
403 Forbidden 에러는 클라이언트가 요청한 리소스에 대한 접근 권한이 없음을 의미하며, 엑세스 권한이 거부 되었음을 나타낸다.

🎈해결방법

Spring Security는 POST, PUT 등의 업데이트 요청에 대해 요청 헤더의 일부로 CSRF 토큰을 제공하도록 하는 CSRF 필터를 기본적으로 사용하는데, 기본적으로 적용된 CSRF 필터에서 CSRF 토큰을 요구한다.

첫 번째는,

httpSecurity
	.csrf().disable()

를 적용하여 해결할 수 있는데, 이를 마음대로 비활성화하는 것은 좋지 않는데, 이를 비활성화 시키고, 때에 따라 방어 코드를 작성하여 대비하는 것이 방법

두 번째는,

package com.example.TodoList.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.OAuth2ClientDsl;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //csrf disable
        http
                .csrf((auth) ->auth.disable());
        //form 로그인 방식 disable
        http
                .formLogin((auth) -> auth.disable());
        //basic 인증 방식 disable
        http
                .httpBasic((auth) -> auth.disable());
        http
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers(new AntPathRequestMatcher("/**")).permitAll()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .anyRequest().authenticated());
        http
                .sessionManagement((session) -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
                return http.build();
    }
}

에서 /** 으로 모든 권한이 접근 가능하도록 수행하게 하였다.
(때에 따라 필요한 상황이 생기면 엔드포인트를 추가하는 방식으로 하는 것도 나쁘지 않은듯)

profile
노력하는 개미

0개의 댓글