반응형

전자정부프레임워크에서 Spring Security를 사용하여 인증(Authentication)과 권한(Authorization)을 구현하는 방법을 학습합니다. 이를 통해 웹 애플리케이션의 보안을 강화할 수 있습니다.


1. Spring Security 개요

Spring Security란?

  • Spring 기반 애플리케이션의 인증 및 권한 관리를 위한 강력한 보안 프레임워크입니다.
  • 주요 기능:
    • 사용자 인증 처리
    • 권한 기반 접근 제어
    • 세션 관리 및 CSRF 방어
    • OAuth2와 같은 인증 프로토콜 지원

2. Spring Security 설정

2-1. 의존성 추가

pom.xml에 Spring Security 의존성을 추가합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

3. 사용자 인증 구현

3-1. SecurityConfig 클래스 작성

Spring Security 설정을 위해 @Configuration과 @EnableWebSecurity를 사용합니다.

import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    // 비밀번호 암호화 방식
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 인메모리 사용자 인증 설정
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(passwordEncoder().encode("admin123"))
                .roles("ADMIN")
                .and()
                .withUser("user")
                .password(passwordEncoder().encode("user123"))
                .roles("USER");
    }

    // HTTP 보안 설정
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")  // 관리자 페이지 접근 제한
                .antMatchers("/user/**").hasRole("USER")    // 사용자 페이지 접근 제한
                .antMatchers("/").permitAll()               // 누구나 접근 가능
                .and()
                .formLogin()  // 로그인 폼 설정
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()     // 로그아웃 설정
                .permitAll();
        return http.build();
    }
}

3-2. 로그인 페이지 작성

login.jsp

<!DOCTYPE html>
<html>
<head>
    <title>로그인</title>
</head>
<body>
    <h1>로그인 페이지</h1>
    <form method="post" action="/login">
        <label for="username">사용자명:</label>
        <input type="text" id="username" name="username" required>
        <br>
        <label for="password">비밀번호:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="submit">로그인</button>
    </form>
</body>
</html>

4. 권한 기반 접근 제어

4-1. 권한에 따른 페이지 설계

  • 관리자 전용 페이지:
    admin.jsp
  • <h1>관리자 페이지</h1> <p>관리자만 접근할 수 있습니다.</p>
  • 사용자 전용 페이지:
    user.jsp
  • <h1>사용자 페이지</h1> <p>일반 사용자만 접근할 수 있습니다.</p>
  • 모든 사용자 접근 가능 페이지:
    index.jsp
  • <h1>메인 페이지</h1> <p>모든 사용자가 볼 수 있는 페이지입니다.</p>

4-2. 테스트

  1. 브라우저에서 /login에 접속하여 로그인합니다.
  2. 각 사용자 계정에 따라 접근 가능한 페이지를 테스트합니다.

5. 세션 관리와 로그아웃

5-1. 세션 관리

  • Spring Security는 기본적으로 세션을 사용하여 인증 상태를 관리합니다.
  • 세션 타임아웃 설정은 application.properties에서 설정할 수 있습니다.
    server.servlet.session.timeout=30m
    

5-2. 로그아웃 처리

  • 로그아웃 시 인증 정보를 제거하고 메인 페이지로 리다이렉트합니다.

6. 마무리

오늘 학습한 Spring Security의 기본 설정과 인증 및 권한 관리 구현은 웹 애플리케이션 보안의 핵심입니다. 다음에서는 JWT(JSON Web Token)를 활용한 토큰 기반 인증에 대해 학습합니다.

반응형

+ Recent posts