io.jsonwebtoken.ExpiredJwtException Java Examples

The following examples show how to use io.jsonwebtoken.ExpiredJwtException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: _JWTFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #2
Source File: PageProvider.java    From NetworkDisk_Storage with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 跳转到主页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String homeHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "index";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
Example #3
Source File: PageProvider.java    From NetworkDisk_Storage with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 跳转到分享管理页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String shareHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "share";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
Example #4
Source File: JWTFilter.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #5
Source File: JWTFilter.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #6
Source File: JwtService.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final String keyId = claims.get(KEY_ID_CLAIM, String.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #7
Source File: JwtAuthenticationMechanism.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 6 votes vote down vote up
/**
 * To validate the JWT token e.g Signature check, JWT claims check(expiration) etc
 *
 * @param token The JWT access tokens
 * @param context
 * @return the AuthenticationStatus to notify the container
 */
private AuthenticationStatus validateToken(String token, HttpMessageContext context) {
    try {
        if (tokenProvider.validateToken(token)) {
            JwtCredential credential = tokenProvider.getCredential(token);

            //fire an @Authenticated CDI event.
            authenticatedEvent.fire(new UserInfo(credential.getPrincipal(), credential.getAuthorities()));

            return context.notifyContainerAboutLogin(credential.getPrincipal(), credential.getAuthorities());
        }
        // if token invalid, response with unauthorized status
        return context.responseUnauthorized();
    } catch (ExpiredJwtException eje) {
        LOGGER.log(Level.INFO, "Security exception for user {0} - {1}", new String[]{eje.getClaims().getSubject(), eje.getMessage()});
        return context.responseUnauthorized();
    }
}
 
Example #8
Source File: JWTFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #9
Source File: JWTFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #10
Source File: JsonWebTokenUtil.java    From sureness with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param jwt json web token
 * @return 解签实体
 * @throws ExpiredJwtException token过期
 * @throws UnsupportedJwtException 不支持的TOKEN
 * @throws MalformedJwtException 参数格式形变等异常
 * @throws SignatureException 签名异常
 * @throws IllegalArgumentException 非法参数
 */
public static Claims parseJwt(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return  Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
            .parseClaimsJws(jwt)
            .getBody();

    // 令牌ID -- claims.getId()
    // 客户标识 -- claims.getSubject()
    // 客户标识
    // 签发者 -- claims.getIssuer()
    // 签发时间 -- claims.getIssuedAt()
    // 接收方 -- claims.getAudience()
    // 访问主张-角色 -- claims.get("roles", String.class)
    // 访问主张-权限 -- claims.get("perms", String.class)
}
 
Example #11
Source File: JWTFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #12
Source File: JWTFilter.java    From gpmr with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #13
Source File: JWTFilter.java    From OpenIoE with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #14
Source File: JwtService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #15
Source File: JWTFilter.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #16
Source File: JWTFilter.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #17
Source File: JWTFilter.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #18
Source File: JWTFilter.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #19
Source File: JwtTokenTest.java    From frostmourne with MIT License 6 votes vote down vote up
@Test
public void parseTokenTest_with_token_expired_expect_expire_exception() throws InterruptedException {
    excpectedException.expect(ExpiredJwtException.class);

    String token = Jwts.builder()
            .claim("salt", "salt")
            .claim("TeamId", 1)
            .setSubject("admin")
            .setExpiration(new Date(System.currentTimeMillis() + 1000))
            .signWith(key).compact();

    Thread.sleep(2000);

    Claims claims = Jwts.parser().require("salt", "salt")
            .setSigningKey(key).parseClaimsJws(token).getBody();
}
 
Example #20
Source File: JWTFilter.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}",
            eje.getClaims().getSubject(), eje.getMessage());

        log.trace("Security exception trace: {}", eje);
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #21
Source File: TokenFilter.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
   throws IOException, ServletException {
   HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
   String token = resolveToken(httpServletRequest);
   String requestRri = httpServletRequest.getRequestURI();
   // 验证 token 是否存在
   OnlineUser onlineUser = null;
   try {
      SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
      OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
      onlineUser = onlineUserService.getOne(properties.getOnlineKey() + token);
   } catch (ExpiredJwtException e) {
      log.error(e.getMessage());
   }
   if (onlineUser != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
      Authentication authentication = tokenProvider.getAuthentication(token);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
   } else {
      log.debug("no valid JWT token found, uri: {}", requestRri);
   }
   filterChain.doFilter(servletRequest, servletResponse);
}
 
