Search in sources :

Example 1 with JWTGeneratorException

use of org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException in project carbon-apimgt by wso2.

the class JWTValidator method generateAndRetrieveJWTToken.

private String generateAndRetrieveJWTToken(String tokenSignature, JWTInfoDto jwtInfoDto) throws APISecurityException {
    String endUserToken = null;
    boolean valid = false;
    String jwtTokenCacheKey = jwtInfoDto.getApiContext().concat(":").concat(jwtInfoDto.getVersion()).concat(":").concat(tokenSignature);
    if (isGatewayTokenCacheEnabled) {
        Object token = getGatewayJWTTokenCache().get(jwtTokenCacheKey);
        if (token != null) {
            endUserToken = (String) token;
            String[] splitToken = ((String) token).split("\\.");
            JSONObject payload = new JSONObject(new String(Base64.getUrlDecoder().decode(splitToken[1])));
            long exp = payload.getLong("exp") * 1000L;
            long timestampSkew = getTimeStampSkewInSeconds() * 1000;
            valid = (exp - System.currentTimeMillis() > timestampSkew);
        }
        if (StringUtils.isEmpty(endUserToken) || !valid) {
            try {
                includeUserStoreClaimsIntoClaims(jwtInfoDto);
                endUserToken = apiMgtGatewayJWTGenerator.generateToken(jwtInfoDto);
                getGatewayJWTTokenCache().put(jwtTokenCacheKey, endUserToken);
            } catch (JWTGeneratorException e) {
                log.error("Error while Generating Backend JWT", e);
                throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
            }
        }
    } else {
        try {
            includeUserStoreClaimsIntoClaims(jwtInfoDto);
            endUserToken = apiMgtGatewayJWTGenerator.generateToken(jwtInfoDto);
        } catch (JWTGeneratorException e) {
            log.error("Error while Generating Backend JWT", e);
            throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
        }
    }
    return endUserToken;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) JWTGeneratorException(org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException)

Example 2 with JWTGeneratorException

use of org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException in project carbon-apimgt by wso2.

the class JWTUtil method signJwt.

/**
 * Utility method to sign a JWT assertion with a particular signature algorithm.
 *
 * @param assertion          valid JWT assertion
 * @param privateKey         private key which use to sign the JWT assertion
 * @param signatureAlgorithm signature algorithm which use to sign the JWT assertion
 * @return byte array of the JWT signature
 * @throws JWTGeneratorException
 */
