Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT token is always throwing ExpiredJwtException while parsing in java

Tags:

java

jwt

I'm trying to implement jwt based authentication to expose my REST api using spring boot, but I'm facing an issue with JWT expiration date.It is always throwing "ExpiredJwtException" even i have set expiration time. I have provided code, please let me know if someone find exact issue and solution. Thanks.

git repository https://github.com/asim-ch/JWT-authentication-with-spring-boot

Authentication Filter

public class JWTAuthenticationFilter extends OncePerRequestFilter {

   @Autowired
   TokenProvider tokenProvider;
   @Autowired
   CustomUserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, 
    HttpServletResponse httpServletResponse, FilterChain filterChain) throws 
    ServletException, IOException {
        try {
            String jwt = getJwt(httpServletRequest);
            if (jwt!=null && tokenProvider.validateJwtToken(jwt)) {
                String username = tokenProvider.getUserNameFromJwtToken(jwt);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication
                        = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("Can NOT set user authentication ", e);
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private String getJwt(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.replace("Bearer ","");
        }

        return null;
    }
}

TokenProvider class

package com.example.RestApi.Configs;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.stream.Collectors;

@Component
public class TokenProvider {


    private String jwtSecret = "something";
    Logger logger = LoggerFactory.getLogger(TokenProvider.class);
    public String generateJwtToken(Authentication authentication) throws UnsupportedEncodingException {
        Date d = new Date();
        Date expiry = new Date(d.getTime() + 720000L);
        UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

        final String authorities = userPrincipal.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));

        String token = Jwts.builder()
                .setSubject((userPrincipal.getUsername()))
                .setIssuedAt(d)
                .claim("roles", authorities)
                .setExpiration(expiry)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
        return token;
    }

    public String getUserNameFromJwtToken(String token) {
        String userName = null;
        try {
            userName = Jwts.parser()
                    .setSigningKey(jwtSecret)
                    .parseClaimsJws(token)
                    .getBody().getSubject();
        } catch (Exception e) {
            System.out.println(e);
        }
        return userName;
    }

    public boolean validateJwtToken(String authToken) throws UnsupportedEncodingException {
        try {
            Jwts.parser().setSigningKey(jwtSecret)
                    .parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.debug("signature exception"+e);
        } catch (MalformedJwtException e) {
           logger.debug("token malformed"+e);

        } catch (ExpiredJwtException e) {
           logger.debug("token expired"+e);

        } catch (UnsupportedJwtException e) {
            logger.debug("unsupported"+e);

        } catch (IllegalArgumentException e) {
            logger.debug("Illegal"+e);

        }

        return false;
    }

}

Exception Facing

In validateToken() mehode I'm always getting this exception

like image 413
Asim shahzad Avatar asked Nov 07 '22 01:11

Asim shahzad


1 Answers

Your code seems to be working fine as tested by me too.

So try of couple of things

  1. Do clean install by command line mvn clean install

  2. Remove m2 repository and then again import dependencies

  3. Try removing cache and restart IDE and system

like image 178
kj007 Avatar answered Nov 14 '22 22:11

kj007