org.keycloak.representations.JsonWebToken Java Examples

The following examples show how to use org.keycloak.representations.JsonWebToken. 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: TokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a predicate that will proceed with checks of the given predicates
 * and will pass if and only if at least one of the given predicates passes.
 * @param <T>
 * @param predicates
 * @return
 */
public static <T extends JsonWebToken> Predicate<T> alternative(final Predicate<? super T>... predicates) {
    return new Predicate<T>() {
        @Override
        public boolean test(T t) {
            for (Predicate<? super T> predicate : predicates) {
                try {
                    if (predicate.test(t)) {
                        return true;
                    }

                    LOG.finer("[alternative] predicate failed: " + predicate);
                } catch (VerificationException ex) {
                    LOG.log(Level.FINER, "[alternative] predicate " + predicate + " failed.", ex);
                }
            }

            return false;
        }
    };
}
 
Example #3
Source File: AuthUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String getSignedRequestToken(String keystore, String storePass, String keyPass, String alias, int sigLifetime, String clientId, String realmInfoUrl) {

        KeyPair keypair = KeystoreUtil.loadKeyPairFromKeystore(keystore, storePass, keyPass, alias, KeystoreUtil.KeystoreFormat.JKS);

        JsonWebToken reqToken = new JsonWebToken();
        reqToken.id(UUID.randomUUID().toString());
        reqToken.issuer(clientId);
        reqToken.subject(clientId);
        reqToken.audience(realmInfoUrl);

        int now = Time.currentTime();
        reqToken.issuedAt(now);
        reqToken.expiration(now + sigLifetime);
        reqToken.notBefore(now);

        String signedRequestToken = new JWSBuilder()
                .jsonContent(reqToken)
                .rsa256(keypair.getPrivate());
        return signedRequestToken;
    }
 
Example #4
Source File: AuthorizationAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void testResourceServerAsAudience(String clientId, String resourceServerClientId, String authzConfigFile) throws Exception {
    AuthzClient authzClient = getAuthzClient(authzConfigFile);
    PermissionRequest request = new PermissionRequest();

    request.setResourceId("Resource A");

    String accessToken = new OAuthClient().realm("authz-test").clientId(clientId).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    String ticket = authzClient.protection().permission().create(request).getTicket();

    // Ticket is opaque to client or resourceServer. The audience should be just an authorization server itself
    JsonWebToken ticketDecoded = JsonSerialization.readValue(new JWSInput(ticket).getContent(), JsonWebToken.class);
    Assert.assertFalse(ticketDecoded.hasAudience(clientId));
    Assert.assertFalse(ticketDecoded.hasAudience(resourceServerClientId));

    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(new AuthorizationRequest(ticket));

    assertNotNull(response.getToken());
    AccessToken rpt = toAccessToken(response.getToken());
    assertEquals(resourceServerClientId, rpt.getAudience()[0]);
}
 
Example #5
Source File: AuthUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String getSignedRequestToken(String keystore, String storePass, String keyPass, String alias, int sigLifetime, String clientId, String realmInfoUrl) {

        KeyPair keypair = KeystoreUtil.loadKeyPairFromKeystore(keystore, storePass, keyPass, alias, KeystoreUtil.KeystoreFormat.JKS);

        JsonWebToken reqToken = new JsonWebToken();
        reqToken.id(UUID.randomUUID().toString());
        reqToken.issuer(clientId);
        reqToken.subject(clientId);
        reqToken.audience(realmInfoUrl);

        int now = Time.currentTime();
        reqToken.issuedAt(now);
        reqToken.expiration(now + sigLifetime);
        reqToken.notBefore(now);

        String signedRequestToken = new JWSBuilder()
                .jsonContent(reqToken)
                .rsa256(keypair.getPrivate());
        return signedRequestToken;
    }
 
Example #6
Source File: DefaultHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);

    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, token.getIssuer());

    ClientRegistration clientReg = ClientRegistration.create().url(AUTH_SERVER_ROOT, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));

    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);

    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, registrationToken.getIssuer());
}
 
Example #7
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);

    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, token.getIssuer());

    ClientRegistration clientReg = ClientRegistration.create().url(authServerUrl, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));

    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);

    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, registrationToken.getIssuer());
}
 
Example #8
Source File: JsonWebTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAudience() {
    // Token with no audience
    JsonWebToken s = new JsonWebToken();
    s.addAudience("audience-1");
    assertArrayEquals(new String[] { "audience-1"}, s.getAudience());

    // Add to existing
    s.addAudience("audience-2");
    assertArrayEquals(new String[]{"audience-1", "audience-2"}, s.getAudience());

    s.addAudience("audience-3");
    assertArrayEquals(new String[]{"audience-1", "audience-2", "audience-3"}, s.getAudience());

    // Add existing. Shouldn't be added as it's already there
    s.addAudience("audience-2");
    assertArrayEquals(new String[]{"audience-1", "audience-2", "audience-3"}, s.getAudience());
}
 
