Se corrigen warnings

parent 5846ef25
...@@ -4,19 +4,31 @@ import lombok.AllArgsConstructor; ...@@ -4,19 +4,31 @@ import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import java.util.List; import java.util.Collection;
@AllArgsConstructor @AllArgsConstructor
public class CustomUserDetails implements UserDetails { public class CustomUserDetails implements UserDetails {
private String username;
private String password; //private final ModelUzyTUsuario usuario;
private List<GrantedAuthority> authorities;
public CustomUserDetails(Object o) {
}
@Override @Override
public String getUsername() { public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
return username; @Override
public String getPassword() {
return null;
} }
@Override
public String getUsername() {
return null;
}
@Override @Override
public boolean isAccountNonExpired() { public boolean isAccountNonExpired() {
...@@ -38,15 +50,6 @@ public class CustomUserDetails implements UserDetails { ...@@ -38,15 +50,6 @@ public class CustomUserDetails implements UserDetails {
return true; return true;
} }
@Override
public String getPassword() {
return password;
}
@Override
public List<GrantedAuthority> getAuthorities() {
return authorities;
}
// Implementa los demás métodos de UserDetails según sea necesario // Implementa los demás métodos de UserDetails según sea necesario
} }
package ec.edu.espe.movilidad.MovilidadWS.Security;
import ec.edu.espe.movilidad.MovilidadWS.Dao.DaoUzyTUsuario;
import ec.edu.espe.movilidad.MovilidadWS.Model.ModelUzyTUsuario;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
private final DaoUzyTUsuario daoUzyTUsuario;
public CustomUserDetailsService(DaoUzyTUsuario daoUzyTUsuario) {
this.daoUzyTUsuario = daoUzyTUsuario;
}
@Override
public UserDetails loadUserByUsername(String findBySpridenID) throws UsernameNotFoundException {
ModelUzyTUsuario usuario = daoUzyTUsuario.findBySpridenID(findBySpridenID)
.orElseThrow(() -> new UsernameNotFoundException("Usuario no encontrado: " + findBySpridenID));
logger.info("Tipo de usuario {}", usuario);
return new CustomUserDetails(usuario);
}
}
...@@ -20,16 +20,16 @@ import static ec.edu.espe.movilidad.MovilidadWS.Constant.GlobalConstants.SECRET_ ...@@ -20,16 +20,16 @@ import static ec.edu.espe.movilidad.MovilidadWS.Constant.GlobalConstants.SECRET_
public class JwtAuthenticationFilter extends OncePerRequestFilter { public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); private static final Logger loggerToken = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try { try {
String authorizationHeader = request.getHeader("Authorization"); String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
String token = authorizationHeader.substring(7); // Eliminar "Bearer " del encabezado String token = authorizationHeader.substring(7); // Eliminar "Bearer" del encabezado
logger.info("Token recibido en el backend: {}", token); loggerToken.info("Token recibido en el backend: {}", token);
UsernamePasswordAuthenticationToken authentication = getAuthentication(token); UsernamePasswordAuthenticationToken authentication = getAuthentication(token);
...@@ -38,7 +38,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { ...@@ -38,7 +38,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
} catch (Exception e) { } catch (Exception e) {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
logger.error("Error en el filtro de autenticación JWT: {}", e.getMessage()); loggerToken.error("Error en el filtro de autenticación JWT: {}", e.getMessage());
} }
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
...@@ -48,30 +48,29 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { ...@@ -48,30 +48,29 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
try { try {
if (tokenEsValido(token)) { if (tokenEsValido(token)) {
UserDetails userDetails = getUserDetailsFromToken(token); UserDetails userDetails = getUserDetailsFromToken(token);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, null);
logger.info("Token válido obtenido en el backend: {}", token); loggerToken.info("Token válido obtenido en el backend: {}", token);
return authenticationToken; return authenticationToken;
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("Error al obtener la autenticación desde el token: {}", e.getMessage());
} }
return null; return null;
} }
private boolean tokenEsValido(String token) { private boolean tokenEsValido(String token) {
logger.info("token de validación: {}", token); loggerToken.info("token de validación: {}", token);
UserDetails userDetails = getUserDetailsFromToken(token); UserDetails userDetails = getUserDetailsFromToken(token);
boolean isValid = JwtUtils.validateToken(token, userDetails); boolean isValid = JwtUtils.validateToken(token, userDetails);
logger.info("Resultado de la validación del token: {}", isValid); loggerToken.info("Resultado de la validación del token: {}", isValid);
return isValid; return isValid;
} }
private UserDetails getUserDetailsFromToken(String token) { private UserDetails getUserDetailsFromToken(String token) {
try { try {
logger.info("Extrayendo detalles del usuario del token: {}", token); loggerToken.info("Extrayendo detalles del usuario del token: {}", token);
Claims claims = Jwts.parserBuilder() Claims claims = Jwts.parserBuilder()
.setSigningKey(SECRET_KEY) .setSigningKey(SECRET_KEY)
.build() .build()
...@@ -79,9 +78,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { ...@@ -79,9 +78,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
.getBody(); .getBody();
String username = claims.getSubject(); String username = claims.getSubject();
return new CustomUserDetails(username, "", null); //return new CustomUserDetails(username, "", null);
return new CustomUserDetails(null);
} catch (Exception e) { } catch (Exception e) {
logger.error("Error al obtener los detalles del usuario desde el token: {}", e.getMessage());
} }
return null; return null;
......
package ec.edu.espe.movilidad.MovilidadWS.Security;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException{
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No autorizado");
}
}
...@@ -3,7 +3,7 @@ package ec.edu.espe.movilidad.MovilidadWS.Security; ...@@ -3,7 +3,7 @@ package ec.edu.espe.movilidad.MovilidadWS.Security;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static ec.edu.espe.movilidad.MovilidadWS.Constant.GlobalConstants.SECRET_KEY;
import java.util.Date; import java.util.Date;
...@@ -22,7 +22,6 @@ public class JwtUtils { ...@@ -22,7 +22,6 @@ public class JwtUtils {
public static String extractUsername(String token) { public static String extractUsername(String token) {
return Jwts.parserBuilder() return Jwts.parserBuilder()
.setSigningKey(SECRET_KEY)
.build() .build()
.parseClaimsJws(token) .parseClaimsJws(token)
.getBody() .getBody()
...@@ -31,7 +30,6 @@ public class JwtUtils { ...@@ -31,7 +30,6 @@ public class JwtUtils {
public static boolean isTokenExpired(String token) { public static boolean isTokenExpired(String token) {
return Jwts.parserBuilder() return Jwts.parserBuilder()
.setSigningKey(SECRET_KEY)
.build() .build()
.parseClaimsJws(token) .parseClaimsJws(token)
.getBody() .getBody()
......
...@@ -13,10 +13,20 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic ...@@ -13,10 +13,20 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@Configuration @Configuration
public class SecurityConfig { public class SecurityConfig {
private final JwtEntryPoint jwtEntryPoint;
public SecurityConfig(JwtEntryPoint jwtEntryPoint) {
this.jwtEntryPoint = jwtEntryPoint;
}
@Bean @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http http
.csrf().disable() .csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(jwtEntryPoint)
.and()
.cors() .cors()
.and() .and()
.authorizeRequests() .authorizeRequests()
......
# POOL CONFIG # POOL CONFIG
spring.datasource.hikari.connection-timeout = 20000 spring.datasource.hikari.connection-timeout = 20000
#maximum number of milliseconds that a client will wait for a connection #maximum number of milliseconds that a client will wait for a connection
spring.datasource.hikari.minimum-idle= 5 spring.datasource.hikari.minimum-idle= 5
#minimum number of idle connections maintained by HikariCP in a connection pool #minimum number of idle connections maintained by HikariCP in a connection pool
...@@ -9,7 +9,7 @@ spring.datasource.hikari.idle-timeout=10000 ...@@ -9,7 +9,7 @@ spring.datasource.hikari.idle-timeout=10000
#maximum idle time for connection #maximum idle time for connection
spring.datasource.hikari.max-lifetime= 1000 spring.datasource.hikari.max-lifetime= 1000
# maximum lifetime in milliseconds of a connection in the pool after it is closed. # maximum lifetime in milliseconds of a connection in the pool after it is closed.
spring.datasource.hikari.auto-commit =true spring.datasource.hikari.auto-commit =true
#spring.datasource.url=jdbc:oracle:thin:@//localhost/XE #spring.datasource.url=jdbc:oracle:thin:@//localhost/XE
spring.datasource.url=jdbc:oracle:thin:@//10.1.0.40:1521/PRODM1 spring.datasource.url=jdbc:oracle:thin:@//10.1.0.40:1521/PRODM1
...@@ -26,3 +26,7 @@ spring.servlet.multipart.enabled=true ...@@ -26,3 +26,7 @@ spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-file-size=10MB
logging.level.org.springframework.security= DEBUG logging.level.org.springframework.security= DEBUG
# security
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment