พื้นฐาน Spring Security
ตั้งค่า Spring Security ทำความเข้าใจสถาปัตยกรรม และนำการยืนยันตัวตนพื้นฐานในหน่วยความจำไปใช้
พื้นฐาน Spring Security เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Welcome to Spring Security!
Securing web applications is crucial in today's digital world. Spring Security is a powerful and highly customizable authentication and access-control framework for Spring applications.
It provides robust security features, allowing you to protect your application from common vulnerabilities and control who can access what.
Why Spring Security?
Imagine building an online store. You need to:
- Authenticate users: Verify a user's identity (login).
- Authorize actions: Determine what a user can do (e.g., only admins can delete products).
- Protect against threats: CSRF, XSS, session fixation.
Spring Security handles all these complex tasks, letting you focus on your application's core logic.
Adding the Security Dependency
To get started, you just need to add the spring-boot-starter-security dependency to your project. This starter brings in all necessary Spring Security modules.
For Maven, add this to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>Default Security in Action
Once the dependency is added, Spring Boot automatically configures basic security. Try running this simple application:
package com.coddykit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SecurityApp {
public static void main(String[] args) {
SpringApplication.run(SecurityApp.class, args);
}
@GetMapping("/hello")
public String hello() {
return "Hello, Secured World!";
}
}Default Login & Password
When you run the previous code with the Spring Security dependency, you'll notice something:
- Accessing
/helloredirects you to a login page. - Spring Security generates a random password, printed in the console at startup.
The username is typically user, and the password is the generated one. This is basic, out-of-the-box security!
AuthN vs. AuthZ
Let's clarify two fundamental concepts:
- Authentication (AuthN): Verifying who you are. This is typically done with credentials like username/password.
- Authorization (AuthZ): Determining what you are allowed to do once authenticated. For example, a user might be authenticated, but only an 'admin' role can delete data.
Spring Security handles both!
The Security Filter Chain
At its core, Spring Security works by intercepting HTTP requests. It uses a series of filters, called the Security Filter Chain, to apply security logic.
When a request comes in, these filters perform tasks like authentication, authorization, session management, and more, before the request even reaches your controller.
Basic In-Memory Authentication
For simple applications or testing, you can define users directly in your application's memory. This is called in-memory authentication.
You'll configure a UserDetailsService bean that provides user details. Let's see how to define a custom user with a specific role.
Configuring In-Memory Users
Here's how to define a user 'john' with password 'pass' and role 'USER'. Remember to encode passwords!
package com.coddykit;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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
@RestController
@EnableWebSecurity
public class SecurityConfigApp {
public static void main(String[] args) {
SpringApplication.run(SecurityConfigApp.class, args);
}
@GetMapping("/public")
public String publicAccess() {
return "This is a public page!";
}
@GetMapping("/user")
public String userAccess() {
return "Welcome, authenticated user!";
}
@Configuration
static class WebSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/public").permitAll()
.requestMatchers("/user").hasRole("USER")
.anyRequest().authenticated()
)
.formLogin(login -> login
.permitAll()
);
return http.build();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.builder()
.username("john")
.password(passwordEncoder.encode("pass"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
}Testing In-Memory Users
Run the previous application. Now try accessing:
http://localhost:8080/public: Should be accessible without login.http://localhost:8080/user: Should redirect to login. Use username 'john' and password 'pass'.http://localhost:8080/admin: Should redirect to login, then show 403 Forbidden even after logging in as 'john', because 'john' doesn't have the 'ADMIN' role.
Quick Check: Spring Security
You've learned about the basics of Spring Security and in-memory authentication. Let's test your understanding.
Lesson Summary
Great job! In this lesson, you've taken your first steps with Spring Security:
- Understood its purpose and core concepts (AuthN, AuthZ).
- Added the necessary dependency and observed default behavior.
- Learned about the Security Filter Chain.
- Implemented basic in-memory authentication with custom users and role-based URL protection.
Next, we'll explore how to handle authentication and authorization using databases and more advanced techniques!
คำถามที่พบบ่อย
บทเรียน “พื้นฐาน Spring Security” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พื้นฐาน Spring Security” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พื้นฐาน Spring Security”
ตั้งค่า Spring Security ทำความเข้าใจสถาปัตยกรรม และนำการยืนยันตัวตนพื้นฐานในหน่วยความจำไปใช้ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “พื้นฐาน Spring Security” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พื้นฐาน Spring Security
- การยืนยันตัวตนและการอนุญาตสิทธิ์
- ความปลอดภัยโดยใช้ JWT
- การผสานรวม OAuth2 และการเข้าสู่ระบบด้วยบัญชีโซเชียล