Search in sources :

Example 1 with UnsupportedJwtException

use of io.jsonwebtoken.UnsupportedJwtException 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 2 with UnsupportedJwtException

use of io.jsonwebtoken.UnsupportedJwtException 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)

Example 3 with UnsupportedJwtException

use of io.jsonwebtoken.UnsupportedJwtException in project sonarqube by SonarSource.

the class JwtSerializer method decode.

Optional<Claims> decode(String token) {
    checkIsStarted();
    Claims claims = null;
    try {
        claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
        requireNonNull(claims.getId(), "Token id hasn't been found");
        requireNonNull(claims.getSubject(), "Token subject hasn't been found");
        requireNonNull(claims.getExpiration(), "Token expiration date hasn't been found");
        requireNonNull(claims.getIssuedAt(), "Token creation date hasn't been found");
        return Optional.of(claims);
    } catch (UnsupportedJwtException | ExpiredJwtException | SignatureException e) {
        return Optional.empty();
    } catch (Exception e) {
        throw AuthenticationException.newBuilder().setSource(Source.jwt()).setLogin(claims == null ? null : claims.getSubject()).setMessage(e.getMessage()).build();
    }
}
Also used : Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.security.SignatureException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) AuthenticationException(org.sonar.server.authentication.event.AuthenticationException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.security.SignatureException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Example 4 with UnsupportedJwtException

use of io.jsonwebtoken.UnsupportedJwtException in project nifi by apache.

the class JwtService method parseTokenFromBase64EncodedString.

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);
    }
}
Also used : Claims(io.jsonwebtoken.Claims) SigningKeyResolverAdapter(io.jsonwebtoken.SigningKeyResolverAdapter) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwsHeader(io.jsonwebtoken.JwsHeader) SignatureException(io.jsonwebtoken.SignatureException) AdministrationException(org.apache.nifi.admin.service.AdministrationException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwtException(io.jsonwebtoken.JwtException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) Key(org.apache.nifi.key.Key) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Example 5 with UnsupportedJwtException

use of io.jsonwebtoken.UnsupportedJwtException in project spring-security-jwt-csrf by alexatiks.

the class JWTAuthenticationFilter method doFilterInternal.

@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");
    }
}
Also used : ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) Authentication(org.springframework.security.core.Authentication) SignatureException(io.jsonwebtoken.SignatureException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Aggregations

ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)8 UnsupportedJwtException (io.jsonwebtoken.UnsupportedJwtException)8 Claims (io.jsonwebtoken.Claims)7 MalformedJwtException (io.jsonwebtoken.MalformedJwtException)7 SignatureException (io.jsonwebtoken.SignatureException)6 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 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 User (com.serotonin.m2m2.vo.User)1 NotFoundException (com.serotonin.m2m2.vo.exception.NotFoundException)1 Account (com.zimbra.cs.account.Account)1 AuthTokenKey (com.zimbra.cs.account.AuthTokenKey)1 CompressionCodec (io.jsonwebtoken.CompressionCodec)1 Header (io.jsonwebtoken.Header)1