[Java - Spring Security6] Config파일 해석 및 직접 FilterChain만들기

2024. 3. 2. 00:15·Spring/Security6
728x90
반응형
SMALL

우선 내 컨트롤러 다이어그램을 먼저 보여주자면!

Controller Diagram

  • 모든 컨트롤러는 REST API로 호출하는 방식이며 Spring Security 프레임워크가 적용되어있다.
  • 모든 API호출 경로는 Security에서 인증 및 인가를 받아야 정상적인 응답을 받을 수 있다.
  • Security는 Filter를 통해 코드가 구현되어 있다.

 

 

위 컨트롤러의 경로로 요청을 보낼 경우 나타나는 Security의 기본 창

  • 아이디와 비밀번호를 자격 인증을 요구하고 있다.

 

위와 같이 이루어지는 Security 6에서 제공하는 기본 샘플을 먼저 살펴보자.

  • 이 중 1번의 과정이 아래의 코드에 구현되어 있다.

https://www.udemy.com/course/spring-security-6-jwt-oauth2-korean/

@Configuration(proxyBeanMethods = false)
	@ConditionalOnDefaultWebSecurity
	static class SecurityFilterChainConfiguration {

		@Bean
		@Order(SecurityProperties.BASIC_AUTH_ORDER)
		SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
			http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
			http.formLogin(withDefaults());
			http.httpBasic(withDefaults());
			return http.build();
		}

	}
  • 위 코드 이전에 해당 SpringBootWebSecurityConfiguration 클래스의 주석을 보면 이와 같은 설명이 있다.

The default configuration for web security. It relies on Spring Security's content-negotiation strategy to determine what sort of authentication to use. If the user specifies their own SecurityFilterChain bean, this will back-off completely and the users should specify all the bits that they want to configure as part of the custom security configuration.

  • 내용을 해석하자면 해당 시큐리티 내용은 content-negotiation strategy 전략을 사용한다. 만약 유저가 스스로 SecurityFilterChain bean을 명시한다면 직접 커스텀해서 모든 부분을 명시해야 한다고 적혀있다. 다시 말해서, FilterChain 을 Bean 어노테이션으로 명시하고 작성한다면 이전에 있던 일방적인 제어는 사라지고 모든 부분을 개발자가 직접 명시해서 들어오는 요청을 관리해야 한다는 뜻이다.
  • 이전에는 일반 java형식의 설정이 사용되었지만 Spring Security6버전에서는 람다DSL이 적용되어 있다. 

 

 

 

기본으로 제공하는 위 코드를 내가 원하는 경로에서 요청받을 수 있게 직접 커스텀해보자.

SecurityFilterChain을 직접 커스텀해서 만들기

  • 맞춤형 요구사항을 정의하기 위해 requestmatchers 메서드를 호출해야한다. 이 메서드는 api경로를 무한으로 받아들인다.
  • 비보호 URI는 permitAll()을 적용하고, 보호된 URI는 authenticated()를 적용한다.
  • 해당 URI를 거부하고 싶다면 denyAll()이 있다. 하지만 이 방법은 바람직하지 않다.
@Configuration
public class ProjectSecurityConfig {
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { //거부패턴 : /myAccount/** 을 통해 아래 모든 경로도 지정 가능
        http.authorizeHttpRequests((requests) ->
                requests.requestMatchers("/myAccount/**","myBalance","/myLoans","myCards")
                        .authenticated()
                        .requestMatchers("/notices", "contact")
                        .permitAll()
        );
        http.formLogin(withDefaults());
        http.httpBasic(withDefaults());
        return http.build();
    }
}

 

 

 

정리

  • 커스텀 보안 요구 사항을 정의하기 위해서 웹 어플리케이션 내에서 생성해야 하는 빈은 SecurityFilterChain이다.
  • SecurityFilterChain은 인자로 HttpSecurity를 받는다.
  • 커스텀하지 않은 SecurityFilterChain은 anyRequest().authenticated();으로 설정되어 있으며 모든 요청 경로가 보안URI로 인증을 요구한다.
  • 직접 경로를 지정할떄에는 requestMatchers메서드를 사용하여 경로패턴을 지정한 후에 permitAll(), denyAll, authenticated등의 메서드를 사용해서 인증후에 인가를 허용할지 거부할지 인가를 사용하지 않을지 정할 수 있다.
  • Bean어노테이션을 사용했기 떄문에 해당 메서드의 결과값은 객체로 반환이 된다.

 

 

