Spring Security 6 & JWT Authentication · บทเรียน

การเสริมความปลอดภัยสำหรับระบบจริง

ใช้การกำหนดค่าและแนวทางปฏิบัติด้านความปลอดภัยที่จำเป็น เพื่อเสริมความแข็งแกร่งให้แอปพลิเคชัน Spring Security สำหรับสภาพแวดล้อมใช้งานจริง

บทเรียน 1 จาก 411 ขั้นตอน

การเสริมความปลอดภัยสำหรับระบบจริง เป็นบทเรียน Spring Security 6 & JWT Authentication ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Security 6 & JWT Authentication และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Security 6 & JWT Authentication มีบทเรียนทั้งหมด 4 บทเรียน

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

Production Hardening Intro

Welcome to Production Security Hardening! Securing an application in development is one thing, but production environments demand much higher vigilance.

In this lesson, we'll explore essential configurations and best practices to protect your Spring Security application when it goes live.

This isn't just about fixing bugs; it's about building a robust defense against real-world threats.

Why HTTPS is Non-Negotiable

In production, all communication between clients and your server must be encrypted using HTTPS (HTTP Secure).

  • Data Confidentiality: Protects sensitive data (passwords, personal info) from eavesdropping.
  • Data Integrity: Ensures data isn't tampered with during transmission.
  • Authentication: Verifies the server's identity to the client.

Without HTTPS, your application is vulnerable to Man-in-the-Middle (MITM) attacks.

Enforcing HTTPS with Spring Security

Spring Security can enforce that all requests must use a secure channel (HTTPS). If an HTTP request comes in, it will be redirected to HTTPS (if your server is configured for SSL).

The requiresSecure() method ensures this. Try running this minimal Spring Boot app and observe its behavior if you try to access it via HTTP (e.g., http://localhost:8080).

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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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;

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

    @Configuration
    @EnableWebSecurity
    static class SecurityConfig {

        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(authorize -> authorize
                    .anyRequest().authenticated()
                )
                .requiresChannel(channel -> channel
                    .anyRequest().requiresSecure() // Enforce HTTPS
                )
                .formLogin(); // Basic form login for testing
            return http.build();
        }

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

Overview of Security Headers

HTTP Security Headers are crucial for preventing common web vulnerabilities. They instruct browsers on how to behave when interacting with your application.

Key headers to configure:

  • HSTS (Strict-Transport-Security): Forces browsers to use HTTPS for future visits.
  • CSP (Content-Security-Policy): Prevents XSS attacks by restricting content sources.
  • X-Frame-Options: Stops clickjacking by controlling if your site can be embedded in an iframe.
  • X-Content-Type-Options: Prevents MIME-sniffing attacks.
  • Referrer-Policy: Controls how much referrer information is sent.

Configuring Security Headers

Spring Security provides convenient methods to configure these headers via HttpSecurity.headers(). This ensures your application's responses always include these vital instructions for the client's browser.

Here's how you can set up some common security headers in your configuration:

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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.header.writers.ReferrerPolicyHeaderWriter;

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

    @Configuration
    @EnableWebSecurity
    static class SecurityConfig {

        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(authorize -> authorize
                    .anyRequest().authenticated()
                )
                .headers(headers -> headers
                    .httpStrictTransportSecurity(hsts -> hsts
                        .includeSubDomains(true)
                        .maxAgeInSeconds(31536000) // 1 year
                    )
                    .contentSecurityPolicy(csp -> csp
                        .policyDirectives("default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'")
                    )
                    .frameOptions(frameOptions -> frameOptions.deny()) // X-Frame-Options: DENY
                    .xContentTypeOptions() // X-Content-Type-Options: nosniff
                    .referrerPolicy(referrer -> referrer
                        .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)
                    )
                )
                .formLogin();
            return http.build();
        }

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

Disabling Sensitive Endpoints

