스프링 시큐리티 세팅

Legday_Dev·2023년 9월 4일
0

Spring

목록 보기
3/14
post-thumbnail

Spring Security 는 로그인하는 사용자를 검증할 수 있고, 그 외에 많은 기능들이 있다.

라이브러리 설정

  • pom.xml 설정파일에 아래와 같이 추가해준다.
<!-- 시큐리티 태그 라이브러리 -->
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
</dependency>
  • 그리고 따로 시큐리티 설정 클래스를 만든 후 아래와 같이 추가해준다.
  • 간단히 설명하자면 encode() 메서드는 비밀번호를 암호화하기 위한 메서드이고
  • crsf().disdable() 메서드는 CSRF 토큰 검사를 비활성화하는 로직이다.
  • 그리고 기본 url인 localhost:8080/ 으로 사용자가 진입하면 시큐리티가 가로채서 /localhost:8080/auth/singin 페이지로 이동시킨다.
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;

@Configuration // IoC
public class SecurityConfig {

    @Bean
    BCryptPasswordEncoder encode(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    SecurityFilterChain configure(HttpSecurity http) throws Exception{
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/","/user/**","/image/**","/subscribe/**", "/comment/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/auth/signin") //get
                .defaultSuccessUrl("/");
        return http.build();
    }

}
profile
백엔드개발자

0개의 댓글