@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); } }
public static boolean Verify(String jwt, String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
@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); } }
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); } }
/** * 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(); } }
@Path("dosomething") @POST @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") public String dosomething(@FormParam(value = "token") String token) throws IOException { String result; try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SECRECT)) .parseClaimsJws(token).getBody(); result = claims.getIssuer(); } catch (ExpiredJwtException exception) { result = "expired"; } return result; }
@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 reponse = (HttpServletResponse) servletResponse; reponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired (" + eje.getMessage() + ")"); } }
@Test(expected = ExpiredJwtException.class) public void expiredTokenCannotBeRefreshed() throws Exception { when(timeProviderMock.now()) .thenReturn(DateUtil.yesterday()); String token = createToken(); jwtTokenUtil.canTokenBeRefreshed(token, DateUtil.tomorrow()); }
private JwtAuthenticatedUser parseToken(String token) { JwtAuthenticatedUser user = null; try { Claims body = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); user = new JwtAuthenticatedUser(body.getSubject(), Arrays.asList(body.get(ROLE_KEY).toString().split(ROLE_DELIMITER))); } catch (ExpiredJwtException e) { LOGGER.warn("Error token expired", e); } return user; }
private Jws<Claims> parseToken(final String token) { if (token != null) { try { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { return null; } } return null; }
@Test(expected=ExpiredJwtException.class) public void testGenerateTokenExpired() { String token = tokenHelper.generateToken("fanjin"); Jwts.parser() .setSigningKey("mySecret") .parseClaimsJws(token) .getBody(); }
/** * 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); } }
@Test(expected = ExpiredJwtException.class) public void authenticateIfTokenExpirationFinishedTest() { final User user = createUser(); String token = tokenService.generate(user.getUsername(), user.getPassword()).getToken(); token = modifyTokenExpirationTime(token); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(authHeaderName, token); final Authentication authentication = tokenService.authenticate(request); assertNull(authentication); }
@Override public CredentialValidationResult validate(RememberMeCredential rememberMeCredential) { try { if (tokenProvider.validateToken(rememberMeCredential.getToken())) { JwtCredential credential = tokenProvider.getCredential(rememberMeCredential.getToken()); return new CredentialValidationResult(credential.getPrincipal(), credential.getAuthorities()); } // if token invalid, response with invalid result status return INVALID_RESULT; } catch (ExpiredJwtException eje) { LOGGER.log(Level.INFO, "Security exception for user {0} - {1}", new Object[]{eje.getClaims().getSubject(), eje.getMessage()}); return INVALID_RESULT; } }
@Override public Authentication authenticate(Authentication authentication) { log.debug("Authenticating: {}", authentication); try { final String token = authentication.getCredentials().toString(); final Claims claims = jwtParser.parseClaimsJws(token).getBody(); checkClaims(claims); return new JwtToken(token, claims); } catch (ExpiredJwtException | MalformedJwtException | PrematureJwtException | SignatureException | UnsupportedJwtException e) { log.warn("{}", e); throw new BadCredentialsException(e.getMessage(), e); } }
@Test public void testAuthenticateExpiredException() throws Exception { final String token = "token"; doReturn(token).when(authentication).getCredentials(); doThrow(new ExpiredJwtException(null, null, null)).when(jwtParser).parseClaimsJws(anyString()); exception.expect(BadCredentialsException.class); exception.expectCause(is(instanceOf(ExpiredJwtException.class))); jwtAuthenticationProvider.authenticate(authentication); }