๐Ÿ›ก๏ธ

Spring Security ์น˜ํŠธ์‹œํŠธ

Spring Boot 3.4+ / 4.x ๋ฐ Spring Security 6.4+ ์ตœ์‹  ์™„์ „ ๊ฐ€์ด๋“œ: Lambda DSL ๊ธฐ๋ฐ˜ SecurityFilterChain, JWT ๋ฌด์ƒํƒœ(Stateless) ์ธ์ฆ ํ•„ํ„ฐ ์ „์ฒด ๊ตฌํ˜„, UserDetailsService & DB ์—ฐ๋™, Method Security(@PreAuthorize), CORS/CSRF ์ •๋ฐ€ ์ œ์–ด, 401/403 ์ปค์Šคํ…€ JSON ์‘๋‹ต ๋ฐ 5.x โž” 6.x ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜ ์ฒดํฌ๋ฆฌ์ŠคํŠธ

--views
๋‹จ์ˆ˜:
#spring-security#spring-boot#spring#java#jwt#authentication#authorization#oauth2#backend#security์ตœ์ข… ์—…๋ฐ์ดํŠธ: 2026-10-10

1. ์‚ฌ์ „ ์š”๊ฑด & ํ”„๋กœ์ ํŠธ ๋นŒ๋“œ ๊ตฌ์„ฑ (Prerequisites & Setup)

๐Ÿ’ป ์‹œ์Šคํ…œ ์„ค์น˜ ๋ฐ ์‹คํ–‰ ์š”๊ตฌ์‚ฌ์–‘ (System Requirements)

ํ•ญ๋ชฉ์ตœ์†Œ ์‚ฌ์–‘ (Minimum)๊ถŒ์žฅ ์‚ฌ์–‘ (Recommended)์ฐธ๊ณ  ๋ฐ ๋น„๊ณ 
์šด์˜์ฒด์ œ (OS)Windows 10/11, macOS (Apple Silicon / Intel), Linux (Ubuntu, Debian, RHEL)Ubuntu 22.04 LTS+, macOS Sonoma, Windows 11 (WSL2)Java ๊ฐ€์ƒ ๋จธ์‹ (JVM) ์ง€์› 64-bit OS
CPU2 ์ฝ”์–ด ์ด์ƒ4 ์ฝ”์–ด ~ 8 ์ฝ”์–ด ์ด์ƒBCrypt ํ•ด์‹ฑ ์—ฐ์‚ฐ ๋ฐ ๋™์‹œ ์ธ์ฆ ์•”ํ˜ธํ™” ์ฒ˜๋ฆฌ ์„ฑ๋Šฅ
๋ฉ”๋ชจ๋ฆฌ (RAM)2 GB ์ด์ƒ (๊ฐœ๋ฐœ/ํ…Œ์ŠคํŠธ)4 GB ~ 8 GB ์ด์ƒSpring Boot ๋Ÿฐํƒ€์ž„ ๋ฐ JVM ํž™(Heap) ๋ฉ”๋ชจ๋ฆฌ
๋””์Šคํฌ (Storage)1 GB ์ด์ƒ์˜ ์—ฌ์œ  ๊ณต๊ฐ„10 GB ์ด์ƒ์˜ ๊ณ ์† NVMe SSD๋นŒ๋“œ ์•„ํ‹ฐํŒฉํŠธ, ์˜์กด์„ฑ JAR ์บ์‹œ ๋ฐ DB ์Šคํ† ๋ฆฌ์ง€
๋„คํŠธ์›Œํฌ / ๋Ÿฐํƒ€์ž„Java 17 / 21 LTS, Spring Boot 3.3+ / Spring Security 6.3+Java 21 / 25 LTS, Spring Boot 3.4+ / 4.xํฌํŠธ 8080 (๊ธฐ๋ณธ HTTP), ํฌํŠธ 443 (HTTPS ํ•„์ˆ˜)

๐Ÿ“ฆ ๋นŒ๋“œ ๋„๊ตฌ๋ณ„ ์˜์กด์„ฑ ์„ค์ • (Dependencies)

์ตœ์‹  Spring Boot 3.x ํ™˜๊ฒฝ์—์„œ๋Š” spring-boot-starter-security์™€ ํ•จ๊ป˜ REST API ํ† ํฐ ์ธ์ฆ์„ ์œ„ํ•œ JJWT ์ตœ์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ(0.12.x)๋ฅผ ํ•จ๊ป˜ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

โ‘  Gradle (build.gradle)

