use of org.jose4j.lang.JoseException in project blueocean-plugin by jenkinsci.
the class JwtTokenVerifierImpl method validate.
/**
* @return
* null if the JWT token is not present
* @throws Exception
* if the JWT token is present but invalid
*/
@CheckForNull
private Authentication validate(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
return null;
}
String token = authHeader.substring("Bearer ".length());
JsonWebStructure jws = parse(token);
if (jws == null) {
return null;
}
try {
String alg = jws.getAlgorithmHeaderValue();
if (alg == null || !alg.equals(RSA_USING_SHA256)) {
logger.error(String.format("Invalid JWT token: unsupported algorithm in header, found %s, expected %s", alg, RSA_USING_SHA256));
throw new ServiceException.UnauthorizedException("Invalid JWT token");
}
String kid = jws.getKeyIdHeaderValue();
if (kid == null) {
logger.error("Invalid JWT token: missing kid");
throw new ServiceException.UnauthorizedException("Invalid JWT token");
}
SigningPublicKey publicKey = JwtSigningKeyProvider.toPublicKey(kid);
if (publicKey == null) {
throw new ServiceException.UnexpectedErrorException("Invalid kid=" + kid);
}
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setRequireJwtId().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
30).setRequireSubject().setVerificationKey(// verify the sign with the public key
publicKey.getKey()).build();
try {
JwtContext context = jwtConsumer.process(token);
JwtClaims claims = context.getJwtClaims();
String subject = claims.getSubject();
if (subject.equals("anonymous")) {
// if anonymous, we do not bother checking expiration
return Jenkins.ANONYMOUS2;
} else {
// If not anonymous user, get Authentication object associated with this claim
// We give a change to the authentication store to inspect the claims and if expired it might
// do cleanup of associated Authentication object for example.
JwtAuthenticationStore authenticationStore = getJwtStore(claims.getClaimsMap());
Authentication authentication = authenticationStore.getAuthentication(claims.getClaimsMap());
// Now check if token expired
NumericDate expirationTime = claims.getExpirationTime();
if (expirationTime.isBefore(NumericDate.now())) {
throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
}
return authentication;
}
} catch (InvalidJwtException e) {
logger.error("Invalid JWT token: " + e.getMessage(), e);
throw new ServiceException.UnauthorizedException("Invalid JWT token");
} catch (MalformedClaimException e) {
logger.error(String.format("Error reading sub header for token %s", jws.getPayload()), e);
throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
}
} catch (JoseException e) {
logger.error("Error parsing JWT token: " + e.getMessage(), e);
throw new ServiceException.UnauthorizedException("Invalid JWT Token: " + e.getMessage());
}
}
use of org.jose4j.lang.JoseException in project open-ecard by ecsec.
the class TCTokenVerifier method verifyRequestToken.
/**
* Verifies the elements of the TCToken.
*
* @throws InvalidRedirectUrlException Thrown in case the RefreshAddress is missing or invalid.
* @throws InvalidTCTokenElement Thrown in case any element inside the TCToken is invalid.
*/
public void verifyRequestToken() throws InvalidRedirectUrlException, InvalidTCTokenElement {
assertRefreshURL(token.getRefreshAddress());
assertHttpsURL("ServerAddress", token.getServerAddress());
assertRequired("SessionIdentifier", token.getSessionIdentifier());
assertRequired("PathSecurity-Protocol", token.getPathSecurityProtocol());
checkEqualOR("PathSecurity-Protocol", token.getPathSecurityProtocol(), "urn:ietf:rfc:5246", "http://ws.openecard.org/pathsecurity/tlsv12-with-pin-encryption");
if (token.getPathSecurityProtocol().equals("http://ws.openecard.org/pathsecurity/tlsv12-with-pin-encryption")) {
assertRequired("PathSecurity-Parameters", token.getPathSecurityParameters());
assertRequired("JWK", token.getPathSecurityParameters().getJWK());
try {
JsonWebKey key = JsonWebKey.Factory.newJwk(token.getPathSecurityParameters().getJWK());
} catch (JoseException ex) {
throw new InvalidTCTokenElement("Failed to parse JWK.", ex);
}
}
}
use of org.jose4j.lang.JoseException in project open-ecard by ecsec.
the class ChipGateway method getPin.
@Nullable
private char[] getPin(@Nullable String encryptedPin) throws RemotePinException {
if (ChipGatewayProperties.isRemotePinAllowed() && encryptedPin != null) {
if (pinKey != null) {
try {
// decrypt PIN
JsonWebEncryption jwe = new JsonWebEncryption();
// specify algorithmic constraints
AlgorithmConstraints algConstraints = new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, KeyManagementAlgorithmIdentifiers.DIRECT);
jwe.setAlgorithmConstraints(algConstraints);
AlgorithmConstraints encConstraints = new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256, ContentEncryptionAlgorithmIdentifiers.AES_192_CBC_HMAC_SHA_384, ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512, ContentEncryptionAlgorithmIdentifiers.AES_128_GCM, ContentEncryptionAlgorithmIdentifiers.AES_192_GCM, ContentEncryptionAlgorithmIdentifiers.AES_256_GCM);
jwe.setContentEncryptionAlgorithmConstraints(encConstraints);
// perform decryption
jwe.setCompactSerialization(encryptedPin);
jwe.setKey(pinKey.getKey());
byte[] pinBytes = jwe.getPlaintextBytes();
// check if PIN is a sane value
char[] pin;
if (pinBytes == null || pinBytes.length == 0) {
String msg = "No or empty PIN received from ChipGateway server, despite a key being present.";
LOG.warn(msg);
pin = null;
} else {
CharBuffer charBuf = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(pinBytes));
pin = new char[charBuf.remaining()];
charBuf.get(pin);
if (charBuf.hasArray()) {
Arrays.fill(charBuf.array(), ' ');
}
}
return pin;
} catch (JoseException ex) {
throw new RemotePinException("Error decrypting PIN.", ex);
}
} else {
// PIN sent but no key provided, raise error for the server
throw new RemotePinException("Encrypted PIN received, but no key for decryption is available.");
}
} else {
// no pin sent, let user supply the pin
return null;
}
}
use of org.jose4j.lang.JoseException in project box-java-sdk by box.
the class BoxDeveloperEditionAPIConnection method constructJWTAssertion.
private String constructJWTAssertion(NumericDate now) {
JwtClaims claims = new JwtClaims();
claims.setIssuer(this.getClientID());
claims.setAudience(JWT_AUDIENCE);
if (now == null) {
claims.setExpirationTimeMinutesInTheFuture(0.5f);
} else {
now.addSeconds(30L);
claims.setExpirationTime(now);
}
claims.setSubject(this.entityID);
claims.setClaim("box_sub_type", this.entityType.toString());
claims.setGeneratedJwtId(64);
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(this.decryptPrivateKey());
jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
jws.setHeader("typ", "JWT");
if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
jws.setHeader("kid", this.publicKeyID);
}
String assertion;
try {
assertion = jws.getCompactSerialization();
} catch (JoseException e) {
throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
}
return assertion;
}
use of org.jose4j.lang.JoseException in project habot by ghys.
the class NotificationService method sendNotification.
/**
* Sends a web push notification to a specified subscription
*
* @param subscription the subscription to send the notification to
* @param payload the payload to push
* @return the {@link Future} for the {@link Response} to the push server
* @throws GeneralSecurityException
*/
public Future<Response> sendNotification(Subscription subscription, String payload) throws GeneralSecurityException {
getPushService();
Notification notification = new Notification(subscription, payload);
try {
return this.pushService.send(notification);
} catch (IOException | JoseException | ExecutionException | InterruptedException e) {
logger.error("Unable to send the notification to {}: {}", this.subscriptionProvider.keyToString(subscription.keys), e.toString());
return null;
}
}
Aggregations