public static byte[] signJwt(String assertion, PrivateKey privateKey, String signatureAlgorithm) throws JWTGeneratorException {
    try {
        // initialize signature with private key and algorithm
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign(privateKey);
        // update signature with data to be signed
        byte[] dataInBytes = assertion.getBytes(Charset.defaultCharset());
        signature.update(dataInBytes);
        // sign the assertion and return the signature
        return signature.sign();
    } catch (NoSuchAlgorithmException e) {
        // do not log
        throw new JWTGeneratorException("Signature algorithm not found", e);
    } catch (InvalidKeyException e) {
        // do not log
        throw new JWTGeneratorException("Invalid private key provided for signing", e);
    } catch (SignatureException e) {
        // do not log
        throw new JWTGeneratorException("Error while signing JWT", e);
    }
}
Also used : Signature(java.security.Signature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) JWTGeneratorException(org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with JWTGeneratorException

use of org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException in project carbon-apimgt by wso2.

the class JWTUtil method generateHeader.

/**
 * Utility method to generate JWT header with public certificate thumbprint for signature verification.
 *
 * @param publicCert         - The public certificate which needs to include in the header as thumbprint
 * @param signatureAlgorithm signature algorithm which needs to include in the header
 * @throws JWTGeneratorException
 */
public static String generateHeader(Certificate publicCert, String signatureAlgorithm) throws JWTGeneratorException {
    try {
        // generate the SHA-1 thumbprint of the certificate
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = publicCert.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();
        String publicCertThumbprint = hexify(digestInBytes);
        String base64UrlEncodedThumbPrint;
        base64UrlEncodedThumbPrint = java.util.Base64.getUrlEncoder().encodeToString(publicCertThumbprint.getBytes("UTF-8"));
        StringBuilder jwtHeader = new StringBuilder();
        /*
             * Sample header
             * {"typ":"JWT", "alg":"SHA256withRSA", "x5t":"a_jhNus21KVuoFx65LmkW2O_l10",
             * "kid":"a_jhNus21KVuoFx65LmkW2O_l10_RS256"}
             * {"typ":"JWT", "alg":"[2]", "x5t":"[1]", "x5t":"[1]"}
             * */
        jwtHeader.append("{\"typ\":\"JWT\",");
        jwtHeader.append("\"alg\":\"");
        jwtHeader.append(getJWSCompliantAlgorithmCode(signatureAlgorithm));
        jwtHeader.append("\",");
        jwtHeader.append("\"x5t\":\"");
        jwtHeader.append(base64UrlEncodedThumbPrint);
        jwtHeader.append("\"}");
        return jwtHeader.toString();
    } catch (NoSuchAlgorithmException | CertificateEncodingException | UnsupportedEncodingException e) {
        throw new JWTGeneratorException("Error in generating public certificate thumbprint", e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest) JWTGeneratorException(org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException)

Example 4 with JWTGeneratorException

use of org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException in project carbon-apimgt by wso2.

the class JWTValidatorImpl method validateToken.

@Override
public JWTValidationInfo validateToken(SignedJWTInfo signedJWTInfo) throws APIManagementException {
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    boolean state;
    try {
        state = validateSignature(signedJWTInfo.getSignedJWT());
        if (state) {
            JWTClaimsSet jwtClaimsSet = signedJWTInfo.getJwtClaimsSet();
            state = isValidCertificateBoundAccessToken(signedJWTInfo);
            if (state) {
                state = validateTokenExpiry(jwtClaimsSet);
                if (state) {
                    jwtValidationInfo.setConsumerKey(getConsumerKey(jwtClaimsSet));
                    jwtValidationInfo.setScopes(getScopes(jwtClaimsSet));
                    jwtValidationInfo.setAppToken(getIsAppToken(jwtClaimsSet));
                    JWTClaimsSet transformedJWTClaimSet = transformJWTClaims(jwtClaimsSet);
                    createJWTValidationInfoFromJWT(jwtValidationInfo, transformedJWTClaimSet);
                    jwtValidationInfo.setRawPayload(signedJWTInfo.getToken());
                    return jwtValidationInfo;
                } else {
                    jwtValidationInfo.setValid(false);
                    jwtValidationInfo.setValidationCode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
                    return jwtValidationInfo;
                }
            } else {
                jwtValidationInfo.setValid(false);
                jwtValidationInfo.setValidationCode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
                return jwtValidationInfo;
            }
        } else {
            jwtValidationInfo.setValid(false);
            jwtValidationInfo.setValidationCode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
            return jwtValidationInfo;
        }
    } catch (ParseException | JWTGeneratorException e) {
        throw new APIManagementException("Error while parsing JWT", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) JWTGeneratorException(org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 5 with JWTGeneratorException

use of org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException in project carbon-apimgt by wso2.

the class ApiKeyAuthenticator method generateAndRetrieveBackendJWTToken.

private String generateAndRetrieveBackendJWTToken(String tokenSignature, JWTInfoDto jwtInfoDto) throws APISecurityException {
    String endUserToken = null;
    boolean valid = false;
    String jwtTokenCacheKey = jwtInfoDto.getApiContext().concat(":").concat(jwtInfoDto.getVersion()).concat(":").concat(tokenSignature);
    if (isGatewayTokenCacheEnabled) {
        Object token = getGatewayApiKeyCache().get(jwtTokenCacheKey);
        if (token != null) {
            endUserToken = (String) token;
            String[] splitToken = ((String) token).split("\\.");
            JSONObject payload = new JSONObject(new String(Base64.getUrlDecoder().decode(splitToken[1])));
            long exp = payload.getLong("exp");
            long timestampSkew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
            valid = (exp - System.currentTimeMillis() > timestampSkew);
        }
        if (StringUtils.isEmpty(endUserToken) || !valid) {
            try {
                endUserToken = apiMgtGatewayJWTGenerator.generateToken(jwtInfoDto);
                getGatewayApiKeyCache().put(jwtTokenCacheKey, endUserToken);
            } catch (JWTGeneratorException e) {
                log.error("Error while Generating Backend JWT", e);
                throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
            }
        }
    } else {
        try {
            endUserToken = apiMgtGatewayJWTGenerator.generateToken(jwtInfoDto);
        } catch (JWTGeneratorException e) {
            log.error("Error while Generating Backend JWT", e);
            throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
        }
    }
    return endUserToken;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) JWTGeneratorException(org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException)

Aggregations

JWTGeneratorException (org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 JSONObject (org.json.JSONObject)2 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InvalidKeyException (java.security.InvalidKeyException)1 MessageDigest (java.security.MessageDigest)1 Signature (java.security.Signature)1 SignatureException (java.security.SignatureException)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 ParseException (java.text.ParseException)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)1