In production, you should disable or restrict access to any endpoints that could reveal sensitive information or allow unintended control.

  • Actuator Endpoints: Spring Boot Actuator provides useful operational insights (/actuator/**). In production, expose only necessary endpoints (e.g., /health, /info) and secure them.
  • HTTP TRACE/OPTIONS Methods: These methods can sometimes be exploited for information disclosure or cross-site tracing attacks. It's often best to disable them.

Always review what's exposed and ensure it's absolutely necessary and secured.

Custom Error Handling

Default error pages in development can expose stack traces and internal server details, which are valuable to attackers.

In production, configure custom error pages that provide minimal information. For example, a simple 'Error 500 - Internal Server Error' message without specifics.

Spring Boot allows you to define custom error pages (e.g., src/main/resources/public/error.html or src/main/resources/templates/error/404.html for specific status codes).

Secure Session Management

Session cookies are critical for maintaining user state, so they need robust protection. Spring Security helps, but you can further harden them.

  • HttpOnly: Prevents client-side scripts from accessing the cookie.
  • Secure: Ensures the cookie is only sent over HTTPS.
  • SameSite: Mitigates CSRF attacks by restricting when cookies are sent with cross-site requests (Lax or Strict).

These are often configured in application.properties, but Spring Security's sessionManagement() also offers controls.

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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.http.SessionCreationPolicy;
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;

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

    @Configuration
    @EnableWebSecurity
    static class SecurityConfig {

        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(authorize -> authorize
                    .anyRequest().authenticated()
                )
                .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // Default, but good to be explicit
                    .sessionFixation().migrateSession() // Protects against session fixation attacks
                )
                .csrf(csrf -> csrf.disable()) // CSRF is enabled by default, disable for simplicity in this example
                .formLogin();
            return http.build();
        }

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

Secure Secrets Management

Never hardcode sensitive information (secrets) like database credentials, API keys, or encryption keys directly in your code or configuration files.

Best practices for managing secrets in production:

  • Environment Variables: Load secrets from environment variables.
  • Externalized Configuration: Use Spring Cloud Config Server or similar tools.
  • Dedicated Secret Management Services: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault are designed for this purpose.

This prevents secrets from being exposed in source control or build artifacts.

Production Hardening Check

Which of the following are recommended practices for hardening a Spring Security application in a production environment? Select all that apply.

Recap & Next Steps

Great job! You've learned crucial steps to harden your Spring Security application for production.

We covered:

  • The necessity of HTTPS and how to enforce it.
  • Configuring vital HTTP security headers.
  • Restricting sensitive endpoints and providing custom error pages.
  • Implementing secure session management practices.
  • Best practices for managing secrets.

These practices form a strong foundation for a secure deployment. Next, we'll dive into logging and monitoring security events to detect and respond to threats effectively.

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

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

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

คอร์ส
12
บทเรียน
48

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

บทเรียน “การเสริมความปลอดภัยสำหรับระบบจริง” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การเสริมความปลอดภัยสำหรับระบบจริง”

ใช้การกำหนดค่าและแนวทางปฏิบัติด้านความปลอดภัยที่จำเป็น เพื่อเสริมความแข็งแกร่งให้แอปพลิเคชัน Spring Security สำหรับสภาพแวดล้อมใช้งานจริง คุณปฏิบัติ Spring Security 6 & JWT Authentication ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Security 6 & JWT Authentication หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Security 6 & JWT Authentication บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การเสริมความปลอดภัยสำหรับระบบจริง” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Spring Security 6 & JWT Authentication นี้ได้ไหม

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

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

  1. การเสริมความปลอดภัยสำหรับระบบจริง
  2. การบันทึกล็อกและเฝ้าติดตามเหตุการณ์ด้านความปลอดภัย
  3. ช่องโหว่ด้านความปลอดภัยที่พบบ่อยและวิธีแก้ไข
  4. การกำหนดส่วนหัวความปลอดภัยและ HTTPS
← กลับไปที่ Spring Security 6 & JWT Authentication