dependencies {
    // Spring Boot ํ•ต์‹ฌ ์›น & ๋ณด์•ˆ ์Šคํƒ€ํ„ฐ
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-validation'

    // JJWT 0.12.x ์ตœ์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ (JWT ํ† ํฐ ์ƒ์„ฑ ๋ฐ ํŒŒ์‹ฑ)
    implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
    runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.6'
    runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.6'

    // ํ…Œ์ŠคํŠธ ํ™˜๊ฒฝ
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

โ‘ก Maven (pom.xml)

<dependencies>
    <!-- Spring Boot Web & Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- JJWT 0.12.x -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-api</artifactId>
        <version>0.12.6</version>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-impl</artifactId>
        <version>0.12.6</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-jackson</artifactId>
        <version>0.12.6</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2. Spring Security ํ•ต์‹ฌ ๋ฉ˜ํƒˆ ๋ชจ๋ธ & ์•„ํ‚คํ…์ฒ˜ (Architecture)

Spring Security๋Š” ์„œ๋ธ”๋ฆฟ ์ปจํ…Œ์ด๋„ˆ(Tomcat)์˜ ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ ์ฒด์ธ(Servlet Filter Chain) ์•ž๋‹จ์— ์œ„์น˜ํ•˜์—ฌ, ๋ชจ๋“  HTTP ์š”์ฒญ์ด ์ปจํŠธ๋กค๋Ÿฌ์— ๋„๋‹ฌํ•˜๊ธฐ ์ „์— **์ธ์ฆ(Authentication: ๋ˆ„๊ตฌ์ธ๊ฐ€?)**๊ณผ **์ธ๊ฐ€(Authorization: ์ ‘๊ทผ ๊ถŒํ•œ์ด ์žˆ๋Š”๊ฐ€?)**๋ฅผ ์ผ๊ด„ ๊ฒ€์ฆํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ“ ํ•„ํ„ฐ ์ฒด์ธ ๋ฐ ์ธ์ฆ ์ฒ˜๋ฆฌ ํ๋ฆ„ (ASCII Diagram)

[ Client HTTP Request ] (ํด๋ผ์ด์–ธํŠธ ์š”์ฒญ)
          โ”‚
          โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                           Servlet Container (Tomcat)                        โ”‚
โ”‚                                                                             โ”‚
โ”‚  [ DelegatingFilterProxy ] (์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ์™€ ์Šคํ”„๋ง ๋นˆ์„ ์—ฐ๊ฒฐํ•˜๋Š” ์ค‘๊ณ„์ž)       โ”‚
โ”‚             โ”‚                                                               โ”‚
โ”‚             โ–ผ                                                               โ”‚
โ”‚  [ FilterChainProxy ] (์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ ํ•„ํ„ฐ ๋ชฉ๋ก์„ ์ด๊ด„ ๊ด€๋ฆฌ)                โ”‚
โ”‚             โ”‚                                                               โ”‚
โ”‚             โ–ผ                                                               โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚ SecurityFilterChain (์ˆœ์ฐจ์ ์œผ๋กœ ์‹คํ–‰๋˜๋Š” ๋ณด์•ˆ ํ•„ํ„ฐ ์ฒด์ธ ๋ชฉ๋ก)         โ”‚  โ”‚
โ”‚  โ”‚                                                                       โ”‚  โ”‚
โ”‚  โ”‚ 1. CorsFilter               : Cross-Origin ๋ฆฌ์†Œ์Šค ๊ณต์œ  ํ—ˆ์šฉ ์—ฌ๋ถ€ ํŒ๋ณ„  โ”‚  โ”‚
โ”‚  โ”‚ 2. CsrfFilter               : CSRF ํ† ํฐ ์ผ์น˜ ์—ฌ๋ถ€ ํ™•์ธ (REST API ์ œ์™ธ)โ”‚  โ”‚
โ”‚  โ”‚ 3. JwtAuthenticationFilter  : Bearer ํ† ํฐ ์ถ”์ถœ ๋ฐ SecurityContext ์ €์žฅ โ”‚  โ”‚
โ”‚  โ”‚ 4. UsernamePasswordAuth...  : ํผ ๋กœ๊ทธ์ธ(์•„์ด๋””/๋น„๋ฐ€๋ฒˆํ˜ธ) ๊ฒ€์ฆ ํ•„ํ„ฐ     โ”‚  โ”‚
โ”‚  โ”‚ 5. ExceptionTranslation...  : ์ธ์ฆ ์˜ˆ์™ธ(401) ๋ฐ ์ธ๊ฐ€ ์˜ˆ์™ธ(403) ๋ฒˆ์—ญ   โ”‚  โ”‚
โ”‚  โ”‚ 6. AuthorizationFilter      : ์ตœ์ข… URL ๊ฒฝ๋กœ๋ณ„ Role / Authority ๊ฒ€์‚ฌ   โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ”‚                                     โ”‚ ์ธ์ฆ ์„ฑ๊ณต                               โ”‚
โ”‚                                     โ–ผ                                       โ”‚
โ”‚                           [ DispatcherServlet ]                             โ”‚
โ”‚                                     โ”‚                                       โ”‚
โ”‚                                     โ–ผ                                       โ”‚
โ”‚                           [ @RestController ]                               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿงฉ ์ธ์ฆ(Authentication) ํ•ต์‹ฌ ๊ฐ์ฒด ๊ตฌ์กฐ

[ SecurityContextHolder ] โ”€โ”€โ–บ [ SecurityContext ] โ”€โ”€โ–บ [ Authentication ]
                                                            โ”œโ”€โ”€ Principal    (์‚ฌ์šฉ์ž ์‹๋ณ„ ๊ฐ์ฒด / UserDetails)
                                                            โ”œโ”€โ”€ Credentials  (์ž๊ฒฉ ์ฆ๋ช… / ๋น„๋ฐ€๋ฒˆํ˜ธ - ์ธ์ฆ ํ›„ ์‚ญ์ œ)
                                                            โ””โ”€โ”€ Authorities  (๊ถŒํ•œ ๋ชฉ๋ก / Collection<GrantedAuthority>)

[ AuthenticationManager ] โ”€โ”€โ–บ [ ProviderManager ] โ”€โ”€โ–บ [ DaoAuthenticationProvider ]
                                                            โ”œโ”€โ”€ UserDetailsService (DB์—์„œ ์œ ์ € ์กฐํšŒ)
                                                            โ””โ”€โ”€ PasswordEncoder    (๋น„๋ฐ€๋ฒˆํ˜ธ ํ•ด์‹œ ์ผ์น˜ ๊ฒ€์ฆ)

3. [์ดˆ๋ณด์ž 1๋‹จ๊ณ„] 3๋ถ„ ํ—ฌ๋กœ์›”๋“œ: ์ตœ์†Œ ๋™์ž‘ ์˜ˆ์ œ (Hello World)

Spring Security 6.x์˜ ์ตœ์‹  Lambda DSL ๋ฐฉ์‹์„ ์ ์šฉํ•˜์—ฌ, ์ธ๋ฉ”๋ชจ๋ฆฌ ์œ ์ € 2๋ช…(์ผ๋ฐ˜ ์œ ์ €, ๊ด€๋ฆฌ์ž)์„ ๋“ฑ๋กํ•˜๊ณ  URL ์ ‘๊ทผ ๊ถŒํ•œ์„ ์ œ์–ดํ•˜๋Š” ์ตœ์†Œ ๋™์ž‘ ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.

โ‘  ๋ณด์•ˆ ์„ค์ • ํด๋ž˜์Šค (SecurityConfig.java)

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // [1] SecurityFilterChain ๋นˆ ๋“ฑ๋ก (์ตœ์‹  Lambda DSL ํ‘œ์ค€)
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // URL ๊ฒฝ๋กœ๋ณ„ ์ธ๊ฐ€(Authorization) ๊ทœ์น™ ์„ค์ •
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()           // ๋ˆ„๊ตฌ๋‚˜ ์ ‘๊ทผ ๊ฐ€๋Šฅ
                .requestMatchers("/api/user/**").hasRole("USER")         // USER ๊ถŒํ•œ ํ•„์š”
                .requestMatchers("/api/admin/**").hasRole("ADMIN")       // ADMIN ๊ถŒํ•œ ํ•„์š”
                .anyRequest().authenticated()                            // ๊ทธ ์™ธ ๋ชจ๋“  ์š”์ฒญ์€ ๋กœ๊ทธ์ธ ํ•„์ˆ˜
            )
            // ๋ธŒ๋ผ์šฐ์ € ํผ ๋กœ๊ทธ์ธ ๋ฐ ๊ธฐ๋ณธ HTTP Basic ์ธ์ฆ ํ™œ์„ฑํ™”
            .formLogin(Customizer.withDefaults())
            .httpBasic(Customizer.withDefaults());

        return http.build();
    }

    // [2] ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” ๋นˆ (BCrypt ๋‹จ๋ฐฉํ–ฅ ํ•ด์‹œ)
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // [3] ์ธ๋ฉ”๋ชจ๋ฆฌ ํ…Œ์ŠคํŠธ ์œ ์ € ์ƒ์„ฑ (์‹ค๋ฌด์—์„œ๋Š” DB ์—ฐ๋™์œผ๋กœ ๋Œ€์ฒด)
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.builder()
            .username("user1")
            .password(passwordEncoder.encode("user1234"))
            .roles("USER") // ์ž๋™์œผ๋กœ "ROLE_USER" ๊ถŒํ•œ ๋ถ€์—ฌ
            .build();

        UserDetails admin = User.builder()
            .username("admin1")
            .password(passwordEncoder.encode("admin1234"))
            .roles("ADMIN", "USER")
            .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
}

