com.nimbusds.jose.JWSVerifier Java Examples
The following examples show how to use
com.nimbusds.jose.JWSVerifier.
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 |
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: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void validToken() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000)); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertTrue("Must be valid", signed.verify(verifier)); }
Example #3
Source File: JWTTokenTest.java From knox with Apache License 2.0 | 6 votes |
@Test public void testTokenSignature() throws Exception { String[] claims = new String[4]; claims[0] = "KNOXSSO"; claims[1] = "[email protected]"; claims[2] = "https://login.example.com"; claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300); JWT token = new JWTToken("RS256", claims); assertEquals("KNOXSSO", token.getIssuer()); assertEquals("[email protected]", token.getSubject()); assertEquals("https://login.example.com", token.getAudience()); // Sign the token JWSSigner signer = new RSASSASigner(privateKey); token.sign(signer); assertTrue(token.getSignaturePayload().length > 0); // Verify the signature JWSVerifier verifier = new RSASSAVerifier(publicKey); assertTrue(token.verify(verifier)); }
Example #4
Source File: JWTTokenTest.java From knox with Apache License 2.0 | 6 votes |
@Test public void testTokenSignatureRS512() throws Exception { String[] claims = new String[4]; claims[0] = "KNOXSSO"; claims[1] = "[email protected]"; claims[2] = "https://login.example.com"; claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300); JWT token = new JWTToken(JWSAlgorithm.RS512.getName(), claims); assertEquals("KNOXSSO", token.getIssuer()); assertEquals("[email protected]", token.getSubject()); assertEquals("https://login.example.com", token.getAudience()); assertTrue(token.getHeader().contains(JWSAlgorithm.RS512.getName())); // Sign the token JWSSigner signer = new RSASSASigner(privateKey); token.sign(signer); assertTrue(token.getSignaturePayload().length > 0); // Verify the signature JWSVerifier verifier = new RSASSAVerifier(publicKey); assertTrue(token.verify(verifier)); }
Example #5
Source File: DefaultTokenAuthorityService.java From knox with Apache License 2.0 | 6 votes |
@Override public boolean verifyToken(JWT token, RSAPublicKey publicKey) throws TokenServiceException { boolean rc; PublicKey key; try { if (publicKey == null) { key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias()).getPublicKey(); } else { key = publicKey; } JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key); // TODO: interrogate the token for issuer claim in order to determine the public key to use for verification // consider jwk for specifying the key too rc = token.verify(verifier); } catch (KeyStoreException | KeystoreServiceException e) { throw new TokenServiceException("Cannot verify token.", e); } return rc; }
Example #6
Source File: GatewayUtils.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Verify the JWT token signature. * * @param jwt SignedJwt Token * @param publicKey public certificate * @return whether the signature is verified or or not * @throws APISecurityException in case of signature verification failure */ public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) throws APISecurityException { JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm(); if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) || JWSAlgorithm.RS384.equals(algorithm))) { try { JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey); return jwt.verify(jwsVerifier); } catch (JOSEException e) { log.error("Error while verifying JWT signature"); throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e); } } else { log.error("Public key is not a RSA"); throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE); } }
Example #7
Source File: JWTAuthenticationHandler.java From registry with Apache License 2.0 | 6 votes |
/** * Verify the signature of the JWT token in this method. This method depends * on the public key that was established during init based upon the * provisioned public key. Override this method in subclasses in order to * customize the signature verification behavior. * * @param jwtToken the token that contains the signature to be validated * @return valid true if signature verifies successfully; false otherwise */ protected boolean validateSignature(SignedJWT jwtToken) { boolean valid = false; if (JWSObject.State.SIGNED == jwtToken.getState()) { LOG.debug("JWT token is in a SIGNED state"); if (jwtToken.getSignature() != null) { LOG.debug("JWT token signature is not null"); try { JWSVerifier verifier = new RSASSAVerifier(publicKey); if (jwtToken.verify(verifier)) { valid = true; LOG.debug("JWT token has been successfully verified"); } else { LOG.warn("JWT signature verification failed."); } } catch (JOSEException je) { LOG.warn("Error while validating signature", je); } } } return valid; }
Example #8
Source File: KnoxJwtRealm.java From zeppelin with Apache License 2.0 | 6 votes |
protected boolean validateSignature(SignedJWT jwtToken) { boolean valid = false; if (JWSObject.State.SIGNED == jwtToken.getState()) { if (jwtToken.getSignature() != null) { try { RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath); JWSVerifier verifier = new RSASSAVerifier(publicKey); if (verifier != null && jwtToken.verify(verifier)) { valid = true; } } catch (Exception e) { LOGGER.info("Exception in validateSignature", e); } } } return valid; }
Example #9
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static boolean verifyTokenRSA( PublicKey pKey, String token ) { try { Payload pl = new Payload( token ); JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl ); JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey ); return jwsObject.verify( verifier ); } catch ( JOSEException e ) { LOG.warn( "Error verifying RSA token", e.getMessage() ); return false; } }
Example #10
Source File: JWTSecurityInterceptor.java From msf4j with Apache License 2.0 | 6 votes |
private boolean verifySignature(String jwt) { try { SignedJWT signedJWT = SignedJWT.parse(jwt); if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) { JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS)); return signedJWT.verify(verifier); } else { log.info("Token has expired"); } } catch (ParseException | IOException | KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) { log.error("Error occurred while JWT signature verification. JWT=" + jwt, e); } return false; }
Example #11
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 6 votes |
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 #12
Source File: JWTUtil.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Verify the JWT token signature. * * @param jwt SignedJwt Token * @param publicKey public certificate * @return whether the signature is verified or or not */ public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) { JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm(); if ((JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) || JWSAlgorithm.RS384.equals(algorithm))) { try { JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey); return jwt.verify(jwsVerifier); } catch (JOSEException e) { log.error("Error while verifying JWT signature", e); return false; } } else { log.error("Public key is not a RSA"); return false; } }
Example #13
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void invalidTokenNotBeforeTime() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000)); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertFalse("Must be invalid", signed.verify(verifier)); }
Example #14
Source File: JWSServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
private JWSVerifier from(ECKey ecKey) { try { Curve curve = Curve.parse(ecKey.getCrv()); if(curve.getStdName()==null) { throw new IllegalArgumentException("Unknown EC Curve: "+ecKey.getCrv()); } AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec(curve.getStdName())); ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class); byte[] x = Base64.getUrlDecoder().decode(ecKey.getX()); byte[] y = Base64.getUrlDecoder().decode(ecKey.getY()); ECPoint ecPoint = new ECPoint(new BigInteger(1,x), new BigInteger(1,y)); ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameters); ECPublicKey ecPublicKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(ecPublicKeySpec); return new ECDSAVerifier(ecPublicKey); } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException | JOSEException ex) { LOGGER.error("Unable to build Verifier from Elliptic Curve (EC) key",ex); throw new IllegalArgumentException("Signature is using and unknown/not managed key"); } }
Example #15
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void invalidTokenExpirationTime() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date()); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertFalse("Must be invalid", signed.verify(verifier)); }
Example #16
Source File: JWSServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public JWSVerifier verifier(JWK jwk) { try { switch (KeyType.parse(jwk.getKty())) { case RSA: return from((RSAKey) jwk); case EC: return from((ECKey) jwk); case OCT: return from((OCTKey) jwk); case OKP: return from((OKPKey) jwk); default: throw new IllegalArgumentException("Signature is using and unknown/not managed algorithm"); } }catch (IllegalArgumentException e) { throw new IllegalArgumentException("Signature is using and unknown/not managed algorithm"); } }
Example #17
Source File: OAuthHandler.java From attic-stratos with Apache License 2.0 | 6 votes |
private String extractAppIdFromIdToken(String token) { String appId = null; KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); try { keyStoreManager.getDefaultPrimaryCertificate(); JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey()); SignedJWT jwsObject = SignedJWT.parse(token); if (jwsObject.verify(verifier)) { appId = jwsObject.getJWTClaimsSet().getStringClaim("appId"); } } catch (Exception e) { String message = "Could not extract application id from id token"; log.error(message, e); } return appId; }
Example #18
Source File: TokenProviderUtility.java From Insights with Apache License 2.0 | 6 votes |
/** * 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 #19
Source File: SecurityUtils.java From para with Apache License 2.0 | 6 votes |
/** * 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 #20
Source File: JwtLoginService.java From cruise-control with BSD 2-Clause "Simplified" License | 5 votes |
private boolean validateSignature(SignedJWT jwtToken) { if (JWSObject.State.SIGNED != jwtToken.getState() || jwtToken.getSignature() == null) { return false; } JWSVerifier verifier = new RSASSAVerifier(_publicKey); try { return jwtToken.verify(verifier); } catch (JOSEException e) { JWT_LOGGER.warn("Couldn't verify the signature of a token", e); return false; } }
Example #21
Source File: KnoxSSOAuthenticationFilter.java From metron with Apache License 2.0 | 5 votes |
/** * Verify the signature of the JWT token in this method. This method depends on * the public key that was established during init based upon the provisioned * public key. Override this method in subclasses in order to customize the * signature verification behavior. * * @param jwtToken The token that contains the signature to be validated. * @return valid true if signature verifies successfully; false otherwise */ protected boolean validateSignature(SignedJWT jwtToken) { // Verify the token signature algorithm was as expected String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName(); if (!receivedSigAlg.equals(JWSAlgorithm.RS256.getName())) { return false; } // Verify the token has been properly signed if (JWSObject.State.SIGNED == jwtToken.getState()) { LOG.debug("SSO token is in a SIGNED state"); if (jwtToken.getSignature() != null) { LOG.debug("SSO token signature is not null"); try { JWSVerifier verifier = getRSASSAVerifier(); if (jwtToken.verify(verifier)) { LOG.debug("SSO token has been successfully verified"); return true; } else { LOG.warn("SSO signature verification failed. Please check the public key."); } } catch (Exception e) { LOG.warn("Error while validating signature", e); } } } return false; }
Example #22
Source File: JwtParserCallout.java From iloveapis2015-jwt-jwe-jws with Apache License 2.0 | 5 votes |
private JWSVerifier getVerifier(String alg, MessageContext msgCtxt) throws Exception { if (alg.equals("HS256")) { return getMacVerifier(msgCtxt); } else if (alg.equals("RS256")) { return getRsaVerifier(msgCtxt); } throw new IllegalStateException("algorithm is unsupported: " + alg); }
Example #23
Source File: RangerSSOAuthenticationFilter.java From ranger with Apache License 2.0 | 5 votes |
/** * Verify the signature of the JWT token in this method. This method depends * on the public key that was established during init based upon the * provisioned public key. Override this method in subclasses in order to * customize the signature verification behavior. * * @param jwtToken * the token that contains the signature to be validated * @return valid true if signature verifies successfully; false otherwise */ protected boolean validateSignature(SignedJWT jwtToken) { boolean valid = false; if (JWSObject.State.SIGNED == jwtToken.getState()) { if (LOG.isDebugEnabled()) { LOG.debug("SSO token is in a SIGNED state"); } if (jwtToken.getSignature() != null) { if (LOG.isDebugEnabled()) { LOG.debug("SSO token signature is not null"); } try { JWSVerifier verifier = new RSASSAVerifier(publicKey); if (jwtToken.verify(verifier)) { valid = true; if (LOG.isDebugEnabled()) { LOG.debug("SSO token has been successfully verified"); } } else { LOG.warn("SSO signature verification failed.Please check the public key"); } } catch (JOSEException je) { LOG.warn("Error while validating signature", je); }catch(Exception e){ LOG.warn("Error while validating signature", e); } } // Now check that the signature algorithm was as expected if (valid) { String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName(); if (!receivedSigAlg.equals(jwtProperties.getExpectedSigAlg())) { valid = false; } } } return valid; }
Example #24
Source File: JWTToken.java From knox with Apache License 2.0 | 5 votes |
@Override public boolean verify(JWSVerifier verifier) { boolean rc = false; try { rc = jwt.verify(verifier); } catch (JOSEException e) { log.unableToVerifyToken(e); } return rc; }
Example #25
Source File: DefaultJwtSigningAndValidationService.java From MaxKey with Apache License 2.0 | 5 votes |
@Override public boolean validateSignature(SignedJWT jwt) { for (JWSVerifier verifier : verifiers.values()) { try { if (jwt.verify(verifier)) { return true; } } catch (JOSEException e) { logger.error("Failed to validate signature, error was: ", e); } } return false; }
Example #26
Source File: Jwt.java From JWT with MIT License | 5 votes |
/** * 校验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 #27
Source File: TokenHelperImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public boolean verify( String secret ) { try { JWSVerifier verifier = new MACVerifier( secret ); return this.signedJWT.verify( verifier ); } catch ( JOSEException e ) { return false; } }
Example #28
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 5 votes |
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 #29
Source File: JWSServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private JWSVerifier from(OKPKey okpKey) { try { Curve curve = Curve.parse(okpKey.getCrv()); if(curve.getStdName()==null) { throw new IllegalArgumentException("Unknown OKP Curve: "+okpKey.getCrv()); } OctetKeyPair jwk = new OctetKeyPair.Builder(curve,new Base64URL(okpKey.getX())).build(); return new Ed25519Verifier(jwk); } catch (JOSEException ex) { LOGGER.error("Unable to build Verifier from Message Authentication Code (MAC) key",ex); throw new IllegalArgumentException("Signature is using and unknown/not managed key"); } }
Example #30
Source File: JWSServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
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"); } }