Post

[Springboot] Spring Boot 3.x 버전 SecurityConfig 설정하기


아이티윌의 국비지원 [스프링부트 SNS 포토그램 프로젝트] 강의를 수강하며 정리한 내용입니다.


오늘의 실습

  • SecurityConfig 설정하기


🔎그 전에 알아야할 것


SecurityConfig를 설정해주는 이유?

사용자가 시스템에 로그인할 때 인증되어야 하고, 인증된 사용자에게는 특정한 권한이나 역할을 부여하여 특정 리소스에 접근할 수 있도록 해야 한다. SecurityConfig는 이러한 인증 및 인가 규칙을 정의하여 시스템의 보안을 관리하는데 유용하다.


Redirect란?

설명은 여기서 참고


실습


[Spring Boot 3.x 버전 SecurityConfig 코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.cos.photogramstart.config;

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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.cos.photogramstart.config.oauth.OAuth2DetailsService;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Configuration //IoC
public class SecurityConfig {
	
	private final OAuth2DetailsService oAuth2DetailsService;
	
	@Bean // 회원가입 시 비밀번호 암호화를 위해 Bean으로 등록해줌. 지금은 몰라도 그냥 넘어가기
	BCryptPasswordEncoder encoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Bean
	SecurityFilterChain configure(HttpSecurity http) throws Exception {
	    http
	        .csrf(csrf -> csrf.disable())
	        .authorizeRequests(authorizeRequests ->
	            authorizeRequests
	                .antMatchers("/", "/user/**", "/image/**", "/subscripbe/**", "/comment/**").authenticated()
	                .anyRequest().permitAll()
	        )
	        .formLogin(formLogin ->
	            formLogin
	                .loginPage("/auth/signin")
	                .defaultSuccessUrl("/")
	        );

	    return http.build();
	}
}

http.csrf(csrf -> csrf.disable())

CSRF(Cross-Site Request Forgery) 공격 방지 기능을 비활성화.( RESTful API를 사용할 때는 CSRF 토큰을 사용하지 않는 것이 일반적임)

.antMatchers("/", "/user/**", "/image/**", "/subscripbe/**", "/comment/**").authenticated()

인증 받을 주소들을 설정.

.formLogin(formLogin -> formLogin.loginPage("/auth/signin").defaultSuccessUrl("/")

인증이 필요한 페이지로 요청이 왔을 때, 리다이렉트 되는 로그인 페이지 경로를 “/auth/signin”으로 설정


이전 버전과의 차이점


[Spring Boot 2.x 버전 SecurityConfig 코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@EnableWebSecurity // 해당 파일로 시큐리티를 활성화
@Configuration // Ioc
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super 삭제 - 기존 시큐리티가 가지고 있는 기능이 다 비활성화
        http.authorizeRequests()
                                .antMatchers("/", "/user/**", "/image/**", "/subscribe/**", "/comment/**").authenticated()
                                .anyRequest().permitAll()
                                .and()
                                .formLogin("/auth/signin")
                                .loginPage("/auth/signin")
                                .defaultSuccessUrl("/");
    }
}

  • @EnableGlobalMethodSecurity(prePostEnabled = true)가 deprecated 됐다.

    3.x 에서는 @EnableMethodScurity를 사용해주면된다. 기본값이 true이기 때문에 굳이 지정해주지 않아도 된다.

  • WebSecurityConfigurerAdapter 인퍼테이스를 상속받지 않는다.

    SecurityFilterChain 인터페이스 함수를 하나 만들어서 Bean으로 등록해준 후 그 안에서 기존에 설정했던 코드를 구현한다. 이때 HttpSecurity를 주입받아 사용하면 된다.

  • 설정 코드를 구현하는 방식이 non-lamda-DSL에서 lamda-DSL로 변경되었다.


This post is licensed under CC BY 4.0 by the author.