spring security가 필터 역할을 함. 

 

 

 

1. dependency 추가

implementation 'org.springframework.boot:spring-boot-starter-security'

 

보안 스타터를 프로젝트는 빌드 파일에 추가만 했을 때는 다음의 보안 구성이 제공된다.

  • 모든 HTTP 요청 경로는 인증(Authentication) 되어야 한다.
  • 어떤 특정 역할이나 권한이 없다.
  • 로그인 페이지가 따로 없다.
  • 스프링 시큐리티의 HTTP 기본 인증 화면을 사용해서 인증된다.

스프링 시큐리티의 HTTP 기본 인증

  • 사용자는 하나만 있으며, 이름은 user다. 비밀번호는 암호화해 준다.

2. 코드

@Configuration
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().frameOptions().disable();

        http.authorizeRequests()
                .anyRequest().authenticated() //어떤 요청이 오던지 로그인 과정이 없었으면 로그인을 하도록 하겠다.
                .and()
                .formLogin()  // 로그인 페이지 허용
                .defaultSuccessUrl("/") //로그인이 완료되었을 때 이동할 위치
                .permitAll()
                .and()
                .logout() // 로그아웃 페이지 허용
                .permitAll();
    }
}

WebSecurityConfig 클래스의 역할 

: 사용자의 HTTP 요청 경로에 대해 접근 제한과 같은 보안 관련 처리를 우리가 원하는 대로 할 수 있게 해 준다.

 

 

** WebSecurityConfigurerAdapter 클래스를 상속받아(extends) configure 메소드를 @override하여 사용하였었으나 WebSecurityConfigurerAdapte 클래스가 depreciated 됨. 이에 따른 코드 변경은 공부가 필요. 

->

SecurityFilterChain filterChain(HttpSecurity http) throws Exception

 

스프링 공식 문서 : https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

 

 

 

3. 라이브러리 추가 후 사이트 접속 시 해당 화면으로 연결

username : user

password : 콘솔 창 참조

 

 

======================================  Develop  =============================================

 

  1. 스프링 시큐리티의 HTTP 기본 인증 화면 대신 우리의 로그인 페이지로 인증하도록 해야 한다.
  2. 다수의 사용자를 제공하며, 새로운 고객이 회원 가입할 수 있어야 한다.
  3. 서로 다른 HTTP 요청 경로마다 서로 다른 보안 규칙을 적용한다. 예를 들어. 홈페이지와 사용자 등록 페이지는 인증이 필요하지 않다.

 

  • 스프링 시큐리티의 HTTP 기본 인증 화면 대신 우리의 로그인 페이지로 인증하도록 해야 한다.
  • image, css 폴더 인증 없이 접근 허용
  • 회원가입 페이지 접근을 위해 /user 경로 허용
  • h2 페이지 접근을 위해 경로 허용
http.authorizeRequests()
                .antMatchers("/images/**").permitAll()  // image 폴더를 login 없이 허용
                .antMatchers("/css/**").permitAll()  // css 폴더를 login 없이 허용
                .antMatchers("/user/**").permitAll() // 회원 관리 URL 전부를 login 없이 허용
                .antMatchers("/h2-console/**").permitAll()// h2-console URL 을 login 없이 허용
                .anyRequest().authenticated() //어떤 요청이 오던지 로그인 과정이 없었으면 로그인을 하도록 하겠다.
                .and()
                .formLogin()
                .loginPage("/user/login")  // default 로그인 페이지가 호출되었을 때 호출 될 경로
                .failureUrl("/user/login/error") // 로그인이 실패 했을 경우 경로
                .defaultSuccessUrl("/") //로그인이 완료되었을 때 이동할 위치
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/user/logout")
                .permitAll();

+ Recent posts