Search in sources :

Example 11 with InvalidJwtException

use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxTrust by GluuFederation.

the class OAuthValidationFilter method getOAuthData.

private OAuthData getOAuthData(HttpSession session, HttpServletRequest request, String authorizationCode) throws Exception {
    // Check state
    String authorizationState = request.getParameter(Configuration.OAUTH_STATE);
    final String stateSession = session != null ? (String) session.getAttribute(Configuration.SESSION_AUTH_STATE) : null;
    if (!StringHelper.equals(stateSession, authorizationState)) {
        log.error("Login failed, oxTrust wasn't allowed to access user data");
        return null;
    }
    String oAuthAuthorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String oAuthHost = getOAuthHost(oAuthAuthorizeUrl);
    String oAuthTokenUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_TOKEN_URL, null);
    String oAuthUserInfoUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_USERINFO_URL, null);
    String oAuthClientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String oAuthClientPassword = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (oAuthClientPassword != null) {
        try {
            oAuthClientPassword = StringEncrypter.defaultInstance().decrypt(oAuthClientPassword, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }
    String scopes = getParameter(request, Configuration.OAUTH_SCOPE);
    log.trace("scopes : " + scopes);
    // 1. Request access token using the authorization code
    log.trace("Getting access token");
    TokenClient tokenClient1 = new TokenClient(oAuthTokenUrl);
    String redirectURL = constructRedirectUrl(request);
    TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, oAuthClientId, oAuthClientPassword);
    if (tokenResponse == null) {
        log.error("Get empty token response. User can't log into application");
        return null;
    }
    log.trace("tokenResponse : " + tokenResponse);
    log.trace("tokenResponse.getErrorType() : " + tokenResponse.getErrorType());
    String accessToken = tokenResponse.getAccessToken();
    String idToken = tokenResponse.getIdToken();
    log.trace("accessToken : " + accessToken);
    log.trace("idToken : " + idToken);
    // Parse JWT
    Jwt jwt;
    try {
        jwt = Jwt.parse(idToken);
    } catch (InvalidJwtException ex) {
        log.error("Failed to parse id_token");
        return null;
    }
    // Check nonce
    String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
    final String nonceSession = session != null ? (String) session.getAttribute(Configuration.SESSION_AUTH_NONCE) : null;
    if (!StringHelper.equals(nonceSession, nonceResponse)) {
        log.error("User info response :  nonce is not matching.");
        return null;
    }
    log.info("Session validation successful. User is logged in");
    UserInfoClient userInfoClient = new UserInfoClient(oAuthUserInfoUrl);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
    if (userInfoResponse == null) {
        log.error("Get empty user info response. User can't log into application");
        return null;
    }
    OAuthData oAuthData = new OAuthData();
    oAuthData.setHost(oAuthHost);
    // Determine uid
    List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
    if ((uidValues == null) || (uidValues.size() == 0)) {
        log.error("User infor response doesn't contains uid claim");
        return null;
    }
    oAuthData.setUserUid(uidValues.get(0));
    oAuthData.setAccessToken(accessToken);
    oAuthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn());
    oAuthData.setScopes(scopes);
    oAuthData.setIdToken(idToken);
    log.trace("User uid: " + oAuthData.getUserUid());
    return oAuthData;
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) TokenResponse(org.gluu.oxauth.client.TokenResponse) Jwt(org.gluu.oxauth.model.jwt.Jwt) EncryptionException(org.gluu.util.security.StringEncrypter.EncryptionException) UserInfoResponse(org.gluu.oxauth.client.UserInfoResponse) TokenClient(org.gluu.oxauth.client.TokenClient) UserInfoClient(org.gluu.oxauth.client.UserInfoClient) OAuthData(org.gluu.oxauth.client.session.OAuthData)

Example 12 with InvalidJwtException

use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class JweDecrypterImpl method decrypt.

