Hola, al tratar de realizar el listado de medicos en insomnia me marca 403: Forbidden y esto en terminal: Errores en terminal. Revise las soluciones anteriores, pero Segun yo todo está correcto. Adjunto codigo de las clases SecurityFilter, TokenService y SecurityConfigurations. SecurityFilter:
public class SecurityFilter extends OncePerRequestFilter {
@Autowired
private TokenService tokenService;
@Autowired
private UsuarioRepository usuarioRepository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Obtener el token del header
var authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authHeader != null) {
var token = authHeader.replace("Bearer ", "");
var nombreUsuario = tokenService.getSubject(token); // extract username
if (nombreUsuario != null) {
// Token valido
System.out.println("Va bien!!");
var usuario = usuarioRepository.findByUser(nombreUsuario);
var authentication = new UsernamePasswordAuthenticationToken(usuario, null,
usuario.getAuthorities()); // Forzamos un inicio de sesion
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(request, response);
}
}
TokenService:
public class TokenService {
@Value("${api.security.secret}")
private String apiSecret;
public String generateToken(Usuario usuario) {
try {
Algorithm algorithm = Algorithm.HMAC256(apiSecret);
return JWT.create()
.withIssuer("voll med")
.withSubject(usuario.getUser())
.withClaim("id", usuario.getId())
.withExpiresAt(generarFechaExpiracion())
.sign(algorithm);
} catch (JWTCreationException exception){
throw new RuntimeException();
}
}
public String getSubject(String token) {
if (token == null) {
throw new RuntimeException("Token is null");
}
DecodedJWT verifier = null;
try {
System.out.println("API Secret: " + apiSecret);
Algorithm algorithm = Algorithm.HMAC256(apiSecret); // validando firma
verifier = JWT.require(algorithm)
.withIssuer("voll med")
.build()
.verify(token);
verifier.getSubject();
} catch (JWTVerificationException exception) {
System.out.println(exception.toString());
}
if (verifier.getSubject() == null) {
throw new RuntimeException("Verifier invalido");
}
System.out.println("Verified Token: " + verifier.getSubject());
return verifier.getSubject();
}
private Instant generarFechaExpiracion() {
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-05:00"));
}
}
SecurityConfigurations:
public class SecurityConfigurations {
@Autowired
private SecurityFilter securityFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // Le indiamos a Spring el tipo de sesion
.and().authorizeRequests()
.requestMatchers(HttpMethod.POST, "/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}