โ‘ก ํ…Œ์ŠคํŠธ ์ปจํŠธ๋กค๋Ÿฌ (HelloController.java)

package com.example.demo.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/public/info")
    public String publicEndpoint() {
        return "๋ˆ„๊ตฌ๋‚˜ ์—ด๋žŒ ๊ฐ€๋Šฅํ•œ ๊ณต๊ฐœ ์ •๋ณด์ž…๋‹ˆ๋‹ค.";
    }

    @GetMapping("/user/profile")
    public String userEndpoint(@AuthenticationPrincipal UserDetails userDetails) {
        return "๋กœ๊ทธ์ธํ•œ ์œ ์ € ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค: " + userDetails.getUsername();
    }

    @GetMapping("/admin/dashboard")
    public String adminEndpoint() {
        return "์ตœ๊ณ  ๊ด€๋ฆฌ์ž ์ „์šฉ ๋Œ€์‹œ๋ณด๋“œ ๋ฐ์ดํ„ฐ์ž…๋‹ˆ๋‹ค.";
    }
}

โ‘ข curl ํ…Œ์ŠคํŠธ ๋ฐ ๊ฒ€์ฆ ๊ฒฐ๊ณผ

# 1. ๊ณต๊ฐœ ๊ฒฝ๋กœ ์š”์ฒญ (์ธ์ฆ ์—†์ด 200 OK ์„ฑ๊ณต)
curl -i http://localhost:8080/api/public/info
# HTTP/1.1 200 OK
# ๋ˆ„๊ตฌ๋‚˜ ์—ด๋žŒ ๊ฐ€๋Šฅํ•œ ๊ณต๊ฐœ ์ •๋ณด์ž…๋‹ˆ๋‹ค.

# 2. ์œ ์ € ๊ฒฝ๋กœ์— ๋น„์ธ๊ฐ€ ์ ‘๊ทผ ์‹œ๋„ (401 Unauthorized ๋ฐ˜ํ™˜)
curl -i http://localhost:8080/api/user/profile
# HTTP/1.1 401 Unauthorized

# 3. HTTP Basic ์ธ์ฆ์œผ๋กœ ์ผ๋ฐ˜ ์œ ์ € ๋กœ๊ทธ์ธ ํ›„ ์ ‘๊ทผ (์„ฑ๊ณต)
curl -i -u user1:user1234 http://localhost:8080/api/user/profile
# HTTP/1.1 200 OK
# ๋กœ๊ทธ์ธํ•œ ์œ ์ € ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค: user1

# 4. ์ผ๋ฐ˜ ์œ ์ €๊ฐ€ ๊ด€๋ฆฌ์ž ๊ฒฝ๋กœ(/api/admin/**) ์ ‘๊ทผ ์‹œ๋„ (403 Forbidden ๊ฑฐ๋ถ€)
curl -i -u user1:user1234 http://localhost:8080/api/admin/dashboard
# HTTP/1.1 403 Forbidden

4. [2๋‹จ๊ณ„] ํ•ต์‹ฌ ๊ธฐ๋Šฅ: REST API ๋ฌด์ƒํƒœ(Stateless) JWT ์™„์ „ ๊ตฌํ˜„

์„ธ์…˜์„ ์„œ๋ฒ„ ๋ฉ”๋ชจ๋ฆฌ์— ์ €์žฅํ•˜์ง€ ์•Š๊ณ , JWT(JSON Web Token)๋ฅผ HTTP ์š”์ฒญ ํ—ค๋”(Authorization: Bearer <token>)๋กœ ์ „๋‹ฌ๋ฐ›์•„ ๊ฒ€์ฆํ•˜๋Š” ํ˜„๋Œ€์ ์ธ ๋ชจ๋˜ ๋ฐฑ์—”๋“œ ํ‘œ์ค€ ์•„ํ‚คํ…์ฒ˜์ž…๋‹ˆ๋‹ค.

โ‘  JJWT 0.12.x ๊ธฐ๋ฐ˜ ํ† ํฐ ๊ณต๊ธ‰์ž (JwtTokenProvider.java)

package com.example.demo.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

@Component
public class JwtTokenProvider {

    // ์‹ค๋ฌด์—์„œ๋Š” application.yml์—์„œ ์ฃผ์ž…๋ฐ›์œผ๋ฉฐ, ๋ฐ˜๋“œ์‹œ 256๋น„ํŠธ(32์ž) ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    private static final String SECRET = "LuckyTechWorldSuperSecretJwtSigningKeyForSpringBootSecurity2026!";
    private static final long ACCESS_TOKEN_VALIDITY = 1000L * 60 * 60; // 1์‹œ๊ฐ„ (๋ฐ€๋ฆฌ์ดˆ)

