0Pricing
Spring Boot 4 Microservices & REST APIs · درس

التحكم في الوصول القائم على الأدوار

هيّئ التفويض القائم على الأدوار لتحديد أذونات وصول دقيقة لأدوار المستخدمين المختلفة.

التحكم في الوصول القائم على الأدوار درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 3 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Intro to Role-Based Access

Role-Based Access Control (RBAC) is a method of restricting system access based on the roles of individual users.

Instead of assigning permissions directly to users, you assign permissions to roles, and then assign roles to users.

  • Simplifies security management.
  • Improves security policy enforcement.
  • Easier to audit and maintain.

Benefits of RBAC

RBAC offers several advantages for securing your applications:

  • Scalability: Easily manage access for many users and resources as your application grows.
  • Flexibility: Roles can be changed or updated without modifying individual user permissions.
  • Compliance: Helps meet regulatory requirements by clearly defining who can do what.

Representing User Roles

In Spring Security, roles are typically represented as simple strings, often prefixed with ROLE_ (e.g., ROLE_ADMIN, ROLE_USER).

It's good practice to define these as constants or enums to avoid typos.

public enum UserRole {
  ADMIN,
  USER
}

Spring Security automatically adds the ROLE_ prefix when you use expressions like hasRole('ADMIN').

public enum UserRole {
  ADMIN,
  USER
}

Basic Security Setup

To enable method-level security and configure users with roles, we set up a SecurityFilterChain bean.

This example defines an in-memory user 'admin' with ROLE_ADMIN and 'user' with ROLE_USER.

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.method.configuration.EnableMethodSecurity;
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
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true) // Enable @PreAuthorize
public class RbacApplication {

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(org.springframework.security.config.Customizer.withDefaults());
        return http.build();
    }

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

@RestController
class PlaceholderController {
    @GetMapping("/")
    public String home() {
        return "Welcome to RBAC Demo!";
    }
}

Applying Role Constraints

Spring Security's @PreAuthorize annotation allows you to define access rules directly on controller methods.

It uses Spring Expression Language (SpEL) to evaluate conditions before a method is executed.

@PreAuthorize("hasRole('ADMIN')")

This ensures only users with the ADMIN role can call the method.

@PreAuthorize("hasRole('ADMIN')")

Exclusive Admin Access

Let's create an endpoint that only users with the ADMIN role can access. If a USER tries to access it, they will get a 403 Forbidden error.

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.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class RbacApplication {

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(org.springframework.security.config.Customizer.withDefaults());
        return http.build();
    }

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

@RestController
class AdminController {

    @GetMapping("/admin/dashboard")
    @PreAuthorize("hasRole('ADMIN')")
    public String getAdminDashboard() {
        return "Welcome, Admin! This is your dashboard.";
    }

    @GetMapping("/")
    public String home() {
        return "Welcome to RBAC Demo!";
    }
}

Granting Multiple Roles

Sometimes, an endpoint should be accessible by more than one role. You can use hasAnyRole() for this.

For example, a dashboard might be visible to both ADMIN and regular USER roles.

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.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class RbacApplication {

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(org.springframework.security.config.Customizer.withDefaults());
        return http.build();
    }

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

@RestController
class MultiRoleController {

    @GetMapping("/dashboard")
    @PreAuthorize("hasAnyRole('ADMIN', 'USER')")
    public String getUserDashboard() {
        return "Hello! Welcome to your dashboard.";
    }

    @GetMapping("/admin/settings")
    @PreAuthorize("hasRole('ADMIN')")
    public String getAdminSettings() {
        return "Admin settings page.";
    }

    @GetMapping("/")
    public String home() {
        return "Welcome to RBAC Demo!";
    }
}

Custom Access Decisions

While hasRole() and hasAnyRole() cover many cases, Spring Security allows more complex access rules.

You can use SpEL to check multiple conditions, like hasRole('ADMIN') and hasIpAddress('192.168.1.0/24').

For very complex or dynamic logic, you can implement custom PermissionEvaluator beans.

Testing Your RBAC

You can test your RBAC configuration by running your Spring Boot application and using a tool like Postman or curl:

  • Log in as 'admin' (user: admin, pass: password) and try to access all endpoints.
  • Log in as 'user' (user: user, pass: password) and verify access to user endpoints, but not admin-only ones.
  • Try without authentication to see if it's rejected.

RBAC Access Check

Consider the following Spring Security configuration and controller method:

@Configuration
@EnableMethodSecurity(prePostEnabled = true)
// ... other config ...

@Bean
public UserDetailsService userDetailsService() {
    UserDetails userA = User.withDefaultPasswordEncoder()
        .username("alice").password("pw").roles("USER").build();
    UserDetails userB = User.withDefaultPasswordEncoder()
        .username("bob").password("pw").roles("MANAGER").build();
    return new InMemoryUserDetailsManager(userA, userB);
}

@RestController
class MyController {
    @GetMapping("/report")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public String getReport() {
        return "Confidential Report";
    }
}

Which user(s) can successfully access the /report endpoint?

@Configuration
@EnableMethodSecurity(prePostEnabled = true)
// ... other config ...

@Bean
public UserDetailsService userDetailsService() {
    UserDetails userA = User.withDefaultPasswordEncoder()
        .username("alice").password("pw").roles("USER").build();
    UserDetails userB = User.withDefaultPasswordEncoder()
        .username("bob").password("pw").roles("MANAGER").build();
    return new InMemoryUserDetailsManager(userA, userB);
}

@RestController
class MyController {
    @GetMapping("/report")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public String getReport() {
        return "Confidential Report";
    }
}

RBAC Lesson Summary

In this lesson, we explored Role-Based Access Control (RBAC) in Spring Boot Microservices.

  • We learned how to define and assign roles to users.
  • We configured Spring Security to recognize these roles using SecurityFilterChain.
  • We used @PreAuthorize with hasRole() and hasAnyRole() to secure API endpoints based on user roles.

RBAC is a powerful way to manage access control efficiently and securely in your applications.

الأسئلة الشائعة

هل درس «التحكم في الوصول القائم على الأدوار» مجاني؟

نعم — نص درس «التحكم في الوصول القائم على الأدوار» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

ماذا ستتعلم في «التحكم في الوصول القائم على الأدوار»؟

هيّئ التفويض القائم على الأدوار لتحديد أذونات وصول دقيقة لأدوار المستخدمين المختلفة. تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟

لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 3.

كم من الوقت يستغرق درس «التحكم في الوصول القائم على الأدوار»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟

نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. أساسيات OAuth2 وJWT
  2. تأمين نقاط نهاية REST
  3. التحكم في الوصول القائم على الأدوار
← العودة إلى Spring Boot 4 Microservices & REST APIs