0Pricing
Spring Security 6 & JWT Authentication · درس

تأمين نقاط النهاية بقواعد وصول مخصصة

تجاوز عمليات التحقق البسيطة من الأدوار بكتابة منطق تفويض مخصص في Spring Security 6 باستخدام AuthorizationManager وتعبيرات SpEL ومطابقات الطلبات

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

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

Why Custom Access Rules?

Roles and methods cover most cases, but real apps need finer control: only the owner of a resource may edit it, or access depends on the time of day or a feature flag.

Spring Security 6 lets you express these rules declaratively or programmatically.

The authorizeHttpRequests DSL

In Spring Security 6 the modern way to secure URLs is authorizeHttpRequests. Each matcher maps a request pattern to an access rule.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/public/**').permitAll()
    .requestMatchers('/admin/**').hasRole('ADMIN')
    .anyRequest().authenticated());

Matching by HTTP Method

You can scope rules to a specific HTTP method, so reads and writes have different requirements.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers(HttpMethod.GET, '/api/orders/**').authenticated()
    .requestMatchers(HttpMethod.POST, '/api/orders/**').hasRole('MANAGER'));

SpEL with access()

The access() rule takes a Spring Expression Language (SpEL) condition for dynamic logic that plain matchers cannot express.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/reports/**')
    .access(new WebExpressionAuthorizationManager(
        "hasRole('ANALYST') and request.getHeader('X-Region') == 'EU'")));

The AuthorizationManager Interface

For full control, implement AuthorizationManager. It returns an AuthorizationDecision that grants or denies access based on the authentication and the request.

public interface AuthorizationManager<T> {
    AuthorizationDecision check(Supplier<Authentication> auth, T object);
}

Writing a Custom AuthorizationManager

Here is a manager that only allows access during business hours. The supplier gives the current user; the object holds request context.

AuthorizationManager<RequestAuthorizationContext> businessHours =
    (auth, ctx) -> {
        int hour = LocalTime.now().getHour();
        boolean ok = hour >= 9 && hour < 18;
        return new AuthorizationDecision(ok);
    };

Plugging It In

Attach your custom manager to a matcher with access(). Any request to the path is now evaluated by your logic.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/maintenance/**').access(businessHours)
    .anyRequest().authenticated());

Owner-Based Access

A common rule: only the resource owner can modify it. You can read a path variable from the request context to compare against the logged-in user.

AuthorizationManager<RequestAuthorizationContext> ownerOnly =
    (auth, ctx) -> {
        String pathUser = ctx.getVariables().get('userId');
        boolean same = auth.get().getName().equals(pathUser);
        return new AuthorizationDecision(same);
    };

Combining Rules

Spring evaluates matchers top to bottom and stops at the first match. Order matters: put specific rules before broad ones, and always end with a catch-all like anyRequest().

Denying by Default

A secure baseline denies everything not explicitly allowed. Use denyAll() as the final rule when you want a strict allow-list.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/health').permitAll()
    .anyRequest().denyAll());

Testing Access Rules

Verify your rules with @WithMockUser and MockMvc. Assert that authorized users get 200 and unauthorized users get 403.

mockMvc.perform(get('/admin/dashboard'))
    .andExpect(status().isForbidden());

Quick Check

Test your understanding of custom access rules.

Recap

You learned to write custom authorization in Spring Security 6:

  • Use the authorizeHttpRequests DSL with path and method matchers
  • Apply SpEL conditions via access()
  • Implement AuthorizationManager for dynamic, owner-based, or time-based rules
  • Order matters; end with a catch-all and prefer deny-by-default

These tools let you enforce business-specific security policies precisely.

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

هل درس «تأمين نقاط النهاية بقواعد وصول مخصصة» مجاني؟

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

ماذا ستتعلم في «تأمين نقاط النهاية بقواعد وصول مخصصة»؟

تجاوز عمليات التحقق البسيطة من الأدوار بكتابة منطق تفويض مخصص في Spring Security 6 باستخدام AuthorizationManager وتعبيرات SpEL ومطابقات الطلبات تتمرن على Spring Security 6 & JWT Authentication مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Security 6 & JWT Authentication؟

لا تُشترط خبرة سابقة. Spring Security 6 & JWT Authentication على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «تأمين نقاط النهاية بقواعد وصول مخصصة»؟

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

هل يمكنني كتابة وتشغيل أكواد في درس Spring Security 6 & JWT Authentication هذا؟

نعم. كل درس في Spring Security 6 & JWT Authentication يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

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

  1. التحكم في الوصول القائم على الأدوار (RBAC)
  2. الأمان على مستوى الأساليب باستخدام التعليقات التوضيحية
  3. تعمّق في تهيئة HttpSecurity
  4. تأمين نقاط النهاية بقواعد وصول مخصصة
← العودة إلى Spring Security 6 & JWT Authentication