use of com.nimbusds.jose.JWSVerifier in project DSpace by DSpace.
the class JWTTokenHandler method isValidToken.
/**
* Determine if current JWT is valid for the given EPerson object.
* To be valid, current JWT *must* have been signed by the EPerson and not be expired.
* If EPerson is null or does not have a known active session, false is returned immediately.
* @param request current request
* @param signedJWT current signed JWT
* @param jwtClaimsSet claims set of current JWT
* @param ePerson EPerson parsed from current signed JWT
* @return true if valid, false otherwise
* @throws JOSEException
*/
protected boolean isValidToken(HttpServletRequest request, SignedJWT signedJWT, JWTClaimsSet jwtClaimsSet, EPerson ePerson) throws JOSEException {
if (ePerson == null || StringUtils.isBlank(ePerson.getSessionSalt())) {
return false;
} else {
JWSVerifier verifier = new MACVerifier(buildSigningKey(ePerson));
// If token is valid and not expired return eperson in token
Date expirationTime = jwtClaimsSet.getExpirationTime();
return signedJWT.verify(verifier) && expirationTime != null && // Ensure expiration timestamp is after the current time, with a minute of acceptable clock skew.
DateUtils.isAfter(expirationTime, new Date(), MAX_CLOCK_SKEW_SECONDS);
}
}
use of com.nimbusds.jose.JWSVerifier in project para by Erudika.
the class SecurityUtils method isValidJWToken.
/**
* 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 (!StringUtils.isBlank(secret) && 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;
}
use of com.nimbusds.jose.JWSVerifier in project gravitee-access-management by gravitee-io.
the class ClientAssertionServiceImpl method validateSignatureWithHMAC.
private Maybe<Client> validateSignatureWithHMAC(JWT jwt) {
try {
Algorithm algorithm = jwt.getHeader().getAlgorithm();
if (algorithm instanceof JWSAlgorithm) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(jwt.getHeader().getAlgorithm().getName());
if (jwsAlgorithm != JWSAlgorithm.HS256 && jwsAlgorithm != JWSAlgorithm.HS384 && jwsAlgorithm != JWSAlgorithm.HS512) {
return Maybe.error(new InvalidClientException("Unable to validate client, assertion signature is not valid."));
}
} else {
return Maybe.error(new InvalidClientException("Unable to validate client, assertion signature is not valid."));
}
String clientId = jwt.getJWTClaimsSet().getSubject();
SignedJWT signedJWT = (SignedJWT) jwt;
return this.clientSyncService.findByClientId(clientId).switchIfEmpty(Maybe.error(new InvalidClientException("Missing or invalid client"))).flatMap(client -> {
try {
// Ensure to validate JWT using client_secret_key only if client is authorized to use this auth method
if (client.getTokenEndpointAuthMethod() == null || ClientAuthenticationMethod.CLIENT_SECRET_JWT.equalsIgnoreCase(client.getTokenEndpointAuthMethod())) {
JWSVerifier verifier = new MACVerifier(client.getClientSecret());
if (signedJWT.verify(verifier)) {
return Maybe.just(client);
}
} else {
return Maybe.error(new InvalidClientException("Invalid client: missing or unsupported authentication method"));
}
} catch (JOSEException josee) {
}
return Maybe.error(new InvalidClientException("Unable to validate client, assertion signature is not valid."));
});
} catch (ClassCastException | ParseException ex) {
LOGGER.error(ex.getMessage(), ex);
return Maybe.error(NOT_VALID);
} catch (IllegalArgumentException ex) {
return Maybe.error(new InvalidClientException(ex.getMessage()));
}
}
use of com.nimbusds.jose.JWSVerifier in project snowflake-jdbc by snowflakedb.
the class SFTrustManager method processOCSPBypassSSD.
private boolean processOCSPBypassSSD(String ocsp_ssd, OcspResponseCacheKey cid, String hostname) {
try {
/*
* Get unverified part of the JWT to extract issuer.
*/
SignedJWT jwt_unverified = SignedJWT.parse(ocsp_ssd);
String jwt_issuer = (String) jwt_unverified.getHeader().getCustomParam("ssd_iss");
String ssd_pubKey;
if (jwt_issuer.equals("dep1")) {
ssd_pubKey = ssdManager.getPubKey("dep1");
} else {
ssd_pubKey = ssdManager.getPubKey("dep2");
}
String publicKeyContent = ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent));
RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
/*
* Verify signature of the JWT Token
* Verify time validity of the JWT Token (API does not do this)
*/
SignedJWT jwt_token_verified = SignedJWT.parse(ocsp_ssd);
JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey);
if (jwt_token_verified.verify(jwsVerifier)) {
String sfc_endpoint = jwt_token_verified.getJWTClaimsSet().getStringClaim("sfcEndpoint");
String jwt_certid = jwt_token_verified.getJWTClaimsSet().getStringClaim("certId");
Date jwt_nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime();
Date jwt_exp = jwt_token_verified.getJWTClaimsSet().getExpirationTime();
long current_ts = System.currentTimeMillis();
if (current_ts < jwt_exp.getTime() && current_ts >= jwt_nbf.getTime()) {
if (!sfc_endpoint.equals("*")) {
/*
* In case there are multiple hostnames
* associated to the same account. The
* code expects a space separated list
* of all hostnames associated with this
* account in sfcEndpoint field
*/
String[] splitString = sfc_endpoint.split("\\s+");
for (String s : splitString) {
if (s.equals(hostname)) {
return true;
}
}
return false;
}
/*
* No In Band token can have > 7 days validity
*/
if (jwt_exp.getTime() - jwt_nbf.getTime() > (7 * 24 * 60 * 60 * 1000)) {
return false;
}
byte[] jwt_certid_dec = Base64.decodeBase64(jwt_certid);
DLSequence jwt_rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(jwt_certid_dec);
ASN1Encodable[] jwt_rawCertIdArray = jwt_rawCertId.toArray();
byte[] issuerNameHashDer = ((DEROctetString) jwt_rawCertIdArray[1]).getEncoded();
byte[] issuerKeyHashDer = ((DEROctetString) jwt_rawCertIdArray[2]).getEncoded();
BigInteger serialNumber = ((ASN1Integer) jwt_rawCertIdArray[3]).getValue();
OcspResponseCacheKey k = new OcspResponseCacheKey(issuerNameHashDer, issuerKeyHashDer, serialNumber);
if (k.equals(cid)) {
LOGGER.debug("Found a Signed OCSP Bypass SSD for ceri id {}", cid);
return true;
}
LOGGER.debug("Found invalid OCSP bypass for cert id {}", cid);
return false;
}
}
return false;
} catch (Throwable ex) {
LOGGER.debug("Failed to parse JWT Token, aborting");
return false;
}
}
use of com.nimbusds.jose.JWSVerifier in project snowflake-jdbc by snowflakedb.
the class SFTrustManager method processKeyUpdateDirective.
/**
* SSD Processing Code
*/
private void processKeyUpdateDirective(String issuer, String ssd) {
try {
/*
* Get unverified part of the JWT to extract issuer.
*
*/
// PlainJWT jwt_unverified = PlainJWT.parse(ssd);
SignedJWT jwt_signed = SignedJWT.parse(ssd);
String jwt_issuer = (String) jwt_signed.getHeader().getCustomParam("ssd_iss");
String ssd_pubKey;
if (!jwt_issuer.equals(issuer)) {
LOGGER.debug("Issuer mismatch. Invalid SSD");
return;
}
if (jwt_issuer.equals("dep1")) {
ssd_pubKey = ssdManager.getPubKey("dep1");
} else {
ssd_pubKey = ssdManager.getPubKey("dep2");
}
if (ssd_pubKey == null) {
LOGGER.debug("Invalid SSD");
return;
}
String publicKeyContent = ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent));
RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
/*
* Verify signature of the JWT Token
*/
SignedJWT jwt_token_verified = SignedJWT.parse(ssd);
JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey);
try {
if (jwt_token_verified.verify(jwsVerifier)) {
/*
* verify nbf time
*/
long cur_time = System.currentTimeMillis();
Date nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime();
// double nbf = jwt_token_verified.getJWTClaimsSet().getDoubleClaim("nbf");
if (cur_time < nbf.getTime()) {
LOGGER.debug("The SSD token is not yet valid. Current time less than Not Before Time");
return;
}
float key_ver = Float.parseFloat(jwt_token_verified.getJWTClaimsSet().getStringClaim("keyVer"));
if (key_ver <= ssdManager.getPubKeyVer(jwt_issuer)) {
return;
}
ssdManager.updateKey(jwt_issuer, jwt_token_verified.getJWTClaimsSet().getStringClaim("pubKey"), key_ver);
}
} catch (Throwable ex) {
LOGGER.debug("Failed to verify JWT Token");
throw ex;
}
} catch (Throwable ex) {
LOGGER.debug("Failed to parse JWT Token, aborting");
}
}
Aggregations