You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
4 Hrs
11 Min
13 Seg

¿Cómo funciona el BasicAuthenticationFilter?

6/23
Resources

How does the Basic Authentication Filter work in Spring Security?

The authentication process in Spring Security is a fundamental part of ensuring the security of our applications. By delegating this process to a filter in the Security Filter Chain, specifically the Basic Authentication Filter, it ensures that the user's credentials are correct before granting access to protected resources. But how does this filter actually work?

What happens when a request is received?

  • Interception of the request: Spring Security's filter chain captures the request and passes it through all configured security filters.
  • Credentials verification: When it reaches the Basic Authentication Filter, it verifies if the user and password sent are correct.

What is the role of the Authentication Manager?

The Authentication Manager acts as a coordinator in the authentication process, deciding how the user should be authenticated:

  • Selects the authentication method: determines whether authentication will be by user and password, Auth0, LDAP, etc.
  • Interaction with Authentication Provider: In the case of the Basic Authentication Filter, it uses the DAO Authentication Provider to verify the user and password credentials.

How is the flow with the DAO Authentication Provider?

The flow continues with the DAO Authentication Provider, which:

  • Queries the User Detail Service: Since in-memory users and passwords are used by Spring, it uses the In-Memory User Detail Service.
  • Password verification: Compares the password provided with the one stored for the requested user.

How to debug the Basic Authentication Filter?

To better understand this process, a debug can be done in the Spring code. The key is in the method doFilterInternal of the Basic Authentication Filter, where:

  1. Set points of interest: place checkpoints on key lines to follow the authentication flow.
  2. Launch the application in debug mode: Allow the application to stop at these points to examine the state of the process.
  3. Observe the passage through the lines: Verify how the UserPasswordAuthenticationToken is handled and how it interacts with the AuthenticationManager.

What is the role of the Abstract User Details Authentication Provider?

The Abstract User Details Authentication Provider establishes some important preliminary validations:

  • User load: Through the retrieveUser method, the user is retrieved from an In-MemoryUserDetailsService.
  • Validation of the user and password: From line 147, it makes sure that the provided password matches the stored one.

What are the results after verification?

  • Successful authentication: If the credentials are correct, the user is loaded into the security context.
  • Response to the request: Finally, the system responds with a status 200 confirming that the process has been successful.

As developers, it is essential to go beyond the superficial use of frameworks such as Spring Security. Understanding how it works internally, especially basic authentication, provides a clearer picture and empowers us to better manage security in our applications. While it is not necessary to learn everything about the inner workings of Spring Security, this is an opportunity to appreciate the value of understanding what goes on behind the scenes, helping us become more informed and competent developers. Keep learning and exploring! I look forward to seeing you in the next class to talk about CSRF protection in Spring.

Contributions 13

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Lo que entiendo es:
.
Se validar la autenticación del usuario, el cual pasa por diferentes filtros de seguridad de manera encadenada:
.

  1. Basic Authenticacion Filter: Valida si el usr y pw son correctos o no
  2. Authentcation Manager: Coordinador que valida el tipo de autenticación si es (usr/pw, Autho0, LDAP…)
  3. Authentication Provider: Es capaz de validar la autenticación de usr/pw por el método DaoAuthenticationProvider.
  4. User Details Service: En este punto se valida si la contraseña del usuario corresponde a la que se recibió a través de la petición.

.
Finalmente, Cuando identifica que es correcto, se lo devuelve al Authentcation Manager, éste a su vez se lo retorna al Basic Authenticacion Filter para que continue su curso y pueda permitir mostrar la información al usuario autenticado.
.

Entendí bastante poco, eso es lo bonito de esto, cuando uno empieza a ver temas mas avanzados se empieza a perder de nuevo jajaja

Sería interesante un segundo curso avanzado donde se apliquen y contrasten otros métodos como LDAP o Auth0, usar Okta por ejemplo, SSO, providers como autenticación con Google o Facebook, entender como aplicar seguridad con sesiones también, ver ejemplos con monolitos, microservicios, hexagonal y diferentes situaciones, ahí les dejo la idea. Excelente curso, ya lo vi y lo estoy repasando antes del examen, muchas gracias Alejandro y Platzi

Para buscar la clase pueden usar Ctrl + N para IntelliJ, Para Eclipse Ctrl + Shift + T

Me llamo la atención lo que mencionas al final, que usamos frameworks sin entender como funcionan internamente. Platzi debería profundizar en esos conocimientos para llegar a entender como funciona por dentro un framework

No entendí mucho, pero me encanto el ver como funciona internamente 👏🤩

Excelente la explicación del funcionamiento a nivel interno como funciona este flujo de autenticación!!!

Gran clase!
El `BasicAuthenticationFilter` es un componente de Spring Security que maneja la autenticación de usuarios a través de un esquema básico. Cuando llega una petición a la aplicación, este filtro intercepta la solicitud y extrae las credenciales (usuario y contraseña) que se envían. Luego, se comunica con el `AuthenticationManager`, que coordina el proceso de autenticación. El flujo es el siguiente: 1. El filtro recibe la solicitud y verifica las credenciales. 2. Si las credenciales son correctas, se envían al `AuthenticationProvider` (generalmente un `DAO Authentication Provider` para autenticar usando el usuario y contraseña). 3. Finalmente, si la autenticación es exitosa, el filtro permite que la petición continúe y se establece el contexto de seguridad. Este proceso garantiza que solo los usuarios autenticados puedan acceder a los recursos protegidos de la aplicación.
Actualmente, si hay cosas que cambian dentro de las clases respecto a este video, pero se puede apreciar el mismo proceso indicado. Y adicional tambien se repasa un poco el debuguear en Intellij.
Muy buena clase!

Para version Java SDK 19

package org.example.confing;
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.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();

        return http.build();
    }
}