[Spring] Spring Security Framework

Minhyeok·2024년 6월 7일
post-thumbnail

✨ 'Spring Security' 프레임워크는 Spring 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해 줌으로써 개발의 수고를 덜어 줍니다. 마치 'Spring' 프레임워크가 웹 서버구현에 편의를 제공해 주는 것과 같습니다.


주요 기능

  1. 인증(Authentication) : 사용자가 누구인지 확인하는 과정입니다. 사용자 인증 정보를 확인하고 유효한 사용자인지 검증합니다.

  2. 권한부여(Authorization) : 인증된 사용자가 애플리케이션 내에서 어떤 권한을 가지는지 결정합니다. 사용자 역할(Role)이나 권한(Permission)에 따라 접근을 제어합니다.

  3. 보안설정(Security Configuration) : 보안 설정은 'WebSecurityConfigurerAdapter' 를 상속받아 설정할 수 있다. 이를 통해 특정 URL 패턴에 대한 접근 제어, 세션 관리, 사용자 정의 로그인 페이지 등을 설정할 수 있다.

  4. CSRF 보호 : CSRF(Cross-Site Request Forgery) 공격을 방지하기 위한 기능을 제공합니다. Spring Security는 기본적으로 CSRF 보호를 활성화합니다.

  5. OAuth2 및 OpenID Connect 지원 : 소셜 로그인이나 SSO(Single Sign-On)와 같은 기능을 손쉽게 구현할 수 있다.


간단한 설정 예제

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}admin").roles("ADMIN");
    }
}

위의 예제는 다음과 같이 설정을 할 수 있다.

  • '/'와 '/home' 경로는 모든 사용자가 접근 가능하도록 설정

  • 기타 모든 요청은 인증된 사용자만 접근 가능

  • 로그인 페이지를 '/login' 경로로 설정

  • 인메모리(In-Memory) 사용자 인증 설정으로 두 명의 사용자 정의


느낀점

Spring Security를 사용하면 보안 관련 설정을 간단하고 명확하게 구성할 수 있다. 다양한 보안요구 사항에 대해 유연하게 대응할 수 있으며, OAuth2와 같은 외부 인증 시스템과의 통합도 용이하다. 초기 설정은 다소 복잡할 수 있지만, Spring Security와 강력한 기능을 활용하면 애플리케이션의 보안을 효과적으로 관리하는데 도움이 될것으로 기대한다.

profile
민혁스

0개의 댓글