    private final SecretKey secretKey = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));

    // [1] ํ† ํฐ ๋ฐœ๊ธ‰ (์‚ฌ์šฉ์ž ์ด๋ฆ„๊ณผ ๊ถŒํ•œ ๋ฌธ์ž์—ด ํฌํ•จ)
    public String createAccessToken(String username, String roles) {
        Date now = new Date();
        Date validity = new Date(now.getTime() + ACCESS_TOKEN_VALIDITY);

        return Jwts.builder()
            .subject(username)
            .claim("roles", roles) // ์˜ˆ: "ROLE_USER,ROLE_ADMIN"
            .issuedAt(now)
            .expiration(validity)
            .signWith(secretKey)
            .compact();
    }

    // [2] ํ† ํฐ์—์„œ Authentication ๊ฐ์ฒด ์—ญ์ถ”์ถœ
    public Authentication getAuthentication(String token) {
        Claims claims = getClaims(token);
        String rolesStr = claims.get("roles", String.class);

        Collection<? extends GrantedAuthority> authorities = (rolesStr == null || rolesStr.isBlank())
            ? java.util.Collections.emptyList()
            : Arrays.stream(rolesStr.split(","))
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());

        User principal = new User(claims.getSubject(), "", authorities);
        return new UsernamePasswordAuthenticationToken(principal, token, authorities);
    }

    // [3] ํ† ํฐ ์œ ํšจ์„ฑ ๊ฒ€์ฆ
    public boolean validateToken(String token) {
        try {
            getClaims(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // [4] ํด๋ ˆ์ž„ ํŒŒ์‹ฑ
    private Claims getClaims(String token) {
        return Jwts.parser()
            .verifyWith(secretKey)
            .build()
            .parseSignedClaims(token)
            .getPayload();
    }
}

โ‘ก JWT ์ „์šฉ ์š”์ฒญ ๊ฐ€๋กœ์ฑ„๊ธฐ ํ•„ํ„ฐ (JwtAuthenticationFilter.java)

๋ชจ๋“  ์š”์ฒญ๋งˆ๋‹ค 1ํšŒ ์‹คํ–‰๋˜๋Š” OncePerRequestFilter๋ฅผ ์ƒ์†๋ฐ›์•„ HTTP Authorization ํ—ค๋”์—์„œ ํ† ํฐ์„ ์ถ”์ถœํ•˜๊ณ  SecurityContext์— ๋“ฑ๋กํ•ฉ๋‹ˆ๋‹ค.

package com.example.demo.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenProvider tokenProvider;

    public JwtAuthenticationFilter(JwtTokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);

        // ์œ ํšจํ•œ JWT ํ† ํฐ์ด ์กด์žฌํ•˜๋ฉด SecurityContext์— ์ธ์ฆ ์ •๋ณด ์ €์žฅ
        if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
            Authentication auth = tokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        // ๋‹ค์Œ ํ•„ํ„ฐ๋กœ ์š”์ฒญ ์ธ๊ณ„
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}

โ‘ข ๋ฌด์ƒํƒœ REST API์šฉ ๋ณด์•ˆ ์„ค์ • (JwtSecurityConfig.java)

package com.example.demo.config;

import com.example.demo.security.JwtAuthenticationFilter;
import com.example.demo.security.JwtTokenProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity // @PreAuthorize, @PostAuthorize ๋ฉ”์„œ๋“œ ๋ณด์•ˆ ํ™œ์„ฑํ™”
public class JwtSecurityConfig {

    private final JwtTokenProvider jwtTokenProvider;

    public JwtSecurityConfig(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // [1] REST API์ด๋ฏ€๋กœ CSRF ๋ณดํ˜ธ ๋น„ํ™œ์„ฑํ™” (์„ธ์…˜์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ)
            .csrf(AbstractHttpConfigurer::disable)
            // [2] ํผ ๋กœ๊ทธ์ธ ๋ฐ ๊ธฐ๋ณธ HTTP Basic ๋น„ํ™œ์„ฑํ™”
            .formLogin(AbstractHttpConfigurer::disable)
            .httpBasic(AbstractHttpConfigurer::disable)
            // [3] ์„ธ์…˜ ์ƒ์„ฑ ์ •์ฑ…์„ ๋ฌด์ƒํƒœ(STATELESS)๋กœ ๊ฐ•์ œ ์ง€์ •
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // [4] ์—”๋“œํฌ์ธํŠธ๋ณ„ ์ธ๊ฐ€ ์„ค์ •
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll() // ๋กœ๊ทธ์ธ, ํšŒ์›๊ฐ€์ž… API
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                .anyRequest().authenticated()
            )
            // [5] ์ปค์Šคํ…€ JWT ํ•„ํ„ฐ๋ฅผ UsernamePasswordAuthenticationFilter ์•ž๋‹จ์— ๋ฐฐ์น˜
            .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider),
                             UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

5. [2๋‹จ๊ณ„] ๋ฉ”์„œ๋“œ ๋ ˆ๋ฒจ ๋ณด์•ˆ (Method Security)

์ปจํŠธ๋กค๋Ÿฌ์˜ ๊ฐœ๋ณ„ ์—”๋“œํฌ์ธํŠธ ๋ฉ”์„œ๋“œ ๋˜๋Š” ์„œ๋น„์Šค ๊ณ„์ธต(Service Layer)์˜ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ๋‹จ์œ„๋กœ ์„ธ๋ฐ€ํ•˜๊ฒŒ ๊ถŒํ•œ์„ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค.

package com.example.demo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    // [1] ROLE_ADMIN ์—ญํ• ์„ ๊ฐ€์ง„ ์œ ์ €๋งŒ ์ฃผ๋ฌธ ์ „์ฒด ๋ชฉ๋ก ์กฐํšŒ ๊ฐ€๋Šฅ
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public String getAllOrders() {
        return "์ „์ฒด ์ฃผ๋ฌธ ๋ชฉ๋ก (๊ด€๋ฆฌ์ž ์ „์šฉ)";
    }

    // [2] USER ๋˜๋Š” ADMIN ์—ญํ• ์„ ๊ฐ€์ง„ ์œ ์ €๋งŒ ์ฃผ๋ฌธ ์ƒ์„ธ ์กฐํšŒ ๊ฐ€๋Šฅ
    @GetMapping("/{orderId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public String getOrderDetail(@PathVariable Long orderId) {
        return orderId + "๋ฒˆ ์ฃผ๋ฌธ ์ƒ์„ธ ๋‚ด์—ญ";
    }

    // [3] SpEL ํ‘œํ˜„์‹์„ ํ™œ์šฉํ•˜์—ฌ ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ ์œ ์ € ๋ณธ์ธ์˜ ์ฃผ๋ฌธ๋งŒ ์ทจ์†Œ ๊ฐ€๋Šฅ
    @DeleteMapping("/{orderId}")
    @PreAuthorize("hasRole('ADMIN') or #username == authentication.name")
    public String cancelOrder(@PathVariable Long orderId, @RequestParam String username) {
        return orderId + "๋ฒˆ ์ฃผ๋ฌธ ์ทจ์†Œ ์„ฑ๊ณต (์†Œ์œ ์ž: " + username + ")";
    }

    // [4] ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ ์ฃผ์ฒด(Principal) ์ •๋ณด ํŒŒ๋ผ๋ฏธํ„ฐ ์ง์ ‘ ์ฃผ์ž…
    @GetMapping("/my")
    public String getMyInfo(@AuthenticationPrincipal UserDetails user) {
        return "ํ˜„์žฌ ๋กœ๊ทธ์ธ ์‚ฌ์šฉ์ž: " + user.getUsername();
    }
}

