Introducción
Seguridad en aplicaciones web
¿Qué es Spring Security?
Configurar Spring Security
Usar la autenticación por defecto
Configuración de seguridad
Crear configuración inicial de seguridad
¿Cómo funciona el BasicAuthenticationFilter?
Deshabilitar protección CSRF
Crear configuración de CORS
Aplicar requestMatchers
Crear autenticación en memoria
Aplicar requestMatchers con roles
Autenticación con BD
Crear usuarios en la base de datos
Implementar la interface UserDetailsService
Asignar roles a usuario
Aplicar authorities a los usuarios
Controlar métodos con Method Security
Seguridad con JWT
Añadir JWT al proyecto
Crear JWT cuando un usuario inicie sesión
Crear servicio para validar un JWT
Crear filtro para verificar el JWT
Aplicar filtro en la configuración
Próximos pasos
Auditoria de usuarios en la base de datos
¿Quieres un Curso de Microservicios con Java Spring?
You don't have access to this class
Keep learning! Join and start boosting your career
To enable a user to securely log in and receive a JSON Web Token for authentication, it is first necessary to understand the authentication flow. This flow is crucial to ensure that only users with valid credentials can gain access to the protected functionalities of the application.
Receiving the authentication request: The application will receive a request through the AuthController
in the login
method.
Calling the authentication flow: This flow is initiated by calling the AuthenticationManager
, which in turn interacts with the AuthenticationProvider
. This manager is responsible for authenticating the user by means of username
and password
.
User verification: The AuthenticationProvider
uses the UserDetailService
(in this case UserSecurityService
) to retrieve the user details from the database. If the credentials are correct, a 200 status code is returned, along with a JSON Web Token.
Here is an example of how to create the controller and flow in code:
@RestController@RequestMapping("/api/auth")public class AuthController { @PostMapping("/login") public ResponseEntity<Void> login(@RequestBody LoginDTO loginDto) { Authentication login = new UsernamePasswordAuthenticationToken( loginDto.getUsername(), loginDto.getPassword()); Authentication authentication = authenticationManager.authenticate(login); if (authentication.isAuthenticated()) { String jwt = jwtUtil.createToken(login.getUsername()); return ResponseEntity.ok().header(HttpHeaders.AUTHORIZATION, jwt).build(); } return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } }}
It is important to stipulate which API paths require authentication and which should be left unprotected to allow logins. Here the security configuration should be adjusted to enable access to the required end-points, ensuring that login
requests do not require prior authentication.
SecurityConfig
to allow access to the /api/auth/**
endpoint.@Overrideprotected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/api/auth/**").permitAll().anyRequest().authenticated();}
Thus, the authentication endpoint will be publicly accessible, which is essential for a user to be able to log in and get their authorization token.
During the authentication process, it is vital to properly handle possible errors. For example, a credential rejection should return a 401 status code with a clear message to the user, indicating that the credentials provided are not correct.
Unauthorized
error.if (!authentication.isAuthenticated()) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();}
This approach ensures that the application provides appropriate feedback on authentication status, thus improving the user experience and application security. In addition, urging developers to rely on this infrastructure provides a clear and secure way to manage authentication in their applications.
Continue exploring, understanding more about authentication and its implementation in modern Spring Security-based applications - your effort in continuous improvement is the key to success in this ever-changing technological world!
Contributions 5
Questions 2
La anotacion @Autowired a nivel del constructor en el controller es redundante, esto debido a que Spring inyecta implícitamente los beans que sean requeridos y que este definidos como private final
✅
Want to see more contributions, questions and answers from the community?