com.nimbusds.jose.crypto.MACVerifier Java Examples

The following examples show how to use com.nimbusds.jose.crypto.MACVerifier. 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: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
public boolean isValidJWToken(String jwt) {
	try {
		String secret = Config.getConfigParam("app_secret_key", "");
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			SignedJWT sjwt = SignedJWT.parse(jwt);
			if (sjwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = sjwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				String jti = claims.getJWTID();
				boolean expired = expirationTime != null && expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);
				boolean jtiRevoked = isApiKeyRevoked(jti, expired);
				return !(expired || notYetValid || jtiRevoked);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example #2
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * used to delete token from cache
 * 
 * @param csrfauthToken
 * @return
 * @throws Exception
 */
public boolean deleteToken(String csrfauthToken) throws Exception {
	Boolean isTokenRemoved = Boolean.FALSE;
	try {
		SignedJWT signedJWT = SignedJWT.parse(csrfauthToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		Boolean isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String key = TokenProviderUtility.tokenCache.get(id);
		if (key != null && isVerify) {
			TokenProviderUtility.tokenCache.remove(id);
			isTokenRemoved = Boolean.TRUE;
		}
	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while deleting token {}", e.getMessage());
	}
	return isTokenRemoved;
}
 
Example #3
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifySignature( String token, String sharedKey )
{
    boolean verifiedSignature = false;

    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );
        verifiedSignature = jwsObject.verify( verifier );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
    }

    return verifiedSignature;
}
 
Example #4
Source File: ReferenceSerializer.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
public IdentityReference deserialize(String token) throws Exception {
    String sToken = new String(Base64.getDecoder().decode(token));

    // Parse the JWE string
    JWEObject jweObject = JWEObject.parse(sToken);

    // Decrypt with shared key
    jweObject.decrypt(new DirectDecrypter(secretKey.getEncoded()));

    // Extract payload
    SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();

    // Check the HMAC
    signedJWT.verify(new MACVerifier(secretKey.getEncoded()));

    // Retrieve the JWT claims
    return new IdentityReference(signedJWT.getJWTClaimsSet().getIssuer(), signedJWT.getJWTClaimsSet().getSubject());
}
 
Example #5
Source File: SecurityUtils.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Validates a JWT token.
 * @param secret secret used for generating the token
 * @param jwt token to validate
 * @return true if token is valid
 */
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
	try {
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			if (jwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = jwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				boolean expired = expirationTime == null || expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);

				return !(expired || notYetValid);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example #6
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Used to verify received token with cached token
 * 
 * @param token
 * @return
 * @throws AuthorizationServiceException
 * @throws AuthenticationCredentialsNotFoundException
 * @throws AccountExpiredException
 * @throws InsightsCustomException
 */
public boolean verifyToken(String token) throws AuthorizationServiceException,
		AuthenticationCredentialsNotFoundException, AccountExpiredException, InsightsCustomException {
	boolean isVerify = Boolean.FALSE;
	boolean isTokenExistsInCache = Boolean.FALSE;
	boolean validateTokenDate = Boolean.FALSE;
	//log.debug(" In verifyToken ");
	try {
		String authToken = ValidationUtils.cleanXSS(token);
		if (authToken == null || authToken.isEmpty()) {
			log.error("authToken is null or empty");
			throw new InsightsCustomException("authToken is null or empty");
		}

		// parse the JWS and verify its HMAC
		SignedJWT signedJWT = SignedJWT.parse(authToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String tokenValueFromCache = null;
		if (TokenProviderUtility.tokenCache != null) {
			tokenValueFromCache = TokenProviderUtility.tokenCache.get(id);
		} else {
			log.error("cache is not initilize properly");
		}

		if (tokenValueFromCache == null) {
			log.debug("No token found in cache");
		} else if (tokenValueFromCache.equalsIgnoreCase(authToken)) {
			//log.debug("Token value matched in cache === ");
			isTokenExistsInCache = Boolean.TRUE;
		} else {
			log.error("Token value not matched in cache=== ");
		}

		//log.debug("alice  after " + signedJWT.getJWTClaimsSet().getSubject());
		//log.debug("cognizant.com  " + signedJWT.getJWTClaimsSet().getIssuer());
		//log.debug("Exceperation Time after  " + signedJWT.getJWTClaimsSet().getExpirationTime());
		log.debug("Check date of token with current date {} ",
				new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime()));//after
		validateTokenDate = new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime());//after

	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while validating token {} ", e.getMessage());
		isVerify = Boolean.FALSE;
		throw new InsightsCustomException("Exception while varifing token ==== " + e.getMessage());
	}

	if (!isVerify) {
		log.debug("Token signuture not match ");
		isVerify = Boolean.FALSE;
		throw new AuthorizationServiceException("Token signuture not match");
	} else if (!isTokenExistsInCache) {
		log.error("Token Not matched ");
		isVerify = Boolean.FALSE;
		throw new AuthenticationCredentialsNotFoundException("Token not found in cache");
	} else if (!validateTokenDate) {
		isVerify = Boolean.FALSE;
		throw new AccountExpiredException("Token Expire");
	} else {
		log.debug("Token verified sucessfully ==== ");
		isVerify = Boolean.TRUE;
	}

	log.debug(" is Token Verify  ====  {} ", isVerify);

	return isVerify;
}
 
Example #7
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private JWSVerifier from(OCTKey octKey) {
    try {
        OctetSequenceKey jwk = new OctetSequenceKey.Builder(new Base64URL(octKey.getK())).build();
        return new MACVerifier(jwk);
    }
    catch (JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Edwards Curve (OKP) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #8
Source File: CookieCsrfSignedTokenRepository.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    // Add padding if necessary
    // HS256 need, at least, 32 ascii characters
    secret = org.apache.commons.lang3.StringUtils.leftPad(secret, 32, '0');

    signer = new MACSigner(secret);
    verifier = new MACVerifier(secret);
}
 
Example #9
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignatureAndDate( String token, String sharedKey ) throws SystemSecurityException
{
    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );

        if ( jwsObject.verify( verifier ) )
        {
            long date = getDate( jwsObject );

            if ( date == 0 || System.currentTimeMillis() <= date )
            {
                return true;
            }
            else
            {
                throw new IdentityExpiredException();
            }
        }
        else
        {
            throw new InvalidLoginException();
        }
    }
    catch ( JOSEException | ParseException ex )
    {
        LOG.warn( ex.getMessage() );

        throw new InvalidLoginException();
    }
}
 