6. [3๋‹จ๊ณ„] ์‹ค๋ฌด ์‘์šฉ: DB/JPA ์—ฐ๋™ & ์ปค์Šคํ…€ ์˜ˆ์™ธ ์‘๋‹ต (JPA & Exception)

โ‘  JPA ์ปค์Šคํ…€ UserDetailsService ์—ฐ๋™

์‹ค์ œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์กฐํšŒํ•˜์—ฌ Spring Security ํ‘œ์ค€ UserDetails ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

package com.example.demo.security;

import com.example.demo.entity.Member;
import com.example.demo.repository.MemberRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final MemberRepository memberRepository;

    public CustomUserDetailsService(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        Member member = memberRepository.findByEmail(email)
            .orElseThrow(() -> new UsernameNotFoundException("ํ•ด๋‹น ์ด๋ฉ”์ผ์˜ ํšŒ์›์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: " + email));

        // DB์˜ Role(์˜ˆ: "USER")์„ "ROLE_USER" ๊ถŒํ•œ์œผ๋กœ ๋งคํ•‘
        return new User(
            member.getEmail(),
            member.getPassword(), // BCrypt ํ•ด์‹œ๋œ ๋น„๋ฐ€๋ฒˆํ˜ธ
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + member.getRole().name()))
        );
    }
}

โ‘ก REST API ์ „์šฉ ์ปค์Šคํ…€ 401 / 403 JSON ์—๋Ÿฌ ํ•ธ๋“ค๋Ÿฌ

์ธ์ฆ ์‹คํŒจ ์‹œ ๊ธฐ๋ณธ HTML ๋กœ๊ทธ์ธ ํผ์œผ๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ๋˜์ง€ ์•Š๊ณ , ํ”„๋ก ํŠธ์—”๋“œ๊ฐ€ ํŒŒ์‹ฑํ•˜๊ธฐ ์‰ฌ์šด ํ‘œ์ค€ JSON ์—๋Ÿฌ ํฌ๋งท์œผ๋กœ ์‘๋‹ตํ•ฉ๋‹ˆ๋‹ค.

1) ์ธ์ฆ ์‹คํŒจ (401 Unauthorized) ํ•ธ๋“ค๋Ÿฌ

package com.example.demo.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        Map<String, Object> body = Map.of(
            "status", 401,
            "error", "Unauthorized",
            "message", "์ธ์ฆ ํ† ํฐ์ด ์œ ํšจํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ๋ˆ„๋ฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.",
            "path", request.getRequestURI()
        );

        response.getWriter().write(objectMapper.writeValueAsString(body));
    }
}

2) ๊ถŒํ•œ ๋ถ€์กฑ (403 Forbidden) ํ•ธ๋“ค๋Ÿฌ

