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

تكامل AuthenticationManager وموفّرات المصادقة

اربط مرشح JWT الخاص بكم مع `AuthenticationManager` في Spring Security وموفّرات المصادقة المخصّصة.

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

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

Orchestrating Authentication

Welcome to the core of Spring Security's authentication process! Today, we'll connect our JWT filter with two vital components: the AuthenticationManager and AuthenticationProvider.

These components work together to verify a user's identity and establish their security context.

The Manager's Core Responsibility

The AuthenticationManager is the central interface in Spring Security for handling authentication requests. Think of it as the conductor of an orchestra.

  • It receives an Authentication object (representing a user's credentials).
  • It delegates the actual authentication task to one or more AuthenticationProviders.
  • If successful, it returns a fully authenticated Authentication object.

The Role of AuthenticationProvider

While the AuthenticationManager orchestrates, AuthenticationProviders are the specialized workers.

Each provider knows how to authenticate a specific type of user or credential (e.g., username/password, LDAP, or in our case, a JWT). It contains the logic to validate the credentials.

Crafting a JWT Token Object

For our JWT flow, we need a way to represent an unauthenticated JWT within Spring Security. We'll create a custom Authentication implementation, often called JwtAuthenticationToken.

  • It will hold the raw JWT string when unauthenticated.
  • After authentication, it will hold the authenticated user's details (UserDetails) and authorities.

Building Our JWT Provider

Now, let's create our own JwtAuthenticationProvider. This class will implement the AuthenticationProvider interface.

Its main job is to take our JwtAuthenticationToken, validate the JWT, extract user details, and return a fully authenticated token.

JwtAuthenticationProvider Logic

Here's a simplified look at what our JwtAuthenticationProvider's authenticate method might do. It checks if the token is valid and then builds an authenticated object.

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collections;

public class CustomJwtAuthProvider implements AuthenticationProvider {

  @Override
  public Authentication authenticate(Authentication authentication)
      throws AuthenticationException {
    // In a real app, you'd validate the JWT here.
    // For this example, we'll assume it's valid if it's our custom type.
    if (authentication instanceof JwtAuthenticationToken) {
      // Simulate successful JWT validation
      // Extract username and roles from the JWT payload
      String username = "coddykitUser"; // From JWT subject
      // Roles would also come from JWT claims
      // For simplicity, we grant a basic role
      GrantedAuthority role = () -> "ROLE_USER";
      User userDetails = new User(username, "", Collections.singletonList(role));

      // Return a fully authenticated token
      // The credentials (JWT string) are usually cleared
      return new JwtAuthenticationToken(userDetails, Collections.singletonList(role));
    }
    return null; // Not our type of authentication
  }

  @Override
  public boolean supports(Class<?> authentication) {
    // This provider supports our custom JwtAuthenticationToken
    return JwtAuthenticationToken.class.isAssignableFrom(authentication);
  }

  // Simple placeholder for our custom token
  static class JwtAuthenticationToken implements Authentication {
    private final User userDetails;
    private final String jwtToken;
    private boolean authenticated;
    private java.util.Collection<? extends GrantedAuthority> authorities;

    public JwtAuthenticationToken(String jwtToken) {
      this.jwtToken = jwtToken;
      this.userDetails = null;
      this.authenticated = false;
      this.authorities = Collections.emptyList();
    }

    public JwtAuthenticationToken(User userDetails,
                                  java.util.Collection<? extends GrantedAuthority> authorities) {
      this.userDetails = userDetails;
      this.jwtToken = null; // Token already validated
      this.authenticated = true;
      this.authorities = authorities;
    }

    @Override
    public java.util.Collection<? extends GrantedAuthority> getAuthorities() {
      return authorities;
    }

    @Override
    public Object getCredentials() {
      return jwtToken; // The raw JWT string (if unauthenticated)
    }

    @Override
    public Object getDetails() {
      return userDetails;
    }

    @Override
    public Object getPrincipal() {
      return userDetails; // The authenticated user object
    }

    @Override
    public boolean isAuthenticated() {
      return authenticated;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated)
        throws IllegalArgumentException {
      this.authenticated = isAuthenticated;
    }

    @Override
    public String getName() {
      return userDetails != null ? userDetails.getUsername() : "N/A";
    }
  }

  public static void main(String[] args) {
    System.out.println("CustomJwtAuthProvider initialized.");
    // In a real app, Spring Security would call authenticate()
    // We're just demonstrating the class structure here.
  }
}

Wiring Up the Provider

For our JwtAuthenticationProvider to be used, we must register it with Spring Security's configuration. This is typically done in your security configuration class.

Spring Boot often auto-configures the AuthenticationManager, but we can add custom providers to it.

Filter-Manager Interaction

Remember our custom JwtAuthenticationFilter from the previous lesson? Now we connect it to the AuthenticationManager.

  • The filter will extract the JWT from the request.
  • It will create an unauthenticated JwtAuthenticationToken.
  • It will then pass this token to the AuthenticationManager for processing.

The manager, in turn, will find and use our JwtAuthenticationProvider.

JWT Authentication Journey

Let's trace the full authentication flow with our new components:

  1. Client sends request with JWT in the Authorization header.
  2. Our JwtAuthenticationFilter intercepts the request, extracts the JWT.
  3. Filter creates an unauthenticated JwtAuthenticationToken.
  4. Filter calls AuthenticationManager.authenticate() with this token.
  5. AuthenticationManager finds our JwtAuthenticationProvider (because supports() returns true).
  6. JwtAuthenticationProvider validates the JWT and builds a fully authenticated JwtAuthenticationToken (containing UserDetails and authorities).
  7. The filter receives the authenticated token and sets it in the SecurityContextHolder.
  8. The request proceeds, now knowing who the user is and what they can do!

Understanding the Flow

Which statements accurately describe the roles of AuthenticationManager and AuthenticationProvider in a Spring Security JWT setup?

Bringing It All Together

In this lesson, we've explored how AuthenticationManager acts as the central orchestrator and how a custom AuthenticationProvider handles the specific logic for validating JWTs.

By integrating these components with our JwtAuthenticationFilter, we've established a robust and modular JWT authentication flow within Spring Security. This separation of concerns makes your security configuration flexible and maintainable!

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

هل درس «تكامل AuthenticationManager وموفّرات المصادقة» مجاني؟

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

ماذا ستتعلم في «تكامل AuthenticationManager وموفّرات المصادقة»؟

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

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

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

كم من الوقت يستغرق درس «تكامل AuthenticationManager وموفّرات المصادقة»؟

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

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

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

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

  1. تصميم تدفق مصادقة JWT
  2. تنفيذ مرشّح JWT مخصّص
  3. تكامل AuthenticationManager وموفّرات المصادقة
  4. معالجة أخطاء المصادقة ونقاط الدخول
← العودة إلى Spring Security 6 & JWT Authentication