io.convergence_platform.services.SecurityHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of service-lib Show documentation
Show all versions of service-lib Show documentation
Holds the common functionality needed by all Convergence Platform-based services written in Java.
The newest version!
package io.convergence_platform.services;
import io.convergence_platform.common.dto.FailureInfoDTO;
import io.convergence_platform.common.exceptions.ManagedApiException;
import io.convergence_platform.common.helpers.ExceptionHelper;
import io.convergence_platform.common.responses.Errors;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.springframework.http.HttpStatus;
import java.io.StringReader;
import java.security.KeyPair;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import static org.springframework.http.HttpStatus.FORBIDDEN;
public class SecurityHelper {
// Command to create a new key
// openssl ecparam -genkey -name secp521r1 -noout -out ec512-key-pair.pem
public static Algorithm getJwtAlgorithm(String ecKey) {
return ExceptionHelper.executeWithValue(() -> {
final String _ecKey = ecKey.replace("\\n", "\n").replace("\"", "");
// Parse the EC key pair
PEMParser pemParser = new PEMParser(new StringReader(_ecKey));
PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
// Convert to Java (JCA) format
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
KeyPair keyPair = converter.getKeyPair(pemKeyPair);
pemParser.close();
// Get private + public EC key
ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
return Algorithm.ECDSA512(publicKey, privateKey);
});
}
public static DecodedJWT verifyJwt(JWTVerifier verifier, String token) {
try {
return verifier.verify(token);
} catch (SignatureVerificationException ex) {
// TODO: This should not happen and should raise an alarm as it is the result of a tampered with JWT
throw new ManagedApiException(FORBIDDEN.value(),
Errors.ERR_ACCESS_DENIED,
"The authorization token signature is invalid.");
} catch (TokenExpiredException ex) {
throw new ManagedApiException(FORBIDDEN.value(),
Errors.EXPIRED_AUTHORIZATION_TOKEN,
"The authorization token is expired, please sign-in again.");
}
}
}