• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

최신 spring security 기준 web.ignoring 관련 질문입니다

24.01.15 06:00 작성 24.01.15 06:18 수정 조회수 484

0

현재 최신 spring security 및 spring 3.2.1 버전을 사용중입니다.

강의 섹션 3-2번강의에서 web.ignoring 설정이 현재 SecurityFilterChain에는 어떻게 적용해야 될지 몰라 찾아보던 중 아래와 같은 자료를 발견하였습니다.

해당 자료는 spring security 관련

https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html#favor-permitall

위의 주소에서 확인하였는데 이부분과 관련하여 질문드립니다. 최신 버전에서는 위의 사진과 같이 코드를 사용하는게 좋을까요? 만약 위와 같이 사용한다면 달라지는 부분이 있는지 궁금하여 질문드립니다. 현재 제가 작성한 코드는 아래와 같습니다.

추가한 부분은 css, js, img, favcon.ico, webjars 입니다

http
        .authorizeHttpRequests(Authorize ->
                Authorize
                        .requestMatchers("/mypage").hasRole("USER")
                        .requestMatchers("/messages").hasRole("MANAGER")
                        .requestMatchers("/config").hasRole("ADMIN")
                        .requestMatchers("/css/**").permitAll()
                        .requestMatchers("/js/**").permitAll()
                        .requestMatchers("/img/**").permitAll()
                        .requestMatchers("/favcon.ico").permitAll()
                        .requestMatchers("/webjars").permitAll()
                        .requestMatchers("/").permitAll()
                        .anyRequest().authenticated()
        );

전체 부분



@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig{



    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password(new BCryptPasswordEncoder().encode("1111")).roles("USER");
        auth.inMemoryAuthentication().withUser("manager").password(new BCryptPasswordEncoder().encode("1111")).roles("MANAGER","USER");
        auth.inMemoryAuthentication().withUser("admin").password(new BCryptPasswordEncoder().encode("1111")).roles("ADMIN","MANAGER","USER");
    }


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

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws  Exception {



        http
                .authorizeHttpRequests(Authorize ->
                        Authorize
                                .requestMatchers("/mypage").hasRole("USER")
                                .requestMatchers("/messages").hasRole("MANAGER")
                                .requestMatchers("/config").hasRole("ADMIN")
                                .requestMatchers("/css/**").permitAll()
                                .requestMatchers("/js/**").permitAll()
                                .requestMatchers("/img/**").permitAll()
                                .requestMatchers("/favcon.ico").permitAll()
                                .requestMatchers("/webjars").permitAll()
                                .requestMatchers("/").permitAll()
                                .anyRequest().authenticated()
                );

        http.formLogin(
                formLogin ->
                        formLogin
                                .successHandler(new AuthenticationSuccessHandler() {
                                    @Override
                                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                                        RequestCache requestCache = new HttpSessionRequestCache();      // 이걸 이용해 세션에 원래 가고자 하는 경로 저장되어 있음
                                        SavedRequest savedRequest = requestCache.getRequest(request, response);     //여기에 저장되어있음
                                        String redirectUrl = savedRequest.getRedirectUrl();
                                        log.info("redirectUrl : " + redirectUrl);
                                        response.sendRedirect(redirectUrl);
                                    }
                                })
                                .permitAll()
        );


        http

                .csrf(csrf ->
                        csrf.
                                csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                );

        return http.build();
    }
}

 

답변 1

답변을 작성해보세요.

1

작성하신 코드로 설정하시면 될 것 같습니다

참고로 정적파일 무시하는 방법은 다음과 같습니다

@Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }