Мое глобальное исключение не распознается, когда вы создаете новое исключение из JwtTokenProviderJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Мое глобальное исключение не распознается, когда вы создаете новое исключение из JwtTokenProvider

Сообщение Anonymous »

У меня есть приложение spirngboot, я использую Jwt для обеспечения безопасности, поэтому в сервисах есть этот блок кода
public void registrarUsuario(RegisterDTO registerDTO){
if (authRepository.existsByEmail(registerDTO.getEmail())){
throw new UserAlreadyRegisterException();
}
Usuarios usuario = new Usuarios();
usuario.setPrimer_nombre(registerDTO.getPrimer_nombre());
usuario.setSegundo_nombre(registerDTO.getSegundo_nombre());
usuario.setPrimer_apellido(registerDTO.getPrimer_apellido());
usuario.setSegundo_apellido(registerDTO.getSegundo_apellido());
usuario.setEmail(registerDTO.getEmail());
usuario.setTelefono(registerDTO.getTelefono());
Credenciales credencial = new Credenciales();
credencial.setContraseña(passwordEncoder.encode(registerDTO.getContraseña()));
credencialesRepository.save(credencial);
usuario.setCredenciales(credencial);
Roles roles = rolRepository.findByNombre("usuario").orElseThrow(() -> new NoSuchElementException("No se encontro el rol usuarios"));
usuario.setRoles(Collections.singletonList(roles));
authRepository.save(usuario);
}```

when i try register new user, if user already created create the exception UserAlready... and show the correct format in the response

```{
"timeStamp": "2024-09-27T04:07:37.495+00:00",
"code": "p-500",
"message": "El usuario ya se encuentra registrado en la aplicacion",
"url": "/api/v1/auth/register"
}```

but when i try create exception when token expired in another endpoints my global handling dont catch this exception and only show in my console

this is my code
my handler exceptions


пакет com.api.reservavuelos.Exceptions;
импортировать com.api.reservavuelos.DTO.ResponseExceptionDTO;
импортировать jakarta.servlet .http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
импортировать org.springframework.web.bind.annotation.ExceptionHandler;
импортировать org.springframework.web.bind.annotation.RestControllerAdvice;
импортировать java.util.Date;
@RestControllerAdvice
публичный класс GlobalExceptionHandler {
частная дата таймпоактуал = новая дата();
@ExceptionHandler(JwtTokenExpiredException.class)
public ResponseEntity handleJwtTokenExpiredException(HttpServletRequest request, JwtTokenExpiredException exception){
return new ResponseEntity(new ResponseExceptionDTO(tiempoactual,"P-401", exception.getMessage(), request.getRequestURI()), HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
public ResponseEntity handleAuthenticationCredentialsNotFoundException(HttpServletRequest request , AuthenticationCredentialsNotFoundException exception){
return new ResponseEntity(new ResponseExceptionDTO(tiempoactual,"P-401", exception.getMessage(), request.getRequestURI()), HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity handleUserNotFoundException(HttpServletRequest request, UserNotFoundException exception) {
return new ResponseEntity(new ResponseExceptionDTO(tiempoactual,"P-404", exception.getMessage(), request.getRequestURI()), HttpStatus.NOT_FOUND);
}

@ExceptionHandler(UserAlreadyRegisterException.class)
public ResponseEntity handleUserAlreadyRegisterException(HttpServletRequest request, UserAlreadyRegisterException exception) {
return new ResponseEntity(new ResponseExceptionDTO(tiempoactual,"p-500", exception.getMessage(), request.getRequestURI()), HttpStatus.BAD_REQUEST);
}


my JwtTokenProvider
```package com.api.reservavuelos.Security;

import com.api.reservavuelos.Exceptions.JwtTokenExpiredException;
import com.api.reservavuelos.Exceptions.UserAlreadyRegisterException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenProvider {

public String generateToken(Authentication authentication) {
// Implementación JWT Token generación
String username = authentication.getName();
Date tiempoactual = new Date();
Date expiracion = new Date(tiempoactual.getTime() + ConstantSecurity.JWT_EXPIRATION_TOKEN);

String Token = Jwts.builder()
.setSubject(username)
.setIssuedAt(tiempoactual)
.setExpiration(expiracion)
.signWith(SignatureAlgorithm.HS512, ConstantSecurity.JWT_FIRMA)
.compact();

return Token;
}

public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(ConstantSecurity.JWT_FIRMA)
.build()
.parseClaimsJws(token)
.getBody();

return claims.getSubject();
}

public Boolean IsValidToken(String token) {
try {
Jwts.parser()
.setSigningKey(ConstantSecurity.JWT_FIRMA)
.build()
.parseClaimsJws(token);
return true;
}catch (ExpiredJwtException e) {
throw new JwtTokenExpiredException("Jwt ha expirado");
} catch (AuthenticationCredentialsNotFoundException e) {
throw new AuthenticationCredentialsNotFoundException("Jwt esta incorrecto");
}
}

}


Подробнее здесь: https://stackoverflow.com/questions/790 ... enprovider
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»