auth-api icon indicating copy to clipboard operation
auth-api copied to clipboard

Sugestão no tratamento de token inválido

Open 3vinicius opened this issue 7 months ago • 0 comments

Uma coisa interessante que da pra fazer é enviar uma response personalizada quando o token for invalido. Isso e util pra aplicações de front que precisam redirecionar o usuario.

O tratamento em SecurityFilter:

 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        var token = this.recoverToken(request);
        if(token != null){
            var login = tokenService.validateToken(token);
            UserDetails user = userRepository.findByLogin(login);

            var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }

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

Mas o metodo validateToken do TokenService não retorna null quando o token é invalido. Ele retorna string vazia:

public String validateToken(String token){
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.require(algorithm)
                .withIssuer("auth-api")
                .build()
                .verify(token)
                .getSubject();
    } catch (JWTVerificationException exception){
        return "";
    }
}

Sugestão

Uma possivel forma de resolver isso seria inverter a logica e tratar direto se o login ta vazio:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    var token = this.recoverToken(request);
    var login = tokenService.validateToken(token);
    if(!login.isEmpty()){
        UserDetails user = userRepository.findByLogin(login);

        var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Token inválido");
        return;
    }
    filterChain.doFilter(request, response);
}

3vinicius avatar May 23 '25 20:05 3vinicius