use of io.jsonwebtoken.ExpiredJwtException in project books by aidanwhiteley.
the class JwtAuthenticationService method readAndValidateAuthenticationData.
public JwtAuthentication readAndValidateAuthenticationData(HttpServletRequest request, HttpServletResponse response) {
LOGGER.debug("Running JwtAuthenticationService - readAndValidateAuthenticationData");
JwtAuthentication auth = null;
boolean oauthCookieFound = false;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
LOGGER.debug("Found cookie named: {}", cookie.getName());
switch(cookie.getName()) {
case JWT_COOKIE_NAME:
String token = cookie.getValue();
if (token == null || token.trim().isEmpty()) {
LOGGER.warn("JWT cookie found but was empty - we will look to remove this later");
} else {
try {
User user = jwtUtils.getUserFromToken(token);
auth = new JwtAuthentication(user);
// If we got to here with no exceptions thrown
// then we can assume we have a valid token
auth.setAuthenticated(true);
LOGGER.debug("JWT found and validated - setting authentication true");
} catch (ExpiredJwtException eje) {
expireJwtCookie(response);
LOGGER.info("JWT expired so cookie deleted");
} catch (RuntimeException re) {
expireJwtCookie(response);
LOGGER.error("Error validating jwt token: {}. So cookie deleted", re.getMessage(), re);
}
}
break;
case JSESSIONID_COOKIE_NAME:
// With the use of Spring Security Oauth2 and the custom
// HttpCookieOAuth2AuthorizationRequestRepository there
// should be no JSESSIONIDs being writtem
LOGGER.warn("Unexpectedly found a JSESSIONID based cookie - killing it!");
expireJsessionIdCookie(response);
break;
case HttpCookieOAuth2AuthorizationRequestRepository.COOKIE_NAME:
oauthCookieFound = true;
break;
default:
LOGGER.debug("Found cookie named {}", cookie.getName());
}
}
}
checkForRedundantOauthCookie(auth, oauthCookieFound, response);
return auth;
}
use of io.jsonwebtoken.ExpiredJwtException in project jhipster-registry by jhipster.
the class JWTFilter method doFilter.
@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);
}
}
use of io.jsonwebtoken.ExpiredJwtException in project ma-core-public by infiniteautomation.
the class MangoTokenAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!(authentication instanceof BearerAuthenticationToken)) {
return null;
}
String bearerToken = (String) authentication.getCredentials();
User user;
Jws<Claims> jws;
try {
jws = tokenAuthenticationService.parse(bearerToken);
user = tokenAuthenticationService.verify(jws);
} catch (ExpiredJwtException e) {
throw new CredentialsExpiredException(e.getMessage(), e);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
// assume that this is not a JWT, allow the next AuthenticationProvider to process it
return null;
} catch (SignatureException | MissingClaimException | IncorrectClaimException e) {
throw new BadCredentialsException(e.getMessage(), e);
} catch (NotFoundException e) {
throw new BadCredentialsException("Invalid username", e);
} catch (Exception e) {
throw new InternalAuthenticationServiceException(e.getMessage(), e);
}
userDetailsChecker.check(user);
if (log.isDebugEnabled()) {
log.debug("Successfully authenticated user using JWT token, header: " + jws.getHeader() + ", body: " + jws.getBody());
}
return new PreAuthenticatedAuthenticationToken(user, bearerToken, user.getAuthorities());
}
use of io.jsonwebtoken.ExpiredJwtException in project pinpoint by naver.
the class BasicLoginService method getUserDetails.
public UserDetails getUserDetails(Cookie[] cookies) {
if (cookies == null) {
return null;
}
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (BasicLoginConstants.PINPOINT_JWT_COOKIE_NAME.equals(name)) {
String pinpointJwtToken = cookie.getValue();
try {
Date expirationDate = jwtService.getExpirationDate(pinpointJwtToken);
if (expirationDate.getTime() > System.currentTimeMillis()) {
String userId = jwtService.getUserId(pinpointJwtToken);
UserDetails userDetails = pinpointMemoryUserDetailsService.loadUserByUsername(String.valueOf(userId));
if (userDetails != null) {
return userDetails;
}
} else {
logger.warn("This token already expired.");
}
} catch (ExpiredJwtException e) {
logger.warn("This token already expired. message:{}", e.getMessage(), e);
}
}
}
return null;
}
use of io.jsonwebtoken.ExpiredJwtException in project zm-mailbox by Zimbra.
the class JWTUtil method validateJWT.
/**
* validate the jwt and return claims if jwt is valid.
* @param jwt
* @param salts
* @return
* @throws ServiceException
*/
public static Claims validateJWT(String jwt, String salts) throws ServiceException {
if (StringUtil.isNullOrEmpty(jwt) || StringUtil.isNullOrEmpty(salts)) {
ZimbraLog.account.debug("Invalid JWT or no salt value");
throw AuthFailedServiceException.AUTH_FAILED("Invalid JWT or no salt value");
}
String jti = getJTI(jwt);
String salt = getJWTSalt(jwt, jti, salts);
if (salt == null) {
ZimbraLog.account.debug("jwt specific salt not found");
throw AuthFailedServiceException.AUTH_FAILED("no salt value");
}
byte[] finalKey = Bytes.concat(getOriginalKey(jwt), salt.getBytes());
Key key = new SecretKeySpec(finalKey, SignatureAlgorithm.HS512.getJcaName());
Claims claims = null;
try {
claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
Account acct = Provisioning.getInstance().get(AccountBy.id, claims.getSubject());
if (acct == null) {
throw AccountServiceException.NO_SUCH_ACCOUNT(claims.getSubject());
}
if (acct.hasInvalidJWTokens(jti)) {
ZimbraLog.security.debug("jwt: %s is no longer valid, has been invalidated on logout", jti);
throw AuthFailedServiceException.AUTH_FAILED("Token has been invalidated");
}
} catch (ExpiredJwtException eje) {
ZimbraLog.account.debug("jwt expired", eje);
throw ServiceException.AUTH_EXPIRED(eje.getMessage());
} catch (SignatureException se) {
ZimbraLog.account.debug("jwt signature exception", se);
throw AuthFailedServiceException.AUTH_FAILED("Signature verification failed", se);
} catch (UnsupportedJwtException uje) {
ZimbraLog.account.debug("unsupported jwt exception", uje);
throw AuthFailedServiceException.AUTH_FAILED("Unsupported JWT received", uje);
} catch (MalformedJwtException mje) {
ZimbraLog.account.debug("malformed jwt exception", mje);
throw AuthFailedServiceException.AUTH_FAILED("Malformed JWT received", mje);
} catch (Exception e) {
ZimbraLog.account.debug("exception during jwt validation", e);
throw AuthFailedServiceException.AUTH_FAILED("Exception thrown while validating JWT", e);
}
return claims;
}
Aggregations