다음 포스팅에는 해당 유저의 비밀번호를 암호화하는 방식인 PasswordEncoder에 대해 알아보겠다!

 

https://sunro1994.tistory.com/185

 

[Java - Spring Security6] PasswordEncoder와 BCryptPasswordEncoder, 그 이외의 암호화 클래스들

목차 1. 암호화 표준 2. 비밀번호 검증 순간의 코드 3. 해싱과 PasswordEncoder로 비밀번호가 인증되는 과정 4. PasswordEncoder의 메서드들 5. PasswordEncoder의 다양한 Encoder들 6. BCryptPasswordEncoder적용하기 1. 암

sunro1994.tistory.com

 

728x90
반응형
SMALL

'Spring > Security6' 카테고리의 다른 글

[Java - Spring Security6] Authentication(인증)과 관련된 Provider와 manager  (0) 2024.03.05
[Java - Spring Security6] PasswordEncoder와 BCryptPasswordEncoder, 그 이외의 암호화 클래스들  (0) 2024.03.04
[Java - Spring Security6] Spring Security를 사용하는 이유 및 아키텍처  (0) 2024.02.25
자바[Java] - Security 소개  (1) 2023.12.11
'Spring/Security6' 카테고리의 다른 글
  • [Java - Spring Security6] Authentication(인증)과 관련된 Provider와 manager
  • [Java - Spring Security6] PasswordEncoder와 BCryptPasswordEncoder, 그 이외의 암호화 클래스들
  • [Java - Spring Security6] Spring Security를 사용하는 이유 및 아키텍처
  • 자바[Java] - Security 소개
공부하고 기억하는 공간
공부하고 기억하는 공간
IT 비전공자로 시작하여 훌륭한 개발자가 되기 위해 공부하고 있는 공간입니다. 틀린 내용이나 부족한 부분이 있으면 댓글로 알려주세요 바로 수정하겠습니다.
    250x250
  • 공부하고 기억하는 공간
    IT - railroad
    공부하고 기억하는 공간
  • 전체
    오늘
    어제
    • 분류 전체보기 (315)
      • 면접 준비 (36)
        • OS (6)
        • Spring Security (0)
        • Java (2)
        • DB (9)
        • Network (3)
      • ElasticSearch (2)
      • Kafka (4)
      • Spring (22)
        • Spring Cloud (7)
        • Security6 (5)
        • JPA (12)
        • 프로젝트 리팩토링 회고록 (4)
        • Logging (8)
        • Batch (2)
      • Redis (17)
        • Redis 개념 (8)
        • Redis 채팅 (5)
        • Redis 읽기쓰기 전략 (1)
      • AWS (11)
      • 리눅스 (29)
        • 리눅스 마스터 2급 (5)
        • 네트워크(기초) (7)
        • 리눅스의 이해 (6)
        • 리눅스의 설치 (2)
        • 리눅스 운영 및 관리 (6)
      • JAVA-기초 (16)
        • JAVA기본 (11)
        • Design Pattern (5)
      • JSP (27)
        • JSP 기본 개념 (10)
        • JSP (1)
      • SQL (1)
      • TIL (36)
      • 문제 풀이 (2)
        • Programmers (9)
        • 백준 문제풀이 (28)
      • JavaScript (10)
      • HTML (17)
      • Ngrinder (1)
        • Ngrinder 문서 정리 (1)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      JS
      자바스크립트
      jsp기초
      자바 면접
      자바 면접질문
      Spring Data Redis
      springsecurity
      spring redis
      redis 채팅
      JavaScript
      리눅스마스터2급정리
      자바기초
      자바 알고리즘
      JSP
      레디스
      Springframework
      HTML
      자바 반복문
      redis
      CSS
      프로그래머스
      Til
      리눅스
      Spring
      java
      스프링프레임워크
      리눅스마스터2급
      백준
      자바
      jsp request
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.3
    공부하고 기억하는 공간
    [Java - Spring Security6] Config파일 해석 및 직접 FilterChain만들기
    상단으로

    티스토리툴바