@Override
public Jwe decrypt(String encryptedJwe) throws InvalidJweException {
    try {
        String[] jweParts = encryptedJwe.split("\\.");
        if (jweParts.length != 5) {
            throw new InvalidJwtException("Invalid JWS format.");
        }
        String encodedHeader = jweParts[0];
        String encodedEncryptedKey = jweParts[1];
        String encodedInitializationVector = jweParts[2];
        String encodedCipherText = jweParts[3];
        String encodedIntegrityValue = jweParts[4];
        Jwe jwe = new Jwe();
        jwe.setEncodedHeader(encodedHeader);
        jwe.setEncodedEncryptedKey(encodedEncryptedKey);
        jwe.setEncodedInitializationVector(encodedInitializationVector);
        jwe.setEncodedCiphertext(encodedCipherText);
        jwe.setEncodedIntegrityValue(encodedIntegrityValue);
        jwe.setHeader(new JwtHeader(encodedHeader));
        EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptedJwe);
        setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM)));
        setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD)));
        final KeyEncryptionAlgorithm keyEncryptionAlgorithm = getKeyEncryptionAlgorithm();
        Key encriptionKey = null;
        if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5 || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP) {
            encriptionKey = privateKey;
        } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
            if (sharedSymmetricKey == null) {
                throw new InvalidJweException("The shared symmetric key is null");
            }
            int keyLength = 16;
            if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
                keyLength = 32;
            }
            if (sharedSymmetricKey.length != keyLength) {
                MessageDigest sha = MessageDigest.getInstance("SHA-256");
                sharedSymmetricKey = sha.digest(sharedSymmetricKey);
                sharedSymmetricKey = Arrays.copyOf(sharedSymmetricKey, keyLength);
            }
            encriptionKey = new SecretKeySpec(sharedSymmetricKey, 0, sharedSymmetricKey.length, "AES");
        } else {
            throw new InvalidJweException("The key encryption algorithm is not supported");
        }
        JWEDecrypter decrypter = DECRYPTER_FACTORY.createJWEDecrypter(encryptedJwt.getHeader(), encriptionKey);
        decrypter.getJCAContext().setProvider(SecurityProviderUtility.getInstance());
        encryptedJwt.decrypt(decrypter);
        final SignedJWT signedJWT = encryptedJwt.getPayload().toSignedJWT();
        if (signedJWT != null) {
            final Jwt jwt = Jwt.parse(signedJWT.serialize());
            jwe.setSignedJWTPayload(jwt);
            jwe.setClaims(jwt != null ? jwt.getClaims() : null);
        } else {
            final String base64encodedPayload = encryptedJwt.getPayload().toString();
            jwe.setClaims(new JwtClaims(base64encodedPayload));
        }
        return jwe;
    } catch (Exception e) {
        throw new InvalidJweException(e);
    }
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) JwtClaims(org.gluu.oxauth.model.jwt.JwtClaims) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignedJWT(com.nimbusds.jwt.SignedJWT) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) JWEDecrypter(com.nimbusds.jose.JWEDecrypter) JwtHeader(org.gluu.oxauth.model.jwt.JwtHeader) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) MessageDigest(java.security.MessageDigest) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateKey(org.gluu.oxauth.model.crypto.signature.RSAPrivateKey) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException)

Example 13 with InvalidJwtException

use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class Jwt method parse.

public static Jwt parse(String encodedJwt) throws InvalidJwtException {
    if (StringUtils.isBlank(encodedJwt)) {
        return null;
    }
    String encodedHeader = null;
    String encodedClaims = null;
    String encodedSignature = null;
    String[] jwtParts = encodedJwt.split("\\.");
    if (jwtParts.length == 2) {
        // Signature Algorithm NONE
        encodedHeader = jwtParts[0];
        encodedClaims = jwtParts[1];
        encodedSignature = "";
    } else if (jwtParts.length == 3) {
        encodedHeader = jwtParts[0];
        encodedClaims = jwtParts[1];
        encodedSignature = jwtParts[2];
    } else {
        throw new InvalidJwtException("Invalid JWT format.");
    }
    Jwt jwt = new Jwt();
    jwt.setHeader(new JwtHeader(encodedHeader));
    jwt.setClaims(new JwtClaims(encodedClaims));
    jwt.setEncodedSignature(encodedSignature);
    jwt.encodedHeader = encodedHeader;
    jwt.encodedClaims = encodedClaims;
    jwt.loaded = true;
    return jwt;
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException)

