0Pricing
Spring Boot 4 Complete Guide · 강의

인증 및 권한 부여

데이터베이스를 사용하여 사용자 인증을 구성하고 다양한 역할과 경로에 대한 접근 제어 규칙을 정의합니다.

인증 및 권한 부여은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

AuthN vs. AuthZ

In security, we often talk about two key concepts: Authentication and Authorization.

  • Authentication (AuthN) is about verifying who you are. Think of it like showing your ID to prove your identity.
  • Authorization (AuthZ) is about determining what you are allowed to do once your identity is confirmed. This is like your ID granting you access to certain areas.

Database Auth Flow

Spring Security can use user details stored in a database to authenticate users. Instead of hardcoding users, we can connect to a real data source.

The process typically involves:

  • A user attempts to log in.
  • Spring Security fetches user details (username, password, roles) from your database.
  • It verifies the password.
  • If successful, the user is authenticated.

Fetching User Details

The core interface for retrieving user-specific data in Spring Security is UserDetailsService. You'll implement this to tell Spring how to find users in your database.

It has one method: loadUserByUsername(String username). This method returns a UserDetails object, which holds the user's username, password, and authorities (roles).

Custom UserDetailsService

Let's create a simple UserDetailsService. For now, we'll simulate fetching users from a list, but in a real app, this would query a database.

Notice we return a User object, which is a common implementation of UserDetails.

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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class MyUserDetailsService implements UserDetailsService {

    private final Map<String, UserDetails> users = new HashMap<>();

    public MyUserDetailsService(PasswordEncoder passwordEncoder) {
        // Simulate users from a database
        users.put("user", User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build());
        users.put("admin", User.builder()
            .username("admin")
            .password(passwordEncoder.encode("adminpass"))
            .roles("ADMIN", "USER")
            .build());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = users.get(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }
        return user;
    }
}

Securing Passwords

Storing passwords as plain text is a major security risk. Spring Security requires you to use a PasswordEncoder to securely hash (encode) passwords.

The most common implementation is BCryptPasswordEncoder, which uses a strong hashing algorithm. You'll define this as a Spring bean.

Wiring Up Authentication

Now, let's wire our UserDetailsService and PasswordEncoder into Spring Security's configuration. We'll define a SecurityFilterChain bean.

This filter chain tells Spring how to handle requests, including authentication.

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

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final UserDetailsService userDetailsService;

    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable()) // Disable CSRF for simplicity in this example
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated() // All other requests require authentication
            )
            .formLogin(form -> form.permitAll()); // Enable form login for browser access
        return http.build();
    }
}

Full Auth Demo

Here's a complete Spring Boot application demonstrating basic authentication using our custom UserDetailsService and PasswordEncoder. Try accessing /hello after logging in!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
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.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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class AuthApp {
    public static void main(String[] args) {
        SpringApplication.run(AuthApp.class, args);
    }
}

@RestController
class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, authenticated user!";
    }
}

@Service
class MyUserDetailsService implements UserDetailsService {
    private final Map<String, UserDetails> users = new HashMap<>();

    public MyUserDetailsService(PasswordEncoder passwordEncoder) {
        users.put("user", User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build());
        users.put("admin", User.builder()
            .username("admin")
            .password(passwordEncoder.encode("adminpass"))
            .roles("ADMIN", "USER")
            .build());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = users.get(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }
        return user;
    }
}

@Configuration
@EnableWebSecurity
class SecurityConfig {
    private final UserDetailsService userDetailsService;

    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.permitAll());
        return http.build();
    }
}

What You Can Do

Once a user is authenticated, authorization determines what resources or actions they are permitted to access. This is done by checking their assigned roles or authorities.

For example, an "ADMIN" user might access admin pages, while a "USER" user can only see their profile.

Securing Paths by Role

Spring Security allows you to define authorization rules directly in your SecurityFilterChain. You can protect specific URL patterns based on roles.

Key methods:

  • .requestMatchers("/admin/**").hasRole("ADMIN"): Only users with the 'ADMIN' role can access URLs under /admin/.
  • .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN"): Users with 'USER' or 'ADMIN' role.
  • .anyRequest().authenticated(): All other requests need any authenticated user.

AuthZ in Action

Let's add authorization rules to our previous example. Try logging in as 'user' (password: 'password') and 'admin' (password: 'adminpass') and access the different endpoints.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
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.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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class AuthZApp {
    public static void main(String[] args) {
        SpringApplication.run(AuthZApp.class, args);
    }
}

@RestController
class SecuredController {
    @GetMapping("/public")
    public String publicPage() {
        return "This is a public page.";
    }

    @GetMapping("/user/profile")
    public String userProfile() {
        return "Welcome, user! This is your profile.";
    }

    @GetMapping("/admin/dashboard")
    public String adminDashboard() {
        return "Welcome, admin! This is the admin dashboard.";
    }
}

@Service
class MyUserDetailsService implements UserDetailsService {
    private final Map<String, UserDetails> users = new HashMap<>();

    public MyUserDetailsService(PasswordEncoder passwordEncoder) {
        users.put("user", User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build());
        users.put("admin", User.builder()
            .username("admin")
            .password(passwordEncoder.encode("adminpass"))
            .roles("ADMIN", "USER")
            .build());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = users.get(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }
        return user;
    }
}

@Configuration
@EnableWebSecurity
class SecurityConfig {
    private final UserDetailsService userDetailsService;

    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/public").permitAll() // Public access
                .requestMatchers("/user/**").hasRole("USER") // Only USER role
                .requestMatchers("/admin/**").hasRole("ADMIN") // Only ADMIN role
                .anyRequest().authenticated() // All others need authentication
            )
            .formLogin(form -> form.permitAll());
        return http.build();
    }
}

Quick Check

Review the concepts of authentication and authorization, and the components involved.

Recap & Next Steps

Great job! In this lesson, you learned to:

  • Distinguish between Authentication and Authorization.
  • Understand how Spring Security uses databases for authentication.
  • Implement a custom UserDetailsService to fetch user data.
  • Use PasswordEncoder to secure user passwords.
  • Configure URL-based authorization rules using roles.

Next, you'll explore more advanced security features like JWT-based authentication for stateless APIs!

자주 묻는 질문

“인증 및 권한 부여” 강의는 무료인가요?

네 — “인증 및 권한 부여” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

“인증 및 권한 부여”에서 뭘 배우나요?

데이터베이스를 사용하여 사용자 인증을 구성하고 다양한 역할과 경로에 대한 접근 제어 규칙을 정의합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“인증 및 권한 부여” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Spring Security 기초
  2. 인증 및 권한 부여
  3. JWT 기반 보안
  4. OAuth2와 소셜 로그인 통합
← Spring Boot 4 Complete Guide(으)로 돌아가기