package com.example.demo.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        Map<String, Object> body = Map.of(
            "status", 403,
            "error", "Forbidden",
            "message", "ํ•ด๋‹น ๋ฆฌ์†Œ์Šค์— ์ ‘๊ทผํ•  ๊ถŒํ•œ์ด ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค.",
            "path", request.getRequestURI()
        );

        response.getWriter().write(objectMapper.writeValueAsString(body));
    }
}

3) SecurityConfig์— ์˜ˆ์™ธ ํ•ธ๋“ค๋Ÿฌ ๋“ฑ๋ก

http.exceptionHandling(ex -> ex
    .authenticationEntryPoint(jwtAuthenticationEntryPoint) // 401 ์—๋Ÿฌ
    .accessDeniedHandler(jwtAccessDeniedHandler)           // 403 ์—๋Ÿฌ
);

7. [3๋‹จ๊ณ„] ์‹ค๋ฌด ์‘์šฉ: CORS ์ •๋ฐ€ ์ œ์–ด (Cross-Origin Policy)

SPA(React, Vue, Next.js ๋“ฑ) ํ”„๋ก ํŠธ์—”๋“œ์™€ ๋ถ„๋ฆฌ๋œ ํ™˜๊ฒฝ์—์„œ ๋ฐœ์ƒํ•˜๋Š” ๋ธŒ๋ผ์šฐ์ € CORS(Cross-Origin Resource Sharing) ์ฐจ๋‹จ์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด CorsConfigurationSource๋ฅผ SecurityFilterChain ์ตœ์ƒ๋‹จ์— ๋ฐ”์ธ๋”ฉํ•ฉ๋‹ˆ๋‹ค.

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // 1. ํ—ˆ์šฉํ•  ํ”„๋ก ํŠธ์—”๋“œ Origin ์ถœ์ฒ˜ ๋ช…์‹œ (์šด์˜ ํ™˜๊ฒฝ์—์„œ๋Š” ์™€์ผ๋“œ์นด๋“œ * ์ง€์–‘)
        config.setAllowedOrigins(List.of("http://localhost:3000", "https://techworld.sulucky5.pe.kr"));
        
        // 2. ํ—ˆ์šฉํ•  HTTP ๋ฉ”์„œ๋“œ
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        
        // 3. ํ—ˆ์šฉํ•  ํ—ค๋” ๋ชฉ๋ก
        config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With"));
        
        // 4. ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์‘๋‹ต ํ—ค๋” ์ค‘ ์ฝ์„ ์ˆ˜ ์žˆ๋„๋ก ๋…ธ์ถœํ•  ํ—ค๋”
        config.setExposedHeaders(List.of("Authorization"));
        
        // 5. ์ฟ ํ‚ค ๋ฐ Authorization ํ—ค๋” ํฌํ•จ ์š”์ฒญ ํ—ˆ์šฉ
        config.setAllowCredentials(true);
        
        // 6. ๋ธŒ๋ผ์šฐ์ € Preflight(OPTIONS) ์š”์ฒญ ์บ์‹œ ์‹œ๊ฐ„ (1์‹œ๊ฐ„)
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

์ ์šฉ ๋””๋ ‰ํ‹ฐ๋ธŒ: SecurityConfig ๋‚ด๋ถ€์—์„œ .cors(cors -> cors.configurationSource(corsConfigurationSource()))๋กœ ์ฃผ์ž…ํ•ฉ๋‹ˆ๋‹ค.


8. ์‹ค๋ฌด ์ฃผ์˜์‚ฌํ•ญ & 5.x โž” 6.x ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜ ๊ฐ€์ด๋“œ (Migration & Best Practices)

โš ๏ธ Spring Security 5.x โž” 6.x ํ•ต์‹ฌ ๋ณ€๊ฒฝ ์‚ฌํ•ญ ๋น„๊ต

๊ธฐ๋Šฅ ํ•ญ๋ชฉ๊ตฌ๋ฒ„์ „ ๋ฐฉ์‹ (Spring Security 5.x)์ตœ์‹  ๋ฐฉ์‹ (Spring Security 6.x / Boot 3.x)
์„ค์ • ์ƒ์† ๊ตฌ์กฐextends WebSecurityConfigurerAdapter์ƒ์† ์ œ๊ฑฐ, @Bean SecurityFilterChain ์ง์ ‘ ๋“ฑ๋ก
์ฒด์ด๋‹ ๋ฌธ๋ฒ•.and().csrf().disable().and().cors()์ˆœ์ˆ˜ Lambda DSL ๊ฐ•์ œ (csrf(AbstractHttpConfigurer::disable))
URL ์ธ๊ฐ€ ๋””๋ ‰ํ‹ฐ๋ธŒ.authorizeRequests().authorizeHttpRequests() ๋กœ ๋ช…์นญ ๋ณ€๊ฒฝ
๊ฒฝ๋กœ ๋งค์ฒ˜ ๋ฉ”์„œ๋“œantMatchers("/api/**"), mvcMatchers()requestMatchers("/api/**") ๋กœ ๋‹จ์ผ ํ†ตํ•ฉ
๋ฉ”์„œ๋“œ ๋ณด์•ˆ ์–ด๋…ธํ…Œ์ด์…˜@EnableGlobalMethodSecurity(prePostEnabled=true)@EnableMethodSecurity ๋กœ ๊ฐ„์†Œํ™”

