WEB/Spring

웹 애플리케이션의 보안의 기본, Spring Security 알아보기

MoonSta 2023. 7. 26. 09:02

 Spring Security는 Spring 기반 웹 애플리케이션의 보안성을 올리기 위해 활용되는 프레임워크로서, 사용자 인증, 인가, 보안 설정 등 다양한 기능을 제공합니다. 이 글에서는 Spring Security의 기본 개념과 주요 기능을 소개하고, 웹 애플리케이션 보안 강화를 위한 최적의 방법 또한 알아보도록 하겠습니다. 

 

 

Spring Security란?

 Spring Security는 웹 애플리케이션의 보안성을 높이기 위해 사용되며, 간편하게 개발 및 관리할 수 있습니다. 또한 이 프레임워크를 사용함으로써 개발자들이 보안에 더욱 집중할 수 있게 되며, 더 나아가 취약점을 최소화하는 안전한 웹 애플리케이션의 구축을 할 수 있도록 도와줄 수 있습니다. 이제 Spring Security에 주요 특징과 기능에 대해 자세하게 알아보도록 하겠습니다.

 

 


 

Spring Security의 주요 특징과 기능

 

  1. Spring Security의 주요한 기능이자 특징으로 인증과 인가(Authentication and Authorization) 처리에 대한 다양한 기술을 지원합니다. 
  2. 사용자의 비밀번호를 안전하게 저장할 수 있도록 강력한 암호화 알고리즘을 사용한 인코딩 기술을 지원합니다.
  3. Spring Security는 로그인 폼을 통해 사용자 인증을 처리하는 폼 기반 인증을 지원하고 있습니다.
  4. 사용자의 로그인 정보를 기억하여 재로그인 없이 애플리케이션에 접속할 수 있는 기능을 제공합니다.
  5. Cross-Site Request Forgey 공격에 대비하여 요청에 대한 위조 방지 기능을 제공합니다.
  6. Spring Security는 세션 관리에 대한 다양한 기능을 지원하며, 세션의 유효성을 지속 및 관리할 수 있습니다.

 

Spring Security 설정 방법

 

Spring Boot에서의 Spring Security 설정은 의존성을 추가하여 간단하게 세팅할 수 있습니다. 

pom.xml 파일에 아래 코드를 추가합니다.

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Security Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

 

 

이제 의존성을 추가하였다면, Java Config에 클래스를 생성해 주도록 하겠습니다. 일반적으로 클래스명은 'WebSecurityConfig'라는 이름으로 생성합니다.

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

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

}

 


 

인증(Authentication) 설정 

 인증(Authentication)은 사용자의 신원을 증명하고 인증되었음을 확인하는 과정입니다. Spring Security에서 사용하기 위해서는 추가적으로 configure(AuthenticationManagerBuilder auth) 메서드를 오버라이딩하여 인증에 대한 정보를 구성합니다.

 

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

 

 예시로 사용한 위의 코드는 isMemoryAuthentication() 메서드를 사용하여 인메모리 방식으로 사용자 정보를 구성하였습니다. 

 


 

인가( Authorization) 설정

인가(Authorization)는 기존에 인증된 사용자에 대한 접근 권한을 관리하는 과정입니다. Spring Security에서 인가(Authorization)를 설정하기 위해서는 configure(HttpSecurity http) 메서드를 오버라이딩 하여 URL 패턴에 대한 접근 권한을 구성합니다.

 

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login").permitAll()
                .and()
            .logout().permitAll();
    }
}

 

 위의 예시 코드에서는 authorizeRequests() 메서드를 사용하여 특정 URL 패턴에 대한 접근 권한을 설정하였습니다. 또한 anMatchers() 메서드를 사용하여 특정 패턴에 대한 권한을 지정하고, hasRole() 메서드를 사용하여 특정한 역할을 가진 사용자에게만 접근을 허용해 주었습니다. 마지막으로 anyRequest(). authenticated()를 사용하여 그 외의 모든 요청에 대한 허용 권한은 인증된 사용자에게만 주도록 설정하였습니다.

 


 

맺음말

 위에 작성한 예시 코드는 Spring Security에서 제공하는 간단한 메서드를 활용하여 인증과 인가에 대한 간단한 처리 과정을 보여주었습니다. 하지만 실제 프로젝트에서는 더 복잡하고 보안성이 필요한 과정을 필요로 할 수 있습니다.