在Java

时间:2018-10-03 16:15:56

标签: java jwt

我正在尝试使用Spring Boot实施基于jwt的身份验证以公开我的REST api,但是我遇到了JWT到期日期的问题。即使我设置了到期时间,它始终会抛出“ ExpiredJwtException”。我已经提供了代码,如果有人找到确切的问题和解决方案,请告诉我。谢谢。

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

身份验证过滤器

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类

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;
    }

}

面对异常

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

2 个答案:

答案 0 :(得分:0)

您的代码似乎也可以通过我的测试正常工作。

那么尝试几件事

  1. 通过命令行mvn clean install

  2. 进行全新安装
  3. 删除m2存储库,然后再次导入依赖项

  4. 尝试删除缓存并重新启动IDE和系统

答案 1 :(得分:0)

我有同样的问题。尝试@ kj007答案。但是它对我不起作用。

就我而言,这是一个Insomnia错误。重新启动后,一切正常。我认为它是在发送旧令牌。