• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

/api/hello에 접근이 안됩니다 ㅠㅠ

23.11.30 17:16 작성 조회수 475

0

package NewYear.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

//기본적인 웹 보안을 활성화 하는 어노테이션
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {


    @Bean
    public WebSecurityCustomizer configure() {
        return (web) -> web.ignoring()
                .requestMatchers(new AntPathRequestMatcher("/h2-console/**"))
                .requestMatchers(new AntPathRequestMatcher("/favicon.ico"));
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((registry) ->
                        registry.requestMatchers(new AntPathRequestMatcher("/api/hello")).permitAll()
                                .anyRequest().authenticated()
                )
                .build();
    }
}

@EnableWebSecurity를 비활성화도 해보고 커뮤니티에 올라온 코드로 다 해봤는 데 접근이 401에러로 접근이 안되는 것 같습니다 ㅠㅠ 해결방안이 있을까요 스프링부트 버전은 3.2.0입니다

답변 1

답변을 작성해보세요.

1

미묘한채널님의 프로필

미묘한채널

2023.11.30

스프링부트의 build 종속성에 spring security가 들어 있으면 자동적으로 시큐리티가 활성화 됩니다.
따라서 @EnableWebSecurity를 빼셔도 시큐리티가 작동하고 api 요청에 대한 권한이 필요한데 이 부분이 없기 때문에 401 unauthorized가 발생합니다.

간단한 방법 두 가지를 제안해 드리는데 문제 해결에 도움이 됐으면 좋겠습니다.


1. 종속성에서 spring security를 빼고 종속성을 새로 고침해주세요. 물론 이렇게 할 경우에는 시큐리티가 비활성화됩니다.

2. 스프링 시큐리티를 활성화 하고 싶은데 잘 안되는 거라면 아래의 코드처럼 진행해보시면 좋겠습니다. 특별한 이유로 new AntPathRequestMatcher를 써야한다면 사용방법을 익히시고 공식문서에서 해당 클래스의 사용 방법에 대한 제안하는 부분이 나와 있으므로 그 부분을 참고하시어 사용해보시면 좋을 것 같습니다. ㅎㅎ
https://docs.spring.io/spring-security/reference/5.8/migration/servlet/config.html

  @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((registry) ->
                        registry.requestMatchers("/api/hello")
                                .permitAll()
                                .anyRequest().authenticated())
                .build();
    }
다이니님의 프로필

다이니

질문자

2023.11.30

답변 감사합니다 !!!

/api/hello 경로에 대해서만 접근 제한을 풀고 싶은 데 앞서 주신 코드로 진행해보아도 401에러가 뜹니다 ㅠㅠ

주신 코드 외에 다른 방식으로도 접근해보았는 데 전부 접근제한이 풀리지 않는 듯 해요 ㅠㅠ 무엇이 문제인지 모르겠습니다 ㅠㅠ

미묘한채널님의 프로필

미묘한채널

2023.11.30

혹시 컨트롤러 부분도 보여주실 수 있을까요?

다이니님의 프로필

다이니

질문자

2023.11.30

@RestController
@RequestMapping("/api")
public class HelloController {
    @GetMapping("/hello")
    public ResponseEntity<String> hello() {
        return ResponseEntity.ok("hello");
    }
}

컨트롤러 부분입니다 !

미묘한채널님의 프로필

미묘한채널

2023.12.01

종속성에는 이렇게만 설정하고

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

스프링 부트 3.2에서 빌드는 이렇게 두 개로 하고 config와 controller도 동일하게 작성해서 실행해보았습니다.

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {


    @Bean
    public WebSecurityCustomizer configure() {
        return (web) -> web.ignoring()
                .requestMatchers(new AntPathRequestMatcher("/h2-console/**"))
                .requestMatchers(new AntPathRequestMatcher("/favicon.ico"));
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((registry) ->
                        registry.requestMatchers("/api/hello")//new AntMatchers로도 정상작동
                                .permitAll()
                                .anyRequest().authenticated()
                )
                .build();
    }
}

HelloController

@RestController
@RequestMapping("/api")
public class HelloController {
    @GetMapping("/hello")
    public ResponseEntity<String> hello() {
        return ResponseEntity.ok("hello");
    }
}

결과는 아래와 같이 잘 나오고 있습니다.

image

스프링 시큐리티는 버전에 따라서 방식이 조금씩 바뀌는 부분들이 있어서 그런 부분들을 공식문서를 보면서 적용해줘야하지만 글쓴이님의 코드는 스프링 부트 3.2에서 정상 작동하는 것으로 보입니다.

 

시큐리티와 관련 있는 부분들 config, 실행 애플리케이션, 환경 설정 파일 등을 확인해보시면 좋을 것 같습니다.

해결이 잘 됐으면 좋겠습니다. ㅎㅎ..

다이니님의 프로필

다이니

질문자

2023.12.01

저번 데이터베이스때부터 답변 정말 감사합니다 !!!!!

근데 해결이 안되었습니다 ㅠㅠ 어떤 걸로 해도 안되는 듯하여 시큐리티 외에 인증 인가 방식을 공부한 후에 로그인 회원가입을 구현하려고 합니다..! 도움 주셔서 정말 감사합니다 !

덕분에 알아간 지식들이 많았습니다 좋은 주말 보내세요 ㅎㅎ