Example #9
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 #10
Source File: JWTClientSecretCredentialsProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    // According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication">OIDC's client authentication spec</a>,
    // JWT claims is the same as one by private_key_jwt

    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    // the same as in KEYCLOAK-2986, JWTClientCredentialsProvider's timeout field
    reqToken.expiration(now + 10);
    reqToken.notBefore(now);
    return reqToken;
}
 
Example #11
Source File: GoogleIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected JsonWebToken validateToken(final String encodedToken, final boolean ignoreAudience) {
    JsonWebToken token = super.validateToken(encodedToken, ignoreAudience);
    String hostedDomain = ((GoogleIdentityProviderConfig) getConfig()).getHostedDomain();

    if (hostedDomain == null) {
        return token;
    }

    Object receivedHdParam = token.getOtherClaims().get(OIDC_PARAMETER_HOSTED_DOMAINS);

    if (receivedHdParam == null) {
        throw new IdentityBrokerException("Identity token does not contain hosted domain parameter.");
    }

    if (hostedDomain.equals("*") || hostedDomain.equals(receivedHdParam))  {
        return token;
    }

    throw new IdentityBrokerException("Hosted domain does not match.");
}
 
Example #12
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 #13
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    if (expectedAudience == null) {
        throw new VerificationException("Missing expectedAudience");
    }

    String[] audience = t.getAudience();
    if (audience == null) {
        throw new VerificationException("No audience in the token");
    }

    if (t.hasAudience(expectedAudience)) {
        return true;
    }

    throw new VerificationException("Expected audience not available in the token");
}
 
Example #14
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 #15
Source File: ClaimLookup.java    From apiman-plugins with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked") // KC code - thanks.
private static Object getOtherClaimValue(JsonWebToken token, String claim) {
    String[] split = claim.split("\\.");
    Map<String, Object> jsonObject = token.getOtherClaims();
    for (int i = 0; i < split.length; i++) {
        if (i == split.length - 1) {
            return jsonObject.get(split[i]);
        } else {
            Object val = jsonObject.get(split[i]);
            if (!(val instanceof Map))
                return null;
            jsonObject = (Map<String, Object>) val;
        }
    }
    return null;
}
 
Example #16
Source File: KeycloakReflectionBuildStep.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
public void registerReflectionItems(BuildProducer<ReflectiveClassBuildItem> reflectiveItems) {
    reflectiveItems.produce(new ReflectiveClassBuildItem(true, true,
            JsonWebToken.class.getName(),
            JWSHeader.class.getName(),
            AccessToken.class.getName(),
            IDToken.class.getName(),
            RefreshToken.class.getName(),
            AccessTokenResponse.class.getName(),
            JSONWebKeySet.class.getName(),
            JWK.class.getName(),
            StringOrArrayDeserializer.class.getName(),
            AccessToken.Access.class.getName(),
            AccessToken.Authorization.class.getName(),
            AuthorizationRequest.class.getName(),
            AuthorizationResponse.class.getName(),
            PermissionRequest.class.getName(),
            PermissionResponse.class.getName(),
            PermissionTicketToken.class.getName(),
            Permission.class.getName(),
            ServerConfiguration.class.getName(),
            ResourceRepresentation.class.getName(),
            ScopeRepresentation.class.getName(),
            ResourceOwnerRepresentation.class.getName(),
            StringListMapDeserializer.class.getName(),
            StringOrArrayDeserializer.class.getName(),
            OIDCConfigurationRepresentation.class.getName()));
}
 
Example #17
Source File: JWTClientSecretCredentialsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String createSignedRequestToken(String clientId, String realmInfoUrl, String algorithm) {
    JsonWebToken jwt = createRequestToken(clientId, realmInfoUrl);
    String signedRequestToken = null;
    if (Algorithm.HS512.equals(algorithm)) {
        signedRequestToken = new JWSBuilder().jsonContent(jwt).hmac512(clientSecret);
    } else if (Algorithm.HS384.equals(algorithm)) {
        signedRequestToken = new JWSBuilder().jsonContent(jwt).hmac384(clientSecret);
    } else {
        signedRequestToken = new JWSBuilder().jsonContent(jwt).hmac256(clientSecret);
    }
    return signedRequestToken;
}
 
