3
respostas

No meu projeto retirei tudo que estava deprecated mas continua forbbiden

No meu projeto está tudo atualizado mas o metodo authenticate continua forbbiden e n consigo fazer login

@Configuration
public class SecurityConfiguration{

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http.csrf().disable()
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and().authorizeHttpRequests()
      .requestMatchers(HttpMethod.POST, "/authenticate").permitAll()
      .anyRequest().authenticated()
      .and().build();
  }

  @Bean
  public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers("/public", "/authenticate", "/user");
  }

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

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

}
@Component
public class SecurityFilter extends OncePerRequestFilter {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private UserDetailsService jwtUserDetailsService;

  @Autowired
  private JwtTokenUtil jwtTokenUtil;

  @Value("${jwt.http.request.header}")
  private String tokenHeader;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException{
    var token = recuperaToken(request);
    var tokenSubject = jwtTokenUtil.getSubject(token);
    System.out.println(tokenSubject);
    chain.doFilter(request, response);
  }

  private String recuperaToken(HttpServletRequest request) {
    var authorizationHeader = request.getHeader("Authorization");
    if(authorizationHeader == null){
      throw new RuntimeException("Token is not present");
    }
    return authorizationHeader.replace("Bearer ", "");
  }

}
3 respostas

Bom dia Breno,

Poderia enviar o log do terminal com a mensagem de erro?

Algumas coisas a verificar no cod que você mandou, na classe SecurityConfiguration deveria ter a anotação @EnableWebSecurity

@Configuration
@EnableWebSecurity
public class SecurityConfiguration

na classe filterChain esta autozidando o caminho /authenticate, não deveria ser /login? na classe AutentitcacaoController foi mapeado /authenticate mesmo?

.requestMatchers(HttpMethod.POST, "/authenticate").permitAll()

java.lang.RuntimeException: Token is not present
        at com.breallencs.mytripyapi.core.config.SecurityFilter.recuperaToken(SecurityFilter.java:49) ~[classes/:na]
        at com.breallencs.mytripyapi.core.config.SecurityFilter.doFilterInternal(SecurityFilter.java:40) ~[classes/:na]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.3.jar:6.0.3]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
        at org.springframework.security.web.ObservationFilterChainDecorator$FilterObservation$SimpleFilterObservation.lambda$wrap$1(ObservationFilterChainDecorator.java:399) ~[spring-security-web-6.0.1.jar:6.0.1]

Esse é o log que recebo quando tento acesssar /authenticate é essa url mesmo que desejo acessar

Oi Breno,

Pelo que vi na tua logica, você esta tentando pegar um token no login, mas não tem como isso porque no login tu não manda o token. Tenta assim.

private String recuperarToken(HttpServletRequest request) {
        var authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null) {
            return authorizationHeader.replace("Bearer ", "");
        }

        return null;
    }
@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        var tokenJWT = recuperarToken(request);

        if (tokenJWT != null) {
            var subject = tokenService.getSubject(tokenJWT);
            var usuario = repository.findByLogin(subject);

            var authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

verifica se a tua classe controller esta assim.

@PostMapping
    public ResponseEntity efetuarLogin(@RequestBody @Valid DadosAutenticacao dados) {
        var authenticationToken = new UsernamePasswordAuthenticationToken(dados.login(), dados.senha());
        var authentication = manager.authenticate(authenticationToken);

        var tokenJWT = tokenService.gerarToken((Usuario) authentication.getPrincipal());

        return ResponseEntity.ok(new DadosTokenJWT(tokenJWT));
    }