Search in sources :

Example 31 with VerificationException

use of org.keycloak.common.VerificationException in project keycloak by keycloak.

the class RSAVerifierTest method testNotBeforeGood.

@Test
public void testNotBeforeGood() throws Exception {
    token.notBefore(Time.currentTime() - 100);
    String encoded = new JWSBuilder().jsonContent(token).rsa256(idpPair.getPrivate());
    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
    } catch (VerificationException ignored) {
        throw ignored;
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 32 with VerificationException

use of org.keycloak.common.VerificationException in project keycloak by keycloak.

the class ServerECDSASignatureVerifierContext method verify.

@Override
public boolean verify(byte[] data, byte[] signature) throws VerificationException {
    try {
        /*
            Fallback for backwards compatibility of ECDSA signed tokens which were issued in previous versions.
            TODO remove by https://issues.jboss.org/browse/KEYCLOAK-11911
             */
        int expectedSize = ECDSASignatureProvider.ECDSA.valueOf(getAlgorithm()).getSignatureLength();
        byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : ECDSASignatureProvider.concatenatedRSToASN1DER(signature, expectedSize);
        return super.verify(data, derSignature);
    } catch (Exception e) {
        throw new VerificationException("Signing failed", e);
    }
}
Also used : VerificationException(org.keycloak.common.VerificationException) VerificationException(org.keycloak.common.VerificationException)

Example 33 with VerificationException

use of org.keycloak.common.VerificationException in project keycloak by keycloak.

the class ClientECDSASignatureVerifierContext method verify.

@Override
public boolean verify(byte[] data, byte[] signature) throws VerificationException {
    try {
        /*
            Fallback for backwards compatibility of ECDSA signed tokens which were issued in previous versions.
            TODO remove by https://issues.jboss.org/browse/KEYCLOAK-11911
             */
        int expectedSize = ECDSASignatureProvider.ECDSA.valueOf(getAlgorithm()).getSignatureLength();
        byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : ECDSASignatureProvider.concatenatedRSToASN1DER(signature, expectedSize);
        return super.verify(data, derSignature);
    } catch (Exception e) {
        throw new VerificationException("Signing failed", e);
    }
}
Also used : VerificationException(org.keycloak.common.VerificationException) VerificationException(org.keycloak.common.VerificationException)

Example 34 with VerificationException

use of org.keycloak.common.VerificationException in project keycloak by keycloak.

the class AuthenticationManager method verifyIdentityToken.

public static AuthResult verifyIdentityToken(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, boolean checkActive, boolean checkTokenType, String checkAudience, boolean isCookie, String tokenString, HttpHeaders headers, Predicate<? super AccessToken>... additionalChecks) {
    try {
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(tokenString, AccessToken.class).withDefaultChecks().realmUrl(Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName())).checkActive(checkActive).checkTokenType(checkTokenType).withChecks(additionalChecks);
        if (checkAudience != null) {
            verifier.audience(checkAudience);
        }
        // Check token revocation in case of access token
        if (checkTokenType) {
            verifier.withChecks(new TokenManager.TokenRevocationCheck(session));
        }
        String kid = verifier.getHeader().getKeyId();
        String algorithm = verifier.getHeader().getAlgorithm().name();
        SignatureVerifierContext signatureVerifier = session.getProvider(SignatureProvider.class, algorithm).verifier(kid);
        verifier.verifierContext(signatureVerifier);
        AccessToken token = verifier.verify().getToken();
        if (checkActive) {
            if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) {
                logger.debug("Identity cookie expired");
                return null;
            }
        }
        UserSessionModel userSession = null;
        UserModel user = null;
        if (token.getSessionState() == null) {
            user = TokenManager.lookupUserFromStatelessToken(session, realm, token);
            if (!isUserValid(session, realm, user, token)) {
                return null;
            }
        } else {
            userSession = session.sessions().getUserSession(realm, token.getSessionState());
            if (userSession != null) {
                user = userSession.getUser();
                if (!isUserValid(session, realm, user, token)) {
                    return null;
                }
            }
        }
        if (token.getSessionState() != null && !isSessionValid(realm, userSession)) {
            // Check if accessToken was for the offline session.
            if (!isCookie) {
                UserSessionModel offlineUserSession = session.sessions().getOfflineUserSession(realm, token.getSessionState());
                if (isOfflineSessionValid(realm, offlineUserSession)) {
                    user = offlineUserSession.getUser();
                    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
                    if (!isClientValid(offlineUserSession, client, token)) {
                        return null;
                    }
                    return new AuthResult(user, offlineUserSession, token, client);
                }
            }
            if (userSession != null)
                backchannelLogout(session, realm, userSession, uriInfo, connection, headers, true);
            logger.debug("User session not active");
            return null;
        }
        session.setAttribute("state_checker", token.getOtherClaims().get("state_checker"));
        ClientModel client;
        if (isCookie) {
            client = null;
        } else {
            client = realm.getClientByClientId(token.getIssuedFor());
            if (!isClientValid(userSession, client, token)) {
                return null;
            }
        }
        return new AuthResult(user, userSession, token, client);
    } catch (VerificationException e) {
        logger.debugf("Failed to verify identity token: %s", e.getMessage());
    }
    return null;
}
Also used : UserModel(org.keycloak.models.UserModel) SignatureProvider(org.keycloak.crypto.SignatureProvider) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) TokenManager(org.keycloak.protocol.oidc.TokenManager)

