inblog logo
|
{CODE-RYU};
    SPIRNG

    스프링 시큐리티 커스터마이징

    Feb 15, 2024
    스프링 시큐리티 커스터마이징
    Contents
    1. SecurityConfig 파일 생성2. 커스터마이징3. 컨트롤러 인증 로직 삭제4. 예외 페이지 설정
     
    notion image
     
    새로운 패키지를 생성한다.
     

    1. SecurityConfig 파일 생성

     
    _core/config/SecurityConfig
    @Configuration //컨퍼넌트 스캔. public class SecurityConfig { //보안을 위한 필터 @Bean SecurityFilterChain configure(HttpSecurity http) throws Exception { //커스터미이징을 위해 필요함 return http.build(); // 아무 것도 없는걸 등록함. 하나씩 막아야됨. } }
     
    notion image
     
    return http.build(); 를 사용하면 모든 필터 기능이 사라진다.
     
    notion image
     
    그리고 로그인이나 회원가입을 하려고 하면 실행되지 않는다.
     
     

    2. 커스터마이징

     
    @Configuration //컨퍼넌트 스캔. public class SecurityConfig { //보안을 위한 필터 @Bean // 현재는 모든 걸 무효화. SecurityFilterChain configure(HttpSecurity http) throws Exception { // 람다식으로 만들어짐 http.authorizeHttpRequests(a -> { // "/board/**" /board/ 뒤에 모든 주소는 인증이 필요함 //anyRequest().permitAll() 앞의 주소가 아닌 주소는 허용해줌 a.requestMatchers("/user/updateForm","/board/**").authenticated().anyRequest().permitAll(); // 인증이 되지 않으면 못들어가는 페이지 }); http.formLogin(f -> { //로그인 페이지로 리다이렉션 f.loginPage("/loginForm"); } ); return http.build(); // 아무 것도 없는걸 등록함. 하나씩 막아야됨. } }
     
     

    3. 컨트롤러 인증 로직 삭제

     
    notion image
    if(sessionUser == null){ return "redirect:/loginForm"; }
     
    스프링 시큐리티를 사용하면 각 컨트롤러 마다 있던 코드의 중복을 막을 수 있다.
    세션값은 권한 체크에서 필요하기 때문에 if 문만 삭제한다.
     
    notion image
     
    user/updateForm 페이지로 들어갔을 때 로그인하지 않았다면 로그인 페이지로 리다이렉션 된다.
     
    notion image
     
    하지만 /board/** 는 board 뒤의 모든 주소를 막기 때문에 인증이 필요하지 않은 페이지도 로그인 페이지로 넘어간다. 따라서 일부 페이지는 제외할 필요가 있다.
     
     

    4. 예외 페이지 설정

     
    ScurityConfig
    @Configuration //컨퍼넌트 스캔. public class SecurityConfig { @Bean public WebSecurityCustomizer ignore(){ // 예외 설정 return w -> w.ignoring().requestMatchers("/board/*","/static/**","/h2-console/**"); } //보안을 위한 필터 @Bean // 현재는 모든 걸 무효화. SecurityFilterChain configure(HttpSecurity http) throws Exception { // 람다식으로 만들어짐 http.authorizeHttpRequests(a -> { // "/board/**" /board/ 뒤에 모든 주소는 인증이 필요함 //anyRequest().permitAll() 앞의 주소가 아닌 주소는 허용해줌 a.requestMatchers("/user/updateForm","/board/**").authenticated().anyRequest().permitAll(); // 인증이 되지 않으면 못들어가는 페이지 }); http.formLogin(f -> { // 로그인 페이지로 리다이렉션 f.loginPage("/loginForm"); } ); return http.build(); // 아무 것도 없는걸 등록함. 하나씩 막아야됨. } }
     
    notion image
     
    예외 설정을 하면 로그인 필요하지 않은 페이지는 정상적으로 접근 가능하다.
    Share article

    {CODE-RYU};

    RSS·Powered by Inblog