У меня есть приложение 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
Мое глобальное исключение не распознается, когда вы создаете новое исключение из JwtTokenProvider ⇐ JAVA
Программисты JAVA общаются здесь
1727411456
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");
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79029826/my-global-exception-dont-catch-when-y-create-new-exception-from-jwttokenprovider[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия