forked from axel/FocusAgenda
62 lines
2.5 KiB
Java
62 lines
2.5 KiB
Java
package com.agendaestudantil.filtro;
|
|
|
|
import com.agendaestudantil.utilitario.UtilJwt;
|
|
import jakarta.servlet.FilterChain;
|
|
import jakarta.servlet.ServletException;
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
import org.springframework.security.core.userdetails.UserDetails;
|
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
import org.springframework.stereotype.Component;
|
|
import org.springframework.web.filter.OncePerRequestFilter;
|
|
|
|
import java.io.IOException;
|
|
|
|
@Component
|
|
public class FiltroJwt extends OncePerRequestFilter {
|
|
|
|
private final UtilJwt utilJwt;
|
|
private final UserDetailsService userDetailsService;
|
|
|
|
public FiltroJwt(UtilJwt utilJwt, UserDetailsService userDetailsService) {
|
|
this.utilJwt = utilJwt;
|
|
this.userDetailsService = userDetailsService;
|
|
}
|
|
|
|
@Override
|
|
protected boolean shouldNotFilter(HttpServletRequest request) {
|
|
String path = request.getRequestURI();
|
|
return path.equals("/") || path.equals("/index.html") || path.equals("/favicon.ico")
|
|
|| path.startsWith("/static/") || path.startsWith("/css/") || path.startsWith("/js/")
|
|
|| path.startsWith("/img/") || path.endsWith(".css") || path.endsWith(".js")
|
|
|| path.endsWith(".ico") || path.endsWith(".html");
|
|
}
|
|
|
|
@Override
|
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
|
throws ServletException, IOException {
|
|
|
|
String header = request.getHeader("Authorization");
|
|
String token = null;
|
|
String estudanteId = null;
|
|
|
|
if (header != null && header.startsWith("Bearer ")) {
|
|
token = header.substring(7);
|
|
estudanteId = utilJwt.getEstudanteIdFromToken(token);
|
|
}
|
|
|
|
if (estudanteId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
|
UserDetails userDetails = userDetailsService.loadUserByUsername(estudanteId);
|
|
|
|
if (utilJwt.validateToken(token)) {
|
|
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
|
userDetails, null, userDetails.getAuthorities());
|
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
}
|
|
}
|
|
|
|
filterChain.doFilter(request, response);
|
|
}
|
|
} |