Search in sources :

Example 21 with VerificationException

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

the class RealmAdminResource method updateRealm.

/**
 * Update the top-level information of the realm
 *
 * Any user, roles or client information in the representation
 * will be ignored.  This will only update top-level attributes of the realm.
 *
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateRealm(final RealmRepresentation rep) {
    auth.realm().requireManageRealm();
    logger.debug("updating realm: " + realm.getName());
    if (Config.getAdminRealm().equals(realm.getName()) && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) {
        return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
    }
    ReservedCharValidator.validate(rep.getRealm());
    ReservedCharValidator.validateLocales(rep.getSupportedLocales());
    try {
        if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) {
            try {
                KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
            } catch (VerificationException e) {
                return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
            }
        }
        if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) {
            try {
                X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
                if (cert == null) {
                    return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
                }
            } catch (Exception e) {
                return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
            }
        }
        boolean wasDuplicateEmailsAllowed = realm.isDuplicateEmailsAllowed();
        RepresentationToModel.updateRealm(rep, realm, session);
        // Refresh periodic sync tasks for configured federationProviders
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        realm.getUserStorageProvidersStream().forEachOrdered(fedProvider -> usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false));
        // This populates the map in DefaultKeycloakContext to be used when treating the event
        session.getContext().getUri();
        adminEvent.operation(OperationType.UPDATE).representation(StripSecretsUtils.strip(rep)).success();
        if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
            UserCache cache = session.getProvider(UserCache.class);
            if (cache != null)
                cache.clear();
        }
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Realm with same name exists");
    } catch (ModelException e) {
        return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) VerificationException(org.keycloak.common.VerificationException) UserCache(org.keycloak.models.cache.UserCache) X509Certificate(java.security.cert.X509Certificate) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BadRequestException(javax.ws.rs.BadRequestException) ParseException(java.text.ParseException) VerificationException(org.keycloak.common.VerificationException) NotFoundException(javax.ws.rs.NotFoundException) ModelException(org.keycloak.models.ModelException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 22 with VerificationException

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

the class KeycloakProxyAuthenticator method authenticateToken.

protected AuthResult authenticateToken(HttpWrapper exchange, String tokenString) throws IOException {
    Logger logger = LoggerFactory.getLogger(getClass());
    AccessToken token;
    try {
        // KeycloakBearerTokenDebug.debugToken( tokenString );
        logger.debug("Verifying token: '{}'", tokenString);
        token = RSATokenVerifier.verifyToken(tokenString, getHardcodedRealmKey(deployment), deployment.getRealmInfoUrl());
    } catch (VerificationException e) {
        logger.error("Failed to verify token", e);
        return new AuthResult(false, "invalid_token", e.getMessage());
    }
    if (token.getIssuedAt() < deployment.getNotBefore()) {
        logger.error("Stale token");
        return new AuthResult(false, "invalid_token", "Stale token");
    }
    // TODO: Not yet supported.
    // boolean verifyCaller = false;
    // if (deployment.isUseResourceRoleMappings()) {
    // verifyCaller = token.isVerifyCaller(deployment.getResourceName());
    // } else {
    // verifyCaller = token.isVerifyCaller();
    // }
    // 
    // String surrogate = null;
    // if (verifyCaller) {
    // if (token.getTrustedCertificates() == null || token.getTrustedCertificates().size() == 0) {
    // logger.warn("No trusted certificates in token");
    // sendClientCertChallenge( exchange );
    // return false;
    // }
    // 
    // // for now, we just make sure Undertow did two-way SSL
    // // assume JBoss Web verifies the client cert
    // X509Certificate[] chain = new X509Certificate[0];
    // try {
    // chain = exchange.getCertificateChain();
    // } catch (Exception ignore) {
    // 
    // }
    // if (chain == null || chain.length == 0) {
    // logger.warn("No certificates provided by undertow to verify the caller");
    // sendClientCertChallenge( exchange );
    // return false;
    // }
    // surrogate = chain[0].getSubjectDN().getName();
    // }
    logger.debug("Token verification succeeded!");
    return new AuthResult(true);
}
Also used : AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) Logger(org.slf4j.Logger)

Example 23 with VerificationException

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

the class MqttConnection method getAuthContext.

public AuthContext getAuthContext() {
    AuthContext authContext;
    if (!credentials) {
        return null;
    }
    try {
        AccessToken accessToken = AdapterTokenVerifier.verifyToken(getAccessToken(), identityProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID));
        authContext = accessToken != null ? new AccessTokenAuthContext(realm, accessToken) : null;
    } catch (VerificationException e) {
        LOG.log(Level.INFO, "Couldn't verify token: " + this, e);
        return null;
    }
    return authContext;
}
Also used : AccessToken(org.keycloak.representations.AccessToken) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) AuthContext(org.openremote.container.security.AuthContext) VerificationException(org.keycloak.common.VerificationException) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext)

Example 24 with VerificationException

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

the class BearerTokenRequestAuthenticator method authenticateToken.

protected AuthOutcome authenticateToken(HttpFacade exchange, String tokenString) {
    log.debug("Verifying access_token");
    if (log.isTraceEnabled()) {
        try {
            JWSInput jwsInput = new JWSInput(tokenString);
            String wireString = jwsInput.getWireString();
            log.tracef("\taccess_token: %s", wireString.substring(0, wireString.lastIndexOf(".")) + ".signature");
        } catch (JWSInputException e) {
            log.errorf(e, "Failed to parse access_token: %s", tokenString);
        }
    }
    try {
        token = AdapterTokenVerifier.verifyToken(tokenString, deployment);
    } catch (VerificationException e) {
        log.debug("Failed to verify token");
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "invalid_token", e.getMessage());
        return AuthOutcome.FAILED;
    }
    if (token.getIssuedAt() < deployment.getNotBefore()) {
        log.debug("Stale token");
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.STALE_TOKEN, "invalid_token", "Stale token");
        return AuthOutcome.FAILED;
    }
    boolean verifyCaller = false;
    if (deployment.isUseResourceRoleMappings()) {
        verifyCaller = token.isVerifyCaller(deployment.getResourceName());
    } else {
        verifyCaller = token.isVerifyCaller();
    }
    surrogate = null;
    if (verifyCaller) {
        if (token.getTrustedCertificates() == null || token.getTrustedCertificates().isEmpty()) {
            log.warn("No trusted certificates in token");
            challenge = clientCertChallenge();
            return AuthOutcome.FAILED;
        }
        // for now, we just make sure Undertow did two-way SSL
        // assume JBoss Web verifies the client cert
        X509Certificate[] chain = new X509Certificate[0];
        try {
            chain = exchange.getCertificateChain();
        } catch (Exception ignore) {
        }
        if (chain == null || chain.length == 0) {
            log.warn("No certificates provided by undertow to verify the caller");
            challenge = clientCertChallenge();
            return AuthOutcome.FAILED;
        }
        surrogate = chain[0].getSubjectDN().getName();
    }
    log.debug("successful authorized");
    return AuthOutcome.AUTHENTICATED;
}
Also used : JWSInputException(org.keycloak.jose.jws.JWSInputException) VerificationException(org.keycloak.common.VerificationException) JWSInput(org.keycloak.jose.jws.JWSInput) X509Certificate(javax.security.cert.X509Certificate) VerificationException(org.keycloak.common.VerificationException) JWSInputException(org.keycloak.jose.jws.JWSInputException)

Example 25 with VerificationException

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

the class OAuthRequestAuthenticator method resolveCode.

/**
 * Start or continue the oauth login process.
 * <p/>
 * if code query parameter is not present, then browser is redirected to authUrl.  The redirect URL will be
 * the URL of the current request.
 * <p/>
 * If code query parameter is present, then an access token is obtained by invoking a secure request to the codeUrl.
 * If the access token is obtained, the browser is again redirected to the current request URL, but any OAuth
 * protocol specific query parameters are removed.
 *
 * @return null if an access token was obtained, otherwise a challenge is returned
 */
protected AuthChallenge resolveCode(String code) {
    // abort if not HTTPS
    if (!isRequestSecure() && deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
        log.error("Adapter requires SSL. Request: " + facade.getRequest().getURI());
        return challenge(403, OIDCAuthenticationError.Reason.SSL_REQUIRED, null);
    }
    log.debug("checking state cookie for after code");
    AuthChallenge challenge = checkStateCookie();
    if (challenge != null)
        return challenge;
    AccessTokenResponse tokenResponse = null;
    strippedOauthParametersRequestUri = rewrittenRedirectUri(stripOauthParametersFromRedirect());
    try {
        // For COOKIE store we don't have httpSessionId and single sign-out won't be available
        String httpSessionId = deployment.getTokenStore() == TokenStore.SESSION ? reqAuthenticator.changeHttpSessionId(true) : null;
        tokenResponse = ServerRequest.invokeAccessCodeToToken(deployment, code, strippedOauthParametersRequestUri, httpSessionId);
    } catch (ServerRequest.HttpFailure failure) {
        log.error("failed to turn code into token");
        log.error("status from server: " + failure.getStatus());
        if (failure.getError() != null && !failure.getError().trim().isEmpty()) {
            log.error("   " + failure.getError());
        }
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    } catch (IOException e) {
        log.error("failed to turn code into token", e);
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    }
    tokenString = tokenResponse.getToken();
    refreshToken = tokenResponse.getRefreshToken();
    idTokenString = tokenResponse.getIdToken();
    log.debug("Verifying tokens");
    if (log.isTraceEnabled()) {
        logToken("\taccess_token", tokenString);
        logToken("\tid_token", idTokenString);
        logToken("\trefresh_token", refreshToken);
    }
    try {
        AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, idTokenString, deployment);
        token = tokens.getAccessToken();
        idToken = tokens.getIdToken();
        log.debug("Token Verification succeeded!");
    } catch (VerificationException e) {
        log.error("failed verification of token: " + e.getMessage());
        return challenge(403, OIDCAuthenticationError.Reason.INVALID_TOKEN, null);
    }
    if (tokenResponse.getNotBeforePolicy() > deployment.getNotBefore()) {
        deployment.updateNotBefore(tokenResponse.getNotBeforePolicy());
    }
    if (token.getIssuedAt() < deployment.getNotBefore()) {
        log.error("Stale token");
        return challenge(403, OIDCAuthenticationError.Reason.STALE_TOKEN, null);
    }
    log.debug("successful authenticated");
    return null;
}
Also used : AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) VerificationException(org.keycloak.common.VerificationException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

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