Example 35 with VerificationException

use of org.keycloak.common.VerificationException in project keycloak by keycloak.

the class LogoutEndpoint method logout.

/**
 * Logout user session.  User must be logged in via a session cookie.
 *
 * When the logout is initiated by a remote idp, the parameter "initiating_idp" can be supplied. This param will
 * prevent upstream logout (since the logout procedure has already been started in the remote idp).
 *
 * @param redirectUri
 * @param initiatingIdp The alias of the idp initiating the logout.
 * @return
 */
@GET
@NoCache
public // deprecated
Response logout(// deprecated
@QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam("id_token_hint") String encodedIdToken, @QueryParam("post_logout_redirect_uri") String postLogoutRedirectUri, @QueryParam("state") String state, @QueryParam("initiating_idp") String initiatingIdp) {
    String redirect = postLogoutRedirectUri != null ? postLogoutRedirectUri : redirectUri;
    IDToken idToken = null;
    if (encodedIdToken != null) {
        try {
            idToken = tokenManager.verifyIDTokenSignature(session, encodedIdToken);
            TokenVerifier.createWithoutSignature(idToken).tokenType(TokenUtil.TOKEN_TYPE_ID).verify();
        } catch (OAuthErrorException | VerificationException e) {
            event.event(EventType.LOGOUT);
            event.error(Errors.INVALID_TOKEN);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
        }
    }
    if (redirect != null) {
        String validatedUri;
        ClientModel client = (idToken == null || idToken.getIssuedFor() == null) ? null : realm.getClientByClientId(idToken.getIssuedFor());
        if (client != null) {
            validatedUri = RedirectUtils.verifyRedirectUri(session, redirect, client);
        } else {
            validatedUri = RedirectUtils.verifyRealmRedirectUri(session, redirect);
        }
        if (validatedUri == null) {
            event.event(EventType.LOGOUT);
            event.detail(Details.REDIRECT_URI, redirect);
            event.error(Errors.INVALID_REDIRECT_URI);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
        }
        redirect = validatedUri;
    }
    UserSessionModel userSession = null;
    if (idToken != null) {
        try {
            userSession = session.sessions().getUserSession(realm, idToken.getSessionState());
            if (userSession != null) {
                checkTokenIssuedAt(idToken, userSession);
            }
        } catch (OAuthErrorException e) {
            event.event(EventType.LOGOUT);
            event.error(Errors.INVALID_TOKEN);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
        }
    }
    // authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false);
    if (authResult != null) {
        userSession = userSession != null ? userSession : authResult.getSession();
        return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
    } else if (userSession != null) {
        // identity cookie is missing but there's valid id_token_hint which matches session cookie => continue with browser logout
        if (idToken != null && idToken.getSessionState().equals(AuthenticationManager.getSessionIdFromSessionCookie(session))) {
            return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
        }
        // this might happen when a backChannelLogout is already initiated from AuthenticationManager.authenticateIdentityCookie
        if (userSession.getState() != LOGGING_OUT && userSession.getState() != LOGGED_OUT) {
            // non browser logout
            event.event(EventType.LOGOUT);
            AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
            event.user(userSession.getUser()).session(userSession).success();
        }
    }
    if (redirect != null) {
        UriBuilder uriBuilder = UriBuilder.fromUri(redirect);
        if (state != null)
            uriBuilder.queryParam(OIDCLoginProtocol.STATE_PARAM, state);
        return Response.status(302).location(uriBuilder.build()).build();
    } else {
        // TODO Empty content with ok makes no sense. Should it display a page? Or use noContent?
        session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
        return Response.ok().build();
    }
}
Also used : AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) OAuthErrorException(org.keycloak.OAuthErrorException) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) UriBuilder(javax.ws.rs.core.UriBuilder) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

VerificationException (org.keycloak.common.VerificationException)41 AccessToken (org.keycloak.representations.AccessToken)17 Test (org.junit.Test)8 JWSBuilder (org.keycloak.jose.jws.JWSBuilder)8 IOException (java.io.IOException)7 ClientModel (org.keycloak.models.ClientModel)7 SignatureProvider (org.keycloak.crypto.SignatureProvider)6 SignatureVerifierContext (org.keycloak.crypto.SignatureVerifierContext)6 UserSessionModel (org.keycloak.models.UserSessionModel)6 Response (javax.ws.rs.core.Response)4 OAuthErrorException (org.keycloak.OAuthErrorException)4 JWSInput (org.keycloak.jose.jws.JWSInput)4 UserModel (org.keycloak.models.UserModel)4 PublicKey (java.security.PublicKey)3 TokenVerifier (org.keycloak.TokenVerifier)3 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)3 IDToken (org.keycloak.representations.IDToken)3 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)3 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)3 SAMLDocumentHolder (org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder)3