우선 내 컨트롤러 다이어그램을 먼저 보여주자면!
Controller Diagram
- 모든 컨트롤러는 REST API로 호출하는 방식이며 Spring Security 프레임워크가 적용되어있다.
- 모든 API호출 경로는 Security에서 인증 및 인가를 받아야 정상적인 응답을 받을 수 있다.
- Security는 Filter를 통해 코드가 구현되어 있다.
위 컨트롤러의 경로로 요청을 보낼 경우 나타나는 Security의 기본 창
- 아이디와 비밀번호를 자격 인증을 요구하고 있다.
위와 같이 이루어지는 Security 6에서 제공하는 기본 샘플을 먼저 살펴보자.
- 이 중 1번의 과정이 아래의 코드에 구현되어 있다.
@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
'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 |