org.keycloak.common.VerificationException Java Examples

The following examples show how to use org.keycloak.common.VerificationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Verifies whether the client denoted by client ID in token's {@code iss} ({@code issuedFor})
 * field both exists and is enabled.
 */
public static <T extends JsonWebToken> void checkIsClientValid(T token, ActionTokenContext<T> context) throws VerificationException {
    String clientId = token.getIssuedFor();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    ClientModel client = authSession == null ? null : authSession.getClient();

    try {
        checkIsClientValid(context.getSession(), client);

        if (clientId != null && ! Objects.equals(client.getClientId(), clientId)) {
            throw new ExplainedTokenVerificationException(token, Errors.CLIENT_NOT_FOUND, Messages.UNKNOWN_LOGIN_REQUESTER);
        }
    } catch (ExplainedVerificationException ex) {
        throw new ExplainedTokenVerificationException(token, ex);
    }
}
 
Example #2
Source File: AdapterTokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verify access token and ID token. Typically called after successful tokenResponse is received from Keycloak
 *
 * @param accessTokenString
 * @param idTokenString
 * @param deployment
 * @return verified and parsed accessToken and idToken
 * @throws VerificationException
 */
public static VerifiedTokens verifyTokens(String accessTokenString, String idTokenString, KeycloakDeployment deployment) throws VerificationException {
    // Adapters currently do most of the checks including signature etc on the access token
    TokenVerifier<AccessToken> tokenVerifier = createVerifier(accessTokenString, deployment, true, AccessToken.class);
    AccessToken accessToken = tokenVerifier.verify().getToken();

    if (idTokenString != null) {
        // Don't verify signature again on IDToken
        IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class).getToken();
        TokenVerifier<IDToken> idTokenVerifier = TokenVerifier.createWithoutSignature(idToken);

        // Always verify audience and azp on IDToken
        idTokenVerifier.audience(deployment.getResourceName());
        idTokenVerifier.issuedFor(deployment.getResourceName());

        idTokenVerifier.verify();
        return new VerifiedTokens(accessToken, idToken);
    } else {
        return new VerifiedTokens(accessToken, null);
    }
}
 
Example #3
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotBeforeBad() {
    token.notBefore(Time.currentTime() + 100);

    String encoded = new JWSBuilder()
            .jsonContent(token)
            .rsa256(idpPair.getPrivate());

    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
        Assert.fail();
    } catch (VerificationException ignored) {
        System.out.println(ignored.getMessage());
    }
}
 
Example #4
Source File: KeycloakSpringAdapterUtils.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RefreshableKeycloakSecurityContext} from the given {@link KeycloakDeployment} and {@link AccessTokenResponse}.
 *
 * @param deployment the <code>KeycloakDeployment</code> for which to create a <code>RefreshableKeycloakSecurityContext</code> (required)
 * @param accessTokenResponse the <code>AccessTokenResponse</code> from which to create a RefreshableKeycloakSecurityContext (required)
 *
 * @return a <code>RefreshableKeycloakSecurityContext</code> created from the given <code>accessTokenResponse</code>
 * @throws VerificationException if the given <code>AccessTokenResponse</code> contains an invalid {@link IDToken}
 */
public static RefreshableKeycloakSecurityContext createKeycloakSecurityContext(KeycloakDeployment deployment, AccessTokenResponse accessTokenResponse) throws VerificationException {
    String tokenString = accessTokenResponse.getToken();
    String idTokenString = accessTokenResponse.getIdToken();
    AccessToken accessToken = RSATokenVerifier
            .verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl());
    IDToken idToken;

    try {
        JWSInput input = new JWSInput(idTokenString);
        idToken = input.readJsonContent(IDToken.class);
    } catch (JWSInputException e) {
        throw new VerificationException("Unable to verify ID token", e);
    }

    // FIXME: does it make sense to pass null for the token store?
    return new RefreshableKeycloakSecurityContext(deployment, null, tokenString, accessToken, idTokenString, idToken, accessTokenResponse.getRefreshToken());
}
 
Example #5
Source File: KeycloakOauthPolicy.java    From apiman-plugins with Apache License 2.0 6 votes vote down vote up
private Holder<Boolean> doTokenAuth(Holder<Boolean> successStatus, ApiRequest request,
        IPolicyContext context, KeycloakOauthConfigBean config, IPolicyChain<ApiRequest> chain,
        String rawToken) {
    try {
        AccessToken parsedToken = RSATokenVerifier.verifyToken(rawToken, config.getRealmCertificate()
                .getPublicKey(), config.getRealm());

        delegateKerberosTicket(request, config, parsedToken);
        forwardHeaders(request, config, rawToken, parsedToken);
        stripAuthTokens(request, config);
        forwardAuthRoles(context, config, parsedToken);

        RequestMetric metric = context.getAttribute(PolicyContextKeys.REQUEST_METRIC, (RequestMetric) null);
        if (metric != null) {
            metric.setUser(parsedToken.getPreferredUsername());
        }

        return successStatus.setValue(true);
    } catch (VerificationException e) {
        System.out.println(e);
        chain.doFailure(failureFactory.verificationException(context, e));
        return successStatus.setValue(false);
    }
}
 
Example #6
Source File: KeycloakDirectAccessGrantService.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
@Override
public RefreshableKeycloakSecurityContext login(String username, String password) throws VerificationException {

    final MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    final HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    body.set("username", username);
    body.set("password", password);
    body.set(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);

    AccessTokenResponse response = template.postForObject(keycloakDeployment.getTokenUrl(), new HttpEntity<>(body, headers), AccessTokenResponse.class);

    return KeycloakSpringAdapterUtils.createKeycloakSecurityContext(keycloakDeployment, response);
}
 
Example #7
Source File: AdapterTokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Creates verifier, initializes it from the KeycloakDeployment and adds the publicKey and some default basic checks (activeness and tokenType). Useful if caller wants to add/remove/update
 * some checks
 *
 * @param tokenString
 * @param deployment
 * @param withDefaultChecks
 * @param tokenClass
 * @param <T>
 * @return tokenVerifier
 * @throws VerificationException
 */
public static <T extends JsonWebToken> TokenVerifier<T> createVerifier(String tokenString, KeycloakDeployment deployment, boolean withDefaultChecks, Class<T> tokenClass) throws VerificationException {
    TokenVerifier<T> tokenVerifier = TokenVerifier.create(tokenString, tokenClass);

    if (withDefaultChecks) {
        tokenVerifier
                .withDefaultChecks()
                .realmUrl(deployment.getRealmInfoUrl());
    }

    String kid = tokenVerifier.getHeader().getKeyId();
    PublicKey publicKey = getPublicKey(kid, deployment);
    tokenVerifier.publicKey(publicKey);

    return tokenVerifier;
}
 
Example #8
Source File: ProductServiceAccountServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setTokens(HttpServletRequest req, KeycloakDeployment deployment, AccessTokenResponse tokenResponse) throws IOException, VerificationException {
    String token = tokenResponse.getToken();
    String refreshToken = tokenResponse.getRefreshToken();
    AdapterTokenVerifier.VerifiedTokens parsedTokens = AdapterTokenVerifier.verifyTokens(token, tokenResponse.getIdToken(), deployment);
    AccessToken tokenParsed = parsedTokens.getAccessToken();
    req.getSession().setAttribute(TOKEN, token);
    req.getSession().setAttribute(REFRESH_TOKEN, refreshToken);
    req.getSession().setAttribute(TOKEN_PARSED, tokenParsed);
}
 
Example #9
Source File: OAuthClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public <T extends JsonWebToken> T verifyToken(String token, Class<T> clazz) {
    try {
        TokenVerifier<T> verifier = TokenVerifier.create(token, clazz);
        String kid = verifier.getHeader().getKeyId();
        String algorithm = verifier.getHeader().getAlgorithm().name();
        KeyWrapper key = getRealmPublicKey(realm, algorithm, kid);
        AsymmetricSignatureVerifierContext verifierContext;
        switch (algorithm) {
            case Algorithm.ES256:
            case Algorithm.ES384:
            case Algorithm.ES512:
                verifierContext = new ServerECDSASignatureVerifierContext(key);
                break;
            default:
                verifierContext = new AsymmetricSignatureVerifierContext(key);
        }
        verifier.verifierContext(verifierContext);
        verifier.verify();
        return verifier.getToken();
    } catch (VerificationException e) {
        throw new RuntimeException("Failed to decode token", e);
    }
}
 
Example #10
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean isUserValid(KeycloakSession session, RealmModel realm, AccessToken token, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    if (user == null) {
        return false;
    }
    if (!user.isEnabled()) {
        return false;
    }
    try {
        TokenVerifier.createWithoutSignature(token)
                .withChecks(NotBeforeCheck.forModel(session ,realm, user))
                .verify();
    } catch (VerificationException e) {
        return false;
    }

    if (token.getIssuedAt() + 1 < userSession.getStarted()) {
        return false;
    }
    return true;
}
 
Example #11
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an optional predicate from a predicate that will proceed with check but always pass.
 * @param <T>
 * @param mandatoryPredicate
 * @return
 */