๐Ÿ›ก๏ธ ์ดˆ๋ณด์ž๊ฐ€ ์ž์ฃผ ๊ฒช๋Š” 4๋Œ€ ํ•จ์ • ๋ฐ ํŠธ๋Ÿฌ๋ธ”์ŠˆํŒ…

1. hasRole() vs hasAuthority()์˜ ROLE_ ์ ‘๋‘์‚ฌ ํ˜ผ๋™

  • ์›์ธ: hasRole("ADMIN")์€ ๋‚ด๋ถ€์ ์œผ๋กœ ์ ‘๋‘์‚ฌ ROLE_์„ ์ž๋™์œผ๋กœ ๋ง๋ถ™์—ฌ "ROLE_ADMIN"์„ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค.
  • ํ•ด๊ฒฐ์ฑ…:
    // UserDetailsService ๋˜๋Š” JWT ํด๋ ˆ์ž„์— "ROLE_ADMIN"์œผ๋กœ ์ €์žฅ๋˜์–ด ์žˆ์„ ๋•Œ:
    .hasRole("ADMIN")             // โœ… ์˜ฌ๋ฐ”๋ฆ„ (์ž๋™์œผ๋กœ "ROLE_ADMIN" ๋งค์นญ)
    .hasRole("ROLE_ADMIN")        // โŒ ์‹คํŒจ ("ROLE_ROLE_ADMIN"์„ ์ฐพ์œผ๋ฏ€๋กœ 403 ์—๋Ÿฌ ๋ฐœ์ƒ)
    .hasAuthority("ROLE_ADMIN")   // โœ… ์˜ฌ๋ฐ”๋ฆ„ (์™„์ „ ์ผ์น˜ ๊ฒ€์‚ฌ)

2. CORS ์‚ฌ์ „ ์š”์ฒญ(OPTIONS Preflight)์— 401/403 ์—๋Ÿฌ ๋ฐœ์ƒ

  • ์›์ธ: ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์‹ค์ œ ์š”์ฒญ ์ „ ๋ณด๋‚ด๋Š” OPTIONS ๋ฉ”์„œ๋“œ ์š”์ฒญ์— ์ธ์ฆ ํ—ค๋”๊ฐ€ ์—†์–ด ์‹œํ๋ฆฌํ‹ฐ ํ•„ํ„ฐ์—์„œ ์ฐจ๋‹จ๋จ.
  • ํ•ด๊ฒฐ์ฑ…:
    .authorizeHttpRequests(auth -> auth
        .requestMatchers(org.springframework.http.HttpMethod.OPTIONS, "/**").permitAll() // Preflight ์ „๋ฉด ํ—ˆ์šฉ
        .anyRequest().authenticated()
    )

3. @Async ๋น„๋™๊ธฐ ์Šค๋ ˆ๋“œ์—์„œ SecurityContext ์œ ์‹ค

  • ์›์ธ: SecurityContextHolder์˜ ๊ธฐ๋ณธ ์ „๋žต์€ ThreadLocal์ด๋ฏ€๋กœ, ๋ณ„๋„์˜ ๋น„๋™๊ธฐ ์›Œ์ปค ์Šค๋ ˆ๋“œ๋กœ ๋„˜์–ด๊ฐ€๋ฉด ์‚ฌ์šฉ์ž ์ธ์ฆ ์ •๋ณด๊ฐ€ ์ „ํŒŒ๋˜์ง€ ์•Š๊ณ  null์ด ๋ฉ๋‹ˆ๋‹ค.
  • ํ•ด๊ฒฐ์ฑ…: SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); ์„ค์ • ๋˜๋Š” DelegatingSecurityContextAsyncTaskExecutor ์‚ฌ์šฉ.

4. ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” ์›๋ฌธ ๋…ธ์ถœ ๋ฐ ๋น„๋ฐ€๋ฒˆํ˜ธ ์ผ์น˜ ๊ฒ€์‚ฌ ์˜ค๋ฅ˜

  • ์ฃผ์˜์‚ฌํ•ญ: BCryptPasswordEncoder๋Š” ๋‹จ๋ฐฉํ–ฅ ์†”ํŒ…(Salting) ํ•ด์‹œ์ด๋ฏ€๋กœ encoder.matches(rawPassword, encodedPassword) ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์ผ์น˜ ์—ฌ๋ถ€๋ฅผ ๊ฒ€์ฆํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด์˜ equals() ๋น„๊ต๋Š” ์ ˆ๋Œ€ ๋ถˆ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
๐Ÿ’ฌ

์˜๊ฒฌ ๋ฐ ์งˆ๋ฌธ

0
0 / 1500