스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 스프링 시큐리티 설정법

예슬·2024년 1월 13일
0
post-thumbnail

'스프링 부트와 AWS로 혼자 구현하는 웹 서비스'라는 책을 실습하며 현재와 달라진 최신 버전으로 인해 작동되지 않아 생긴 오류를 고칩니다.

24.01.13. 기준 작성되었습니다.
버전이 다를 경우 지원하지 않는 메서드들이 있습니다. 버전을 확인 해 주세요.

  • Spring Boot: 6.0.11
  • Java: 17
  • Gradle: 8.4

소셜 로그인 등 클라이언트 입장에서 소셜 기능 구현 시 필요한 의존성

implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

config/auth/SecurityConfig.java

시큐리티 설정을 하는 데 더이상 쓰지 않는 메서드들이 많아서 구글링하기 시작 했다.

  1. 책에서는 WebSecurityConfigurerAdapter를 상속받아 설정을 오버라이딩하여 사용하지만 현재는 deprecated 되어 Bean으로 등록하여 사용하는 방식으로 변경
  2. authorizeRequest() deprecated -> authorizeHttpRequests()로 변경
  3. antMatchers() deprecated -> requestMatchers()로 변경
  4. 작성 방식 람다로 변경

그리고... 아래 빨간 줄은 전부 다음 버전에서 사라질 예정이라고 떠서 실행은 되니까 대수롭지 않게 여기고 넘겼는데 해당 설정이 안 먹는 건지 localhost:8080 으로 접속하면 메인 화면이 뜨지 않고 계속 구글 로그인 화면으로 인증을 요구했다.

구글링 하다보니 @Configuration을 사용해야 하길래 클래스에 추가를 해줬더니 에러 메시지가 떴다.

그러다 같은 오류를 해결하신 분이 계셔서 그 분을 참고해서 해결

작성된 코드 전문

package com.book.springboot.config.auth;

import com.book.springboot.domain.user.Role;
import lombok.RequiredArgsConstructor;
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.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
public class SecurityConfig {

    private final CustomOAuth2UserService customOAuth2UserService;

    @Bean
    protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)

                .headers((headers) -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))

                .authorizeHttpRequests(auth -> auth 
                        .requestMatchers(
                                new AntPathRequestMatcher("/"),
                                new AntPathRequestMatcher("/css/**"),
                                new AntPathRequestMatcher("/images/**"),
                                new AntPathRequestMatcher("/js/**"),
                                new AntPathRequestMatcher("/h2-console/**"),
                                new AntPathRequestMatcher("/profile")
                        ).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/api/v1/**")).hasRole(Role.USER.name())
                        .anyRequest().authenticated())

                .logout((logout) -> logout
                        .logoutSuccessUrl("/")) 
                .oauth2Login((oauth2) -> oauth2 
                        .userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint 
                                .userService(customOAuth2UserService))
                        .defaultSuccessUrl("/", true));

        return http.build();
    }
}


예전에 겪어본 프로젝트에서도 로그인 부분을 내가 맡은 게 아니라서
스프링 시큐리티를 접해 볼 수 없었는데... 해당 책 읽기를 잘한 것 같다.

스터디원 분들이 스프링 시큐리티를 더 공부해보고 싶다는 얘기를 하셨었는데 정말 많이 공부해야 할 것 같다.

참고한 블로그 분의 에러 해결 과정 중 처음에 고친 방법은 공식문서 참고하는 것이라고 하셨는데 나는 아직 이 부분이 많이 부족한 것 같아 많이 배우고 공부해야겠다.😊👍

그외 참고

profile
블로그 이사 했습니다! 🏠 ⤵

0개의 댓글