Spring Boot 4 Microservices & REST APIs · บทเรียน

การรักษาความปลอดภัย REST Endpoint

ใช้ Spring Security เพื่อปกป้อง REST API endpoint จากการเข้าถึงโดยไม่ได้รับอนุญาต

บทเรียน 2 จาก 311 ขั้นตอน

การรักษาความปลอดภัย REST Endpoint เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Secure Your API Endpoints?

APIs are gateways to your application's data and functionality. Without proper security, anyone could access, modify, or delete sensitive information.

This lesson will show you how Spring Security helps protect your REST APIs from unauthorized access, ensuring only legitimate users can interact with your services.

Spring Security: Your API's Bouncer

Spring Security is a powerful and highly customizable framework for authentication and access control. For REST APIs, it acts like a bouncer, checking credentials before allowing requests to reach your endpoints.

  • It handles user authentication (who you are).
  • It manages authorization (what you can do).
  • It protects against common web vulnerabilities.

Get Started: Add Dependency

To integrate Spring Security into your Spring Boot project, you need to add its starter dependency to your pom.xml file (if using Maven).

This dependency brings in all the necessary Spring Security components and auto-configuration.

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

Default Security Behavior

Once the Spring Security dependency is added, your Spring Boot application automatically secures all HTTP endpoints!

When you run the app, Spring Security generates a random password and logs it to the console. You'll need this password, along with the default username "user", to access any endpoint.

Customizing Security Rules

The default security is a good start, but you'll want to define your own rules. We do this by creating a security configuration class.

This class uses @Configuration and @EnableWebSecurity, and defines a SecurityFilterChain bean to customize HTTP security.

Try running this basic setup. It will still require authentication, but we'll add users next!

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.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.httpBasic(); // Enable basic auth
        http.authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated() // All requests need auth
        );
        return http.build();
    }
}

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

Defining Users in Memory

For simple applications or testing, you can define users directly in your security configuration using an InMemoryUserDetailsManager bean.

We'll add a user named "user" with password "password" and role "USER". Note: withDefaultPasswordEncoder() is for quick demos; in production, use strong password encoders.

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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

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

Endpoint-Specific Authorization

You can define different security rules for different URL patterns using requestMatchers(). The anyRequest().authenticated() rule ensures all other requests require authentication.

Here, we'll make our /hello endpoint require authentication, while other paths will be public.

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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/hello").authenticated() // /hello requires auth
            .anyRequest().permitAll() // All other requests are public
        );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

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

    @GetMapping("/public")
    public String publicEndpoint() {
        return "Hello, Public!";
    }
}

Public Endpoints with permitAll()

Sometimes you need endpoints that don't require any authentication, like a health check or public information. For these, you use .permitAll().

Order matters! More specific rules (like /public/**) should come before more general ones (like anyRequest()).

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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/public/**").permitAll() // Public access
            .requestMatchers("/secure/**").authenticated() // Requires authentication
            .anyRequest().denyAll() // Deny all other requests by default
        );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

@RestController
class MyController {
    @GetMapping("/public/info")
    public String publicInfo() {
        return "This is public information!";
    }

    @GetMapping("/secure/data")
    public String secureData() {
        return "This is secure data!";
    }
}

CSRF Protection & REST APIs

CSRF (Cross-Site Request Forgery) protection is crucial for browser-based applications. However, for stateless REST APIs typically consumed by non-browser clients (like mobile apps or other services), CSRF protection is generally not needed and can sometimes cause issues.

You can explicitly disable it in your security configuration:

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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // Disable CSRF for REST APIs
            .httpBasic();
        http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/public/**").permitAll()
            .requestMatchers("/secure/**").authenticated()
            .anyRequest().denyAll()
        );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

@RestController
class MyController {
    @GetMapping("/public/info")
    public String publicInfo() {
        return "This is public information!";
    }

    @GetMapping("/secure/data")
    public String secureData() {
        return "This is secure data!";
    }
}

Quick Check: Security Access

Consider the following SecurityConfig. What would happen if you try to access /api/status without providing any credentials?

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.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .httpBasic();
        http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/api/public/**").permitAll()
            .requestMatchers("/api/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
        );
        return http.build();
    }
}

Lesson Recap: Securing Endpoints

In this lesson, you learned the foundational steps to secure your Spring Boot REST API endpoints:

  • Added the Spring Security dependency.
  • Understood the default security behavior.
  • Configured a SecurityFilterChain to define custom rules.
  • Set up in-memory users for basic authentication.
  • Used requestMatchers() with permitAll() and authenticated() to define access for specific paths.
  • Disabled CSRF protection for stateless REST APIs.

This knowledge is crucial for building robust and secure microservices!

เริ่มต้นได้ฟรี

เรียนรู้ Java ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
24
บทเรียน
93

คำถามที่พบบ่อย

บทเรียน “การรักษาความปลอดภัย REST Endpoint” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การรักษาความปลอดภัย REST Endpoint” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การรักษาความปลอดภัย REST Endpoint”

ใช้ Spring Security เพื่อปกป้อง REST API endpoint จากการเข้าถึงโดยไม่ได้รับอนุญาต คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “การรักษาความปลอดภัย REST Endpoint” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐาน OAuth2 และ JWT
  2. การรักษาความปลอดภัย REST Endpoint
  3. การควบคุมการเข้าถึงตามบทบาท
← กลับไปที่ Spring Boot 4 Microservices & REST APIs