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

การควบคุมการเข้าถึงตามบทบาท (RBAC)

นำการอนุญาตตามบทบาทไปใช้เพื่อจำกัดการเข้าถึงทรัพยากรเฉพาะตามบทบาทและสิทธิ์ของผู้ใช้

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

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

Understanding RBAC Basics

Welcome! Today we'll dive into Role-Based Access Control (RBAC). It's a fundamental security concept for managing who can do what in an application.

Imagine a school: students can view grades, teachers can post grades, and administrators can manage all users. Each group has a 'role' with specific 'permissions'.

  • Role: A collection of permissions.
  • Permission: The ability to perform a specific action (e.g., read, write, delete).

Roles in Spring Security

Spring Security uses roles to enforce authorization. When you define a user, you also assign them one or more roles.

Internally, Spring Security treats roles as Granted Authorities. By convention, roles are often prefixed with ROLE_ (e.g., ROLE_ADMIN, ROLE_USER). This helps distinguish them from other types of authorities.

Assigning Roles to Users

Before we can use RBAC, users need roles! When a user logs in, Spring Security's authentication process retrieves their assigned roles.

These roles are typically loaded from a database via a UserDetailsService, or for simpler cases, defined directly in memory. We'll use in-memory users for our examples to keep things clear.

Securing URLs with `hasRole()`

The core of RBAC in Spring Security for web applications is configuring HttpSecurity. We use methods like hasRole() to specify which roles can access certain URL patterns.

For example, to protect an 'admin' page, you might write: .requestMatchers("/admin/**").hasRole("ADMIN"). Spring Security automatically adds the ROLE_ prefix when you use hasRole().

RBAC Web Security Config

Let's see a simple Spring Security configuration. This setup defines two in-memory users (user and admin) and secures two endpoints: /user and /admin.

Try running this code and accessing the URLs!

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
@RestController
public class Main {

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

  @GetMapping("/user")
  public String userEndpoint() {
    return "Hello, User!";
  }

  @GetMapping("/admin")
  public String adminEndpoint() {
    return "Hello, Admin!";
  }

  @Configuration
  @EnableWebSecurity
  static class WebSecurityConfig {

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
      http
          .authorizeHttpRequests(authorize -> authorize
              .requestMatchers("/user/**").hasRole("USER")
              .requestMatchers("/admin/**").hasRole("ADMIN")
              .anyRequest().authenticated()
          )
          .formLogin(org.springframework.security.config.Customizer.withDefaults());
      return http.build();
    }
  }
}

Testing Our RBAC Setup

After running the previous example, open your browser and try to access these URLs:

  • http://localhost:8080/user: Log in with user/password or admin/password. Both should work!
  • http://localhost:8080/admin: Log in with admin/password. This should work.
  • http://localhost:8080/admin: Log in with user/password. You should see an 'Access Denied' error (403 Forbidden).

This demonstrates how roles restrict access!

Multiple Roles: `hasAnyRole()`

What if an endpoint can be accessed by more than one role? Spring Security provides hasAnyRole() for this.

Instead of listing multiple hasRole() calls, you can do: .requestMatchers("/dashboard/**").hasAnyRole("USER", "ADMIN"). This grants access if the authenticated user has EITHER the USER role OR the ADMIN role.

`hasRole()` vs `hasAuthority()`

You might also see hasAuthority() being used. What's the difference?

  • hasRole("ADMIN"): This implicitly adds the ROLE_ prefix, so it checks for ROLE_ADMIN.
  • hasAuthority("ROLE_ADMIN"): This requires the exact authority string, including the ROLE_ prefix if it's part of the authority name.

Generally, hasRole() is preferred for clarity when dealing with roles defined with the ROLE_ prefix.

Securing Specific HTTP Methods

RBAC can also be applied to specific HTTP methods for a given path. This is useful for REST APIs where different actions (GET, POST, PUT, DELETE) require different permissions.

You can chain requestMatchers() with HttpMethod:

.requestMatchers(HttpMethod.POST, "/products/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/products/**").hasAnyRole("USER", "ADMIN")

Here, only ADMIN can create products, but both USER and ADMIN can view them.

Best Practices for RBAC

To make RBAC effective and manageable:

  • Keep Roles Simple: Don't create too many roles. Roles should represent distinct job functions.
  • Least Privilege: Grant only the necessary roles/permissions to users.
  • Centralized Management: Manage roles and their assignments from a single, secure place.
  • Audit Regularly: Periodically review role assignments and permissions to ensure they are still appropriate.

RBAC Knowledge Check

You've learned about implementing Role-Based Access Control in Spring Security. Let's quickly test your understanding!

Recap: Role-Based Access Control

Great job! In this lesson, you learned about:

  • What RBAC is and its importance for authorization.
  • How Spring Security uses roles (as GrantedAuthority).
  • Configuring URL-based RBAC with HttpSecurity.
  • Using hasRole() and hasAnyRole() to protect endpoints.
  • Distinguishing between hasRole() and hasAuthority().
  • Applying RBAC to specific HTTP methods.
  • Key best practices for effective RBAC implementation.

You now have a solid foundation for controlling access based on user roles!

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

บทเรียน “การควบคุมการเข้าถึงตามบทบาท (RBAC)” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การควบคุมการเข้าถึงตามบทบาท (RBAC)”

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

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

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

บทเรียน “การควบคุมการเข้าถึงตามบทบาท (RBAC)” ใช้เวลานานแค่ไหน

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

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

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

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

  1. การควบคุมการเข้าถึงตามบทบาท (RBAC)
  2. การรักษาความปลอดภัยระดับเมธอดด้วยแอนโนเทชัน
  3. เจาะลึกการกำหนดค่า HttpSecurity
  4. รักษาความปลอดภัยให้ปลายทางด้วยกฎการเข้าถึงแบบกำหนดเอง
← กลับไปที่ Spring Security 6 & JWT Authentication