Search in sources :

Example 1 with ExpiredJwtException

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;
}
Also used : Cookie(javax.servlet.http.Cookie) User(com.aidanwhiteley.books.domain.User) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException)

Example 2 with ExpiredJwtException

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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) Authentication(org.springframework.security.core.Authentication)

Example 3 with ExpiredJwtException

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());
}
Also used : User(com.serotonin.m2m2.vo.User) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) SignatureException(io.jsonwebtoken.SignatureException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) MissingClaimException(io.jsonwebtoken.MissingClaimException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.SignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) MissingClaimException(io.jsonwebtoken.MissingClaimException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Example 4 with ExpiredJwtException

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;
}
Also used : Cookie(javax.servlet.http.Cookie) UserDetails(org.springframework.security.core.userdetails.UserDetails) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) Date(java.util.Date)

Example 5 with ExpiredJwtException

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;
}
Also used : Account(com.zimbra.cs.account.Account) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SignatureException(io.jsonwebtoken.SignatureException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) AuthTokenKey(com.zimbra.cs.account.AuthTokenKey) Key(java.security.Key) AccountServiceException(com.zimbra.cs.account.AccountServiceException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) ServiceException(com.zimbra.common.service.ServiceException) SignatureException(io.jsonwebtoken.SignatureException) AuthFailedServiceException(com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Aggregations

ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)16 UnsupportedJwtException (io.jsonwebtoken.UnsupportedJwtException)8 Claims (io.jsonwebtoken.Claims)7 MalformedJwtException (io.jsonwebtoken.MalformedJwtException)7 SignatureException (io.jsonwebtoken.SignatureException)6 Authentication (org.springframework.security.core.Authentication)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 JwsHeader (io.jsonwebtoken.JwsHeader)3 ServiceException (com.zimbra.common.service.ServiceException)2 AccountServiceException (com.zimbra.cs.account.AccountServiceException)2 AuthFailedServiceException (com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException)2 JwtException (io.jsonwebtoken.JwtException)2 SigningKeyResolverAdapter (io.jsonwebtoken.SigningKeyResolverAdapter)2 SignatureException (io.jsonwebtoken.security.SignatureException)2 Key (java.security.Key)2 Date (java.util.Date)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 Cookie (javax.servlet.http.Cookie)2 UserDetails (org.springframework.security.core.userdetails.UserDetails)2 User (com.aidanwhiteley.books.domain.User)1