public static <T extends JsonWebToken> Predicate<T> optional(final Predicate<T> mandatoryPredicate) {
    return new Predicate<T>() {
        @Override
        public boolean test(T t) throws VerificationException {
            try {
                if (! mandatoryPredicate.test(t)) {
                    LOG.finer("[optional] predicate failed: " + mandatoryPredicate);
                }

                return true;
            } catch (VerificationException ex) {
                LOG.log(Level.FINER, "[optional] predicate " + mandatoryPredicate + " failed.", ex);
                return true;
            }
        }
    };
}
 
Example #12
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 *  Verifies whether the user given by ID both exists in the current realm. If yes,
 *  it optionally also injects the user using the given function (e.g. into session context).
 */
public static void checkIsUserValid(KeycloakSession session, RealmModel realm, String userId, Consumer<UserModel> userSetter) throws VerificationException {
    UserModel user = userId == null ? null : session.users().getUserById(userId, realm);

    if (user == null) {
        throw new ExplainedVerificationException(Errors.USER_NOT_FOUND, Messages.INVALID_USER);
    }

    if (! user.isEnabled()) {
        throw new ExplainedVerificationException(Errors.USER_DISABLED, Messages.INVALID_USER);
    }

    if (userSetter != null) {
        userSetter.accept(user);
    }
}
 
Example #13
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the authentication session has not yet been converted to user session, in other words
 * that the user has not yet completed authentication and logged in.
 */
public static <T extends JsonWebToken> void checkNotLoggedInYet(ActionTokenContext<T> context, AuthenticationSessionModel authSessionFromCookie, String authSessionId) throws VerificationException {
    if (authSessionId == null) {
        return;
    }

    UserSessionModel userSession = context.getSession().sessions().getUserSession(context.getRealm(), authSessionId);
    boolean hasNoRequiredActions =
      (userSession == null || userSession.getUser().getRequiredActions() == null || userSession.getUser().getRequiredActions().isEmpty())
      &&
      (authSessionFromCookie == null || authSessionFromCookie.getRequiredActions() == null || authSessionFromCookie.getRequiredActions().isEmpty());

    if (userSession != null && hasNoRequiredActions) {
        LoginFormsProvider loginForm = context.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(context.getAuthenticationSession())
          .setSuccess(Messages.ALREADY_LOGGED_IN);

        if (context.getSession().getContext().getClient() == null) {
            loginForm.setAttribute(Constants.SKIP_LINK, true);
        }

        throw new LoginActionsServiceException(loginForm.createInfoPage());
    }
}
 
Example #14
Source File: ClientECDSASignatureVerifierContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static KeyWrapper getKey(KeycloakSession session, ClientModel client, JWSInput input) throws VerificationException {
    KeyWrapper key = PublicKeyStorageManager.getClientPublicKeyWrapper(session, client, input);
    if (key == null) {
        throw new VerificationException("Key not found");
    }
    return key;
}
 
Example #15
Source File: ServerECDSASignatureVerifierContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #16
Source File: ClientECDSASignatureVerifierContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #17
Source File: PreAuthActionsHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected JWSInput verifyAdminRequest() throws Exception {
    if (!facade.getRequest().isSecure() && deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
        log.warn("SSL is required for adapter admin action");
        facade.getResponse().sendError(403, "ssl required");
        return null;
    }
    String token = StreamUtil.readString(facade.getRequest().getInputStream());
    if (token == null) {
        log.warn("admin request failed, no token");
        facade.getResponse().sendError(403, "no token");
        return null;
    }

    try {
        // Check just signature. Other things checked in validateAction
        TokenVerifier tokenVerifier = AdapterTokenVerifier.createVerifier(token, deployment, false, JsonWebToken.class);
        tokenVerifier.verify();
        return new JWSInput(token);
    } catch (VerificationException ignore) {
        log.warn("admin request failed, unable to verify token: "  + ignore.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(ignore.getMessage(), ignore);
        }

        facade.getResponse().sendError(403, "token failed verification");
        return null;
    }
}
 
