본문 바로가기
Spring/Spring Security

[Spring Security] SecurityConfig

by seoyamin 2023. 1. 31.

[참고]  https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0/dashboard

 

[무료] 스프링부트 시큐리티 & JWT 강의 - 인프런 | 강의

스프링부트 시큐리티에 대한 개념이 잡힙니다., - 강의 소개 | 인프런...

www.inflearn.com

 

 

1. Security Config 

개발자가 직접 설정한 Config 파일로, Filter 역할을 한다.

 

 

2. SecurityConfig.java 뜯어보기

package com.cos.security1.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity  // Spring Security Filter가 Spring Filter Chain에 등록됨
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll()
                
                .and()
                .formLogin()
                .loginPage("/loginForm")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/");
    }

}

 

2-1. csrf

http.csrf().disable();

 

2-2. authorizeRequests

스프링의 페이지마다 접근 가능한 권한을 설정할 수 있다.

접근 권한이 없는 유저가 해당 페이지에 접속할 경우  403 Error 를 발생시킨다.

http.authorizeRequests()
        .antMatchers("/user/**").authenticated()
        .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .anyRequest().permitAll()
        
        .and()
        .formLogin()
        .loginPage("/loginForm")
        .loginProcessingUrl("/login")
        .defaultSuccessUrl("/");

 

  • authenticated()  :  로그인한 일반 유저
  • access("hasRole('ROLE_ADMIN')") : 관리자 등 특별한 ROLE을 가진 유저
  • permitAll() : 누구나 접근 가능
  • formLogin() : 접근 권한 없는 유저가 접근한 경우 처리
  • loginPage("/loginForm") : 접근 권한 없는 유저가 접근한 경우 해당 페이지로 보내버림
  • loginProcessingUrl("/login") : "/login" 주소가 호출되면 Spring Security가 낚아채서 대신 로그인 진행해줌
    • 따라서 login 관련 controller 만들 필요 없다!
  • defaultSuccessUrl("/") : 로그인 성공 시 해당 페이지로 이동