postman 401 Unauthorized 오류

순두누나·2025년 5월 7일

트러블슈팅

목록 보기
4/8

API 테스트를 하던 중 401 unauthorized 오류 발생

원인 요약

Spring Boot 프로젝트에서 spring-boot-starter-security 의존성이 있으면, 기본적으로 모든 API 요청은 인증된 사용자만 접근 가능하게 설정되어있음. 그래서 로그인이나 회원가입 같은 비로그인 상태에서도 접근 가능한 API도 막혀버림.

✅ 해결 방법: 회원가입 API는 예외로 설정

🔧 방법: SecurityConfig 파일 수정하기

@Configuration + @EnableWebSecurity를 사용하는 설정 클래스를 하나 만들어서 회원가입 경로만 열어주면 됨.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/api/auth/register").permitAll()
                        .anyRequest().authenticated()
                );
                //.httpBasic().disable();
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

💡 위 설정은 /api/auth/register 요청에 대해서는 인증 없이 접근할 수 있게 해주는 거.

여기서 URL 확인하는 법!

: Controller.java 파일에 들어가서
@RequestMapping("/api/auth")@PostMapping("/register") 이 합쳐진 게 URL!

profile
순두의 누나입니다

0개의 댓글