Example #18
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void verifyRedirectBindingSignature(String paramKey, KeyLocator keyLocator, String keyId) throws VerificationException {
    String request = facade.getRequest().getQueryParamValue(paramKey);
    String algorithm = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);
    String signature = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY);
    String decodedAlgorithm = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);

    if (request == null) {
        throw new VerificationException("SAML Request was null");
    }
    if (algorithm == null) throw new VerificationException("SigAlg was null");
    if (signature == null) throw new VerificationException("Signature was null");

    // Shibboleth doesn't sign the document for redirect binding.
    // todo maybe a flag?

    String relayState = facade.getRequest().getQueryParamValue(GeneralConstants.RELAY_STATE);
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromPath("/")
            .queryParam(paramKey, request);
    if (relayState != null) {
        builder.queryParam(GeneralConstants.RELAY_STATE, relayState);
    }
    builder.queryParam(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY, algorithm);
    String rawQuery = builder.build().getRawQuery();

    try {
        //byte[] decodedSignature = RedirectBindingUtil.urlBase64Decode(signature);
        byte[] decodedSignature = Base64.decode(signature);
        byte[] rawQueryBytes = rawQuery.getBytes("UTF-8");

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.getFromXmlMethod(decodedAlgorithm);

        if (! validateRedirectBindingSignature(signatureAlgorithm, rawQueryBytes, decodedSignature, keyLocator, keyId)) {
            throw new VerificationException("Invalid query param signature");
        }
    } catch (Exception e) {
        throw new VerificationException(e);
    }
}
 
Example #19
Source File: KeycloakInstalled.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void parseAccessToken(AccessTokenResponse tokenResponse) throws VerificationException {
    this.tokenResponse = tokenResponse;
    tokenString = tokenResponse.getToken();
    refreshToken = tokenResponse.getRefreshToken();
    idTokenString = tokenResponse.getIdToken();

    AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, idTokenString, deployment);
    token = tokens.getAccessToken();
    idToken = tokens.getIdToken();
}
 
Example #20
Source File: AdapterTokenVerifier.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies bearer token. Typically called when bearer token (access token) is sent to the service, which wants to verify it. Hence it also checks the audience in the token.
 *
 * @param tokenString
 * @param deployment
 * @return
 * @throws VerificationException
 */
public static AccessToken verifyToken(String tokenString, KeycloakDeployment deployment) throws VerificationException {
    TokenVerifier<AccessToken> tokenVerifier = createVerifier(tokenString, deployment, true, AccessToken.class);

    // Verify audience of bearer-token
    if (deployment.isVerifyTokenAudience()) {
        tokenVerifier.audience(deployment.getResourceName());
    }

    return tokenVerifier.verify().getToken();
}
 
Example #21
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpirationGood() throws Exception {
    token.expiration(Time.currentTime() + 100);

    String encoded = new JWSBuilder()
            .jsonContent(token)
            .rsa256(idpPair.getPrivate());

    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
    } catch (VerificationException ignored) {
        throw ignored;
    }
}
 
Example #22
Source File: AsymmetricSignatureVerifierContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(byte[] data, byte[] signature) throws VerificationException {
    try {
        Signature verifier = Signature.getInstance(JavaAlgorithm.getJavaAlgorithm(key.getAlgorithm()));
        verifier.initVerify((PublicKey) key.getPublicKey());
        verifier.update(data);
        return verifier.verify(signature);
    } catch (Exception e) {
        throw new VerificationException("Signing failed", e);
    }
}
 
Example #23
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response handleActionTokenVerificationException(ActionTokenContext<?> tokenContext, VerificationException ex, String eventError, String errorMessage) {
    if (tokenContext != null && tokenContext.getAuthenticationSession() != null) {
        new AuthenticationSessionManager(session).removeAuthenticationSession(realm, tokenContext.getAuthenticationSession(), true);
    }

    event
      .detail(Details.REASON, ex == null ? "<unknown>" : ex.getMessage())
      .error(eventError == null ? Errors.INVALID_CODE : eventError);
    return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, errorMessage == null ? Messages.INVALID_CODE : errorMessage);
}
 
Example #24
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <T extends JsonWebToken> ActionTokenHandler<T> resolveActionTokenHandler(String actionId) throws VerificationException {
    if (actionId == null) {
        throw new VerificationException("Action token operation not set");
    }
    ActionTokenHandler<T> handler = session.getProvider(ActionTokenHandler.class, actionId);

    if (handler == null) {
        throw new VerificationException("Invalid action token operation");
    }
    return handler;
}
 
Example #25
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static <T extends JsonWebToken & ActionTokenKeyModel> void checkTokenWasNotUsedYet(T token, ActionTokenContext<T> context) throws VerificationException {
    ActionTokenStoreProvider actionTokenStore = context.getSession().getProvider(ActionTokenStoreProvider.class);

    if (actionTokenStore.get(token) != null) {
        throw new ExplainedTokenVerificationException(token, Errors.EXPIRED_CODE, Messages.EXPIRED_ACTION);
    }
}
 
