본문 바로가기
Spring/Spring Security

스프링 시큐리티 설치부터 적용까지

by java나유 2022. 11. 2.

 build.gradle 에 스프링 시큐리티를 설치한다.


  
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
}

✔ 참고로 스프링 시큐리티와 Thymeleaf 라이브러리를 사용하도록 설치 한 코드이다.

로컬 서버를 재시작 해준다.

 

그리고 화면을 키면 어떠한 경로에도 이 화면이 뜰 것이다.

이는, 기본적으로 인증되지 않은 사용자는 서비스를 사용할 수 없게 되어있어서이다. 

기본 아이디는 user이고 password는 console에 찍히지만.. 나는 게시판 화면을 만들것이라서 이런 화면이 뜨면 곤란하다. 로그인 없이 게시물을 조회할 수 있기 때문이다.

 

그래서 SecurityConfig 파일을 만들었다.


  
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
;
return http.build();
}
}

@Configuration : 스프링 환결설정 파일이라는 뜻 / 스프링 시큐리티의 설정을 위해 사용

@EnableWebSecurity : 모든 요청URL이 스프링 시큐리티의 제어를 받도록 만드는 설정

 

스프링 시큐리티 세부 설정은 SecutiryFilterChain @Bean을 생성한다.


  
http.authorizeRequests().antMatchers("/**").permitAll()

인증되지 않은 모든 요청을 허락한다는 코드이고 위 로그인 화면이 뜨는 것을 막는다.

++

스프링 시큐리티를 설치하면 CSRF 토큰이 자동으로 생성된다. 

728x90

댓글