Example #22
Source File: JwtService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #23
Source File: AbstractJWTFilter.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  if (StringUtils.isEmpty(getProvidedUrl())) {
    throw new BadCredentialsException("Authentication provider URL must not be null or empty.");
  }
  if (StringUtils.isEmpty(getPublicKey())) {
    throw new BadCredentialsException("Public key for signature validation must be provisioned.");
  }

  try {
    Claims claims = Jwts
      .parser()
      .setSigningKey(parseRSAPublicKey(getPublicKey()))
      .parseClaimsJws(getJWTFromCookie(request))
      .getBody();
    String userName  = claims.getSubject();
    logger.info("USERNAME: " + userName);
    logger.info("URL = " + request.getRequestURL());
    if (StringUtils.isNotEmpty(claims.getAudience()) && !getAudiences().contains(claims.getAudience())) {
      throw new IllegalArgumentException(String.format("Audience validation failed. (Not found: %s)", claims.getAudience()));
    }
    Authentication authentication = new JWTAuthenticationToken(userName, getPublicKey(), getAuthorities(userName));
    authentication.setAuthenticated(true);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return authentication;
  } catch (ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
    logger.info("URL = " + request.getRequestURL());
    logger.warn("Error during JWT authentication: {}", e.getMessage());
    throw new BadCredentialsException(e.getMessage(), e);
  }
}
 
Example #24
Source File: JwtAuthenticationFilter.java    From SpringSecurity-JWT-Vue-Deom with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(httpServletRequest);

        // 对用 token 获取到的用户进行校验
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired,登陆已过期");
    }
}
 
Example #25
Source File: JwtTokenUtils.java    From datax-web with MIT License 5 votes vote down vote up
public static boolean isExpiration(String token) {
    try {
        return getTokenBody(token).getExpiration().before(new Date());
    } catch (ExpiredJwtException e) {
        return true;
    }
}
 
Example #26
Source File: JWTPolicy.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> validateJwt(String token, JWTPolicyBean config)
        throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {

    // check if we have to use jwk(s)
    if (urlValidator.isValid(config.getSigningKeyString())){
        if (provider == null){
            provider = getNewJwksProvider(config.getSigningKeyString());
        }

        Jwk jwk;
        try {
            jwk = provider.get(config.getKid());
            if (config.getSigningKey() == null || !(config.getSigningKey().equals(jwk.getPublicKey()))) {
                config.setSigningKey(jwk.getPublicKey());
            }
        } catch (JwkException e) {
           throw new SignatureException("JWK was not found with kid: " + config.getKid(), e);
        }
    }

    JwtParser parser = Jwts.parser()
            .setSigningKey(config.getSigningKey())
            .setAllowedClockSkewSeconds(config.getAllowedClockSkew());

    // Set all claims
    config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc
        .forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue()));

    return parser.parse(token, new ConfigCheckingJwtHandler(config));
}
 
Example #27
Source File: RawAccessJwtToken.java    From springboot-security-jwt with MIT License 5 votes vote down vote up
/**
 * Parses and validates JWT Token signature.
 * 
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 * 
 */
public Jws<Claims> parseClaims(String signingKey) {
    try {
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
        logger.error("Invalid JWT Token", ex);
        throw new BadCredentialsException("Invalid JWT token: ", ex);
    } catch (ExpiredJwtException expiredEx) {
        logger.info("JWT Token is expired", expiredEx);
        throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
    }
}
 
Example #28
Source File: JwtTokenUtilTest.java    From spring-react-boilerplate with MIT License 5 votes vote down vote up
@Test(expected = ExpiredJwtException.class)
public void expiredTokenCannotBeRefreshed() throws Exception {
    when(clockMock.now())
        .thenReturn(DateUtil.yesterday());
    String token = createToken();
    jwtTokenUtil.canTokenBeRefreshed(token, DateUtil.tomorrow());
}
 
Example #29
Source File: JWTAuthenticationFilter.java    From spring-security-jwt-csrf with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException,
        IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired");
    }
}
 
Example #30
Source File: TokenAuthenticationService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
public Authentication getAuthentication(HttpServletRequest request, HttpServletResponse response) {

        String token = request.getHeader(HEIMDALL_AUTHORIZATION_NAME);

        if (token != null && !token.isEmpty()) {
            token = token.replace(TOKEN_PREFIX, "");
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey(jwtProperty.getSecret())
                        .parseClaimsJws(token)
                        .getBody();
                String user = claims.getSubject();

                if (user != null) {
                    if (credentialStateService.isLogged(claims.getId())) {
                        User userFound = userService.findByUsername(user);
                        addAuthentication(response, user, claims.getId());
                        return new UsernamePasswordAuthenticationToken(userFound.getUserName(), userFound.getPassword(), getAuthoritiesByRoles(userFound.getRoles()));
                    }
                }
            } catch (ExpiredJwtException ex) {
                credentialStateService.logout(token);
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                try {
                    response.getWriter().write("{ \"error\": \"Token expired\" }");
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        return null;
    }