Example #10
Source File: TokenHelperImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify( String secret )
{
    try
    {
        JWSVerifier verifier = new MACVerifier( secret );
        return this.signedJWT.verify( verifier );
    }
    catch ( JOSEException e )
    {
        return false;
    }
}
 
Example #11
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
    * 校验token是否合法,返回Map集合,集合中主要包含    state状态码   data鉴权成功后从token中提取的数据
    * 该方法在过滤器中调用,每次请求API时都校验
    * @param token
    * @return  Map<String, Object>
    */
public static Map<String, Object> validToken(String token) {
	Map<String, Object> resultMap = new HashMap<String, Object>();
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		Payload payload = jwsObject.getPayload();
		JWSVerifier verifier = new MACVerifier(SECRET);

		if (jwsObject.verify(verifier)) {
			JSONObject jsonOBj = payload.toJSONObject();
			// token校验成功(此时没有校验是否过期)
			resultMap.put("state", TokenState.VALID.toString());
			// 若payload包含ext字段,则校验是否过期
			if (jsonOBj.containsKey("ext")) {
				long extTime = Long.valueOf(jsonOBj.get("ext").toString());
				long curTime = new Date().getTime();
				// 过期了
				if (curTime > extTime) {
					resultMap.clear();
					resultMap.put("state", TokenState.EXPIRED.toString());
				}
			}
			resultMap.put("data", jsonOBj);

		} else {
			// 校验失败
			resultMap.put("state", TokenState.INVALID.toString());
		}

	} catch (Exception e) {
		//e.printStackTrace();
		// token格式不合法导致的异常
		resultMap.clear();
		resultMap.put("state", TokenState.INVALID.toString());
	}
	return resultMap;
}
 
Example #12
Source File: CookieCsrfSignedTokenRepository.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    // Add padding if necessary
    // HS256 need, at least, 32 ascii characters
    secret = org.apache.commons.lang3.StringUtils.leftPad(secret, 32, '0');

    signer = new MACSigner(secret);
    verifier = new MACVerifier(secret);
}
 
Example #13
Source File: AuthUtils.java    From blog with MIT License 5 votes vote down vote up
public static ReadOnlyJWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {
  SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));
  if (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) {
    return signedJWT.getJWTClaimsSet();
  } else {
    throw new JOSEException("Signature verification failed");
  }
}
 
Example #14
Source File: DefaultConsentReferencePolicy.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("PMD")
private ConsentReference verifyParseJWT(String encryptedConsentId, String authorizationId, String cookieString, boolean strict) {
    Date refTime = new Date();
    try {
        SignedJWT jwt = SignedJWT.parse(cookieString);
        JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();

        // Validate xsrf
        Object authorizationIdClaim = jwtClaimsSet.getClaim(AUTH_ID_JWT_CLAIM_NAME);
        if (strict && authorizationIdClaim == null) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Missing claim %s for jwt with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        if (authorizationIdClaim != null && !StringUtils.equalsIgnoreCase(authorizationIdClaim.toString(), authorizationId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        Object encryptedConsentIdClaim = jwtClaimsSet.getClaim(ENC_CONSENT_ID_JWT_CLAIM_NAME);
        if (encryptedConsentIdClaim == null || !StringUtils.equalsIgnoreCase(encryptedConsentIdClaim.toString(), encryptedConsentId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", ENC_CONSENT_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        JWSHeader header = jwt.getHeader();
        // CHeck algorithm
        if (!JWSAlgorithm.HS256.equals(header.getAlgorithm())) {
            throw invalidConsent(String.format("Wrong jws algo for token with subject : %s", jwtClaimsSet.getSubject()));
        }

        // CHeck expiration
        if (jwtClaimsSet.getExpirationTime() == null || jwtClaimsSet.getExpirationTime().before(refTime)) {
            throw invalidConsent(String.format(
                "Token with subject %s is expired at %s and reference time is %s : ", jwtClaimsSet.getSubject(),
                jwtClaimsSet.getExpirationTime(), refTime));
        }

        // check signature.
        boolean verified = jwt.verify(new MACVerifier(hmacSecret));
        if (!verified) {
            throw invalidConsent(String.format("Could not verify signature of token with subject %s: ", jwtClaimsSet.getSubject()));
        }

        return consentReference(encryptedConsentId, authorizationId, jwtClaimsSet);

    } catch (ParseException | JOSEException e) {
        // If we can not parse the token, we log the error and return false.
        throw invalidConsent(e.getMessage());
    }
}
 
Example #15
Source File: JWT.java    From api-server-seed with Apache License 2.0 4 votes vote down vote up
public static boolean verify(JWSObject jwsObject) throws JOSEException {
	JWSVerifier verifier = new MACVerifier(JWT.SHARED_SECRET);
	return jwsObject.verify(verifier);
}