Example #18
Source File: JsonWebTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void isActiveShouldReturnTrueWhenBeforeTimeInFutureWithinTimeSkew() {
    int notBeforeTime = Time.currentTime() + 5;
    int allowedClockSkew = 10;
    JsonWebToken jsonWebToken = new JsonWebToken();
    jsonWebToken.notBefore(notBeforeTime);
    assertTrue(jsonWebToken.isActive(allowedClockSkew));
}
 
Example #19
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 #20
Source File: JsonWebTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void isActiveShouldReturnFalseWhenWhenBeforeTimeInFutureOutsideTimeSkew() {
    int notBeforeTime = Time.currentTime() + 10;
    int allowedClockSkew = 5;
    JsonWebToken jsonWebToken = new JsonWebToken();
    jsonWebToken.notBefore(notBeforeTime);
    assertFalse(jsonWebToken.isActive(allowedClockSkew));
}
 
Example #21
Source File: JWTClientCredentialsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + this.tokenTimeout);
    reqToken.notBefore(now);

    return reqToken;
}
 
Example #22
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected JsonWebToken generateToken() {
    JsonWebToken jwt = new JsonWebToken();
    jwt.id(KeycloakModelUtils.generateId());
    jwt.type(OAuth2Constants.JWT);
    jwt.issuer(getConfig().getClientId());
    jwt.subject(getConfig().getClientId());
    jwt.audience(getConfig().getTokenUrl());
    int expirationDelay = session.getContext().getRealm().getAccessCodeLifespan();
    jwt.expiration(Time.currentTime() + expirationDelay);
    jwt.issuedNow();
    return jwt;
}
 
Example #23
Source File: JsonWebTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void isActiveReturnFalseWhenBeforeTimeInFuture() {
    int currentTime = Time.currentTime();
    int futureTime = currentTime + 10;
    JsonWebToken jsonWebToken = new JsonWebToken();
    jsonWebToken.notBefore(futureTime);
    assertFalse(jsonWebToken.isActive());
}
 
Example #24
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    String subject = t.getSubject();
    if (subject == null) {
        throw new VerificationException("Subject missing in token");
    }

    return true;
}
 
Example #25
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    if (! t.isActive()) {
        throw new TokenNotActiveException(t, "Token is not active");
    }

    return true;
}
 
Example #26
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    if (this.realmUrl == null) {
        throw new VerificationException("Realm URL not set");
    }

    if (! this.realmUrl.equals(t.getIssuer())) {
        throw new VerificationException("Invalid token issuer. Expected '" + this.realmUrl + "', but was '" + t.getIssuer() + "'");
    }

    return true;
}
 
Example #27
Source File: ClientRegistrationTokenUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static String setupToken(JsonWebToken jwt, KeycloakSession session, RealmModel realm, String id, String type, int expiration) {
    String issuer = getIssuer(session, realm);

    jwt.type(type);
    jwt.id(id);
    jwt.issuedAt(Time.currentTime());
    jwt.expiration(expiration);
    jwt.issuer(issuer);
    jwt.audience(issuer);

    return session.tokens().encode(jwt);
}
 
Example #28
Source File: ClientRegistrationTokenUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static TokenVerification verifyToken(KeycloakSession session, RealmModel realm, String token) {
    if (token == null) {
        return TokenVerification.error(new RuntimeException("Missing token"));
    }

    String kid;
    JsonWebToken jwt;
    try {
        TokenVerifier<JsonWebToken> verifier = TokenVerifier.create(token, JsonWebToken.class)
                .withChecks(new TokenVerifier.RealmUrlCheck(getIssuer(session, realm)), TokenVerifier.IS_ACTIVE);

        SignatureVerifierContext verifierContext = session.getProvider(SignatureProvider.class, verifier.getHeader().getAlgorithm().name()).verifier(verifier.getHeader().getKeyId());
        verifier.verifierContext(verifierContext);

        kid = verifierContext.getKid();

        verifier.verify();

        jwt = verifier.getToken();
    } catch (VerificationException e) {
        return TokenVerification.error(new RuntimeException("Failed decode token", e));
    }

    if (!(TokenUtil.TOKEN_TYPE_BEARER.equals(jwt.getType()) ||
            TYPE_INITIAL_ACCESS_TOKEN.equals(jwt.getType()) ||
            TYPE_REGISTRATION_ACCESS_TOKEN.equals(jwt.getType()))) {
        return TokenVerification.error(new RuntimeException("Invalid type of token"));
    }

    return TokenVerification.success(kid, jwt);
}
 
Example #29
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 #30
Source File: TokenVerifier.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    if (! tokenType.equalsIgnoreCase(t.getType())) {
        throw new VerificationException("Token type is incorrect. Expected '" + tokenType + "' but was '" + t.getType() + "'");
    }
    return true;
}