Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

StackOverflowError ao fazer autenticação e autorização JWT

Estou fazendo uma API de faculdade seguindo os passos do curso, ao testar a autorização fazendo uma requisição para o controller de autenticação no Postman passando email e senha acabei recebendo o seguinte erro:

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-5.3.22.jar:5.3.22]
at jdk.proxy4/jdk.proxy4.$Proxy120.authenticate(Unknown Source) ~[na:na]
at jdk.internal.reflect.GeneratedMethodAccessor69.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-5.3.22.jar:5.3.22]
at jdk.proxy4/jdk.proxy4.$Proxy120.authenticate(Unknown Source) ~[na:na]
at jdk.internal.reflect.GeneratedMethodAccessor69.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-5.3.22.jar:5.3.22]
at jdk.proxy4/jdk.proxy4.$Proxy120.authenticate(Unknown Source) ~[na:na]
at jdk.internal.reflect.GeneratedMethodAccessor69.invoke(Unknown Source) ~[na:na]

Já procurei na internet qual o significado, porém, não achei nada que me ajudasse.

3 respostas

Aqui vai meu codigo:

@RestController
@RequestMapping("/autenticacao")
public class AutenticacaoController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;

    @PostMapping
    public ResponseEntity<TokenDto> autenticar(@RequestBody @Valid LoginForm form) {
        UsernamePasswordAuthenticationToken dadosLogin = form.converter();
        try {
            Authentication authentication = authenticationManager.authenticate(dadosLogin);
            String token = tokenService.gerarToken(authentication);
            System.out.println(token);
            return ResponseEntity.ok(new TokenDto(token, "Bearer"));
        } catch (AuthenticationException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
public class AutenticacaoTokenFilter extends OncePerRequestFilter {

private TokenService tokenService;
private PerfilRepository repository;

public AutenticacaoTokenFilter(TokenService tokenService, PerfilRepository repository) {
    this.tokenService = tokenService;
    this.repository = repository;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String token = recuperarToken(request);
    boolean valido = tokenService.isTokenValido(token);
    if(valido) {
        autenticaCliente(token);
    }

    filterChain.doFilter(request, response);
}

private void autenticaCliente(String token) {
    Long idUsuario = tokenService.getIdUsuario(token);
    Perfil usuario = repository.findById(idUsuario).get();
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

private String recuperarToken(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    if(token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
        return null;
    }
    return token.substring(7, token.length());
}
}
@EnableWebSecurity
@Configuration
public class SecurityConfigurations {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PerfilRepository repository;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(HttpMethod.POST, "/alunos").permitAll()
            .antMatchers(HttpMethod.POST, "/alunos/*").permitAll()
            .antMatchers(HttpMethod.POST, "/professores").permitAll()
            .antMatchers(HttpMethod.POST, "/professores/*").permitAll()
            .antMatchers(HttpMethod.POST, "/coordenadores").permitAll()
            .antMatchers(HttpMethod.POST, "/coordenadores/**").permitAll()
            .antMatchers(HttpMethod.POST, "/autenticacao").permitAll()
            .anyRequest().authenticated()
            .and().csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().addFilterBefore(new AutenticacaoTokenFilter(tokenService, repository),
                        UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/**.html", "/v2/api-docs", "/webjars/**", "/configuration/**",
                "/swagger-resources/**");
    }

}

Faltaram as classes PerfilRepository, TokenService e o POM.XML Só com o projeto montado e compilando dá para ajudar....

solução!

Desenvolvi elas sim, mas já resolvi o erro, estava usando o método authorizeRequests() ao invés de authorizeHttpRequests() no método filterChain da classe SecurityConfiguration.