Example #26
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *  This check verifies that current authentication session is consistent with the one specified in token.
 *  Examples:
 *  <ul>
 *      <li>1. Email from administrator with reset e-mail - token does not contain auth session ID</li>
 *      <li>2. Email from "verify e-mail" step within flow - token contains auth session ID.</li>
 *      <li>3. User clicked the link in an e-mail and gets to a new browser - authentication session cookie is not set</li>
 *      <li>4. User clicked the link in an e-mail while having authentication running - authentication session cookie
 *             is already set in the browser</li>
 *  </ul>
 *
 *  <ul>
 *      <li>For combinations 1 and 3, 1 and 4, and 2 and 3: Requests next step</li>
 *      <li>For combination 2 and 4:
 *          <ul>
 *          <li>If the auth session IDs from token and cookie match, pass</li>
 *          <li>Else if the auth session from cookie was forked and its parent auth session ID
 *              matches that of token, replaces current auth session with that of parent and passes</li>
 *          <li>Else requests restart by throwing RestartFlow exception</li>
 *          </ul>
 *      </li>
 *  </ul>
 *
 *  When the check passes, it also sets the authentication session in token context accordingly.
 *
 *  @param <T>
 */
public static <T extends JsonWebToken> boolean doesAuthenticationSessionFromCookieMatchOneFromToken(
        ActionTokenContext<T> context, AuthenticationSessionModel authSessionFromCookie, String authSessionCompoundIdFromToken) throws VerificationException {
    if (authSessionCompoundIdFromToken == null) {
        return false;
    }


    if (Objects.equals(AuthenticationSessionCompoundId.fromAuthSession(authSessionFromCookie).getEncodedId(), authSessionCompoundIdFromToken)) {
        context.setAuthenticationSession(authSessionFromCookie, false);
        return true;
    }

    // Check if it's forked session. It would have same parent (rootSession) as our browser authenticationSession
    String parentTabId = authSessionFromCookie.getAuthNote(AuthenticationProcessor.FORKED_FROM);
    if (parentTabId == null) {
        return false;
    }


    AuthenticationSessionModel authSessionFromParent = authSessionFromCookie.getParentSession().getAuthenticationSession(authSessionFromCookie.getClient(), parentTabId);
    if (authSessionFromParent == null) {
        return false;
    }

    // It's the correct browser. We won't continue login
    // from the login form (browser flow) but from the token's flow
    // Don't expire KC_RESTART cookie at this point
    LOG.debugf("Switched to forked tab: %s from: %s . Root session: %s", authSessionFromParent.getTabId(), authSessionFromCookie.getTabId(), authSessionFromCookie.getParentSession().getId());

    context.setAuthenticationSession(authSessionFromParent, false);
    context.setExecutionId(authSessionFromParent.getAuthNote(AuthenticationProcessor.LAST_PROCESSED_EXECUTION));

    return true;
}
 
Example #27
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    if (redirectUri == null) {
        return true;
    }

    ClientModel client = context.getAuthenticationSession().getClient();

    if (RedirectUtils.verifyRedirectUri(context.getSession(), redirectUri, client) == null) {
        throw new ExplainedTokenVerificationException(t, Errors.INVALID_REDIRECT_URI, Messages.INVALID_REDIRECT_URI);
    }

    return true;
}
 
Example #28
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *  Verifies whether the user given by ID both exists in the current realm. If yes,
 *  it optionally also injects the user using the given function (e.g. into session context).
 */
public static <T extends JsonWebToken & ActionTokenKeyModel> void checkIsUserValid(T token, ActionTokenContext<T> context) throws VerificationException {
    try {
        checkIsUserValid(context.getSession(), context.getRealm(), token.getUserId(), context.getAuthenticationSession()::setAuthenticatedUser);
    } catch (ExplainedVerificationException ex) {
        throw new ExplainedTokenVerificationException(token, ex);
    }
}
 
Example #29
Source File: KeycloakDirectAccessGrantAuthenticationProvider.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (deployment == null) {
        deployment = resolver.resolve(null);
    }
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    if (token.getCredentials() == null) {
        throw new AuthenticationCredentialsNotFoundException("");
    }
    try {
        return directGrantAuth(token.getName(), token.getCredentials().toString());
    } catch (VerificationException|IOException e) {
        throw new KeycloakAuthenticationException(e.getMessage(), e);
    }
}
 
Example #30
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpirationBad() {
    token.expiration(Time.currentTime() - 100);

    String encoded = new JWSBuilder()
            .jsonContent(token)
            .rsa256(idpPair.getPrivate());

    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
        Assert.fail();
    } catch (VerificationException ignored) {
    }
}