Example 14 with InvalidJwtException

use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class JwtClaimSet method toJsonObject.

public JSONObject toJsonObject() throws InvalidJwtException {
    JSONObject jsonObject = new JSONObject();
    try {
        for (Map.Entry<String, Object> claim : claims.entrySet()) {
            if (claim.getValue() instanceof Date) {
                Date date = (Date) claim.getValue();
                jsonObject.put(claim.getKey(), date.getTime() / 1000);
            } else if (claim.getValue() instanceof JwtSubClaimObject) {
                JwtSubClaimObject subClaimObject = (JwtSubClaimObject) claim.getValue();
                jsonObject.put(subClaimObject.getName(), subClaimObject.toJsonObject());
            } else if (claim.getValue() instanceof List) {
                List claimObjectList = (List) claim.getValue();
                JSONArray claimsJSONArray = new JSONArray();
                for (Object claimObj : claimObjectList) {
                    claimsJSONArray.put(claimObj);
                }
                jsonObject.put(claim.getKey(), claimsJSONArray);
            } else {
                jsonObject.put(claim.getKey(), claim.getValue());
            }
        }
    } catch (JSONException e) {
        throw new InvalidJwtException(e);
    } catch (Exception e) {
        throw new InvalidJwtException(e);
    }
    return jsonObject;
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 15 with InvalidJwtException

use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class AuthenticationFilter method processJwtAuth.

private void processJwtAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
    boolean authorized = false;
    try {
        if (servletRequest.getParameter("client_assertion") != null && servletRequest.getParameter("client_assertion_type") != null) {
            String clientId = servletRequest.getParameter("client_id");
            ClientAssertionType clientAssertionType = ClientAssertionType.fromString(servletRequest.getParameter("client_assertion_type"));
            String encodedAssertion = servletRequest.getParameter("client_assertion");
            if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
                ClientAssertion clientAssertion = new ClientAssertion(appConfiguration, cryptoProvider, clientId, clientAssertionType, encodedAssertion);
                String username = clientAssertion.getSubjectIdentifier();
                String password = clientAssertion.getClientSecret();
                // Identity.username and user isn't authenticated
                if (!username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                    identity.getCredentials().setUsername(username);
                    identity.getCredentials().setPassword(password);
                    authenticator.authenticateClient(servletRequest, true);
                    authorized = true;
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ServletException | IOException | InvalidJwtException ex) {
        log.info("JWT authentication failed: {}", ex);
    }
    if (!authorized) {
        sendError(servletResponse);
    }
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) ClientAssertionType(org.gluu.oxauth.model.token.ClientAssertionType) IOException(java.io.IOException) ClientAssertion(org.gluu.oxauth.model.token.ClientAssertion)

Aggregations

InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)19 Jwt (org.gluu.oxauth.model.jwt.Jwt)10 JSONException (org.json.JSONException)8 Response (javax.ws.rs.core.Response)6 JSONObject (org.json.JSONObject)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 URISyntaxException (java.net.URISyntaxException)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 Builder (javax.ws.rs.client.Invocation.Builder)4 BaseTest (org.gluu.oxauth.BaseTest)4 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)4 Parameters (org.testng.annotations.Parameters)4 Test (org.testng.annotations.Test)4 IOException (java.io.IOException)3 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)3 TokenClient (org.gluu.oxauth.client.TokenClient)3 TokenResponse (org.gluu.oxauth.client.TokenResponse)3 UserInfoResponse (org.gluu.oxauth.client.UserInfoResponse)3 SignatureAlgorithm (org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm)3 Client (org.gluu.oxauth.model.registration.Client)3