Search in sources :

Example 31 with JWSInput

use of org.keycloak.jose.jws.JWSInput 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 32 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class OAuthRequestAuthenticator method logToken.

private void logToken(String name, String token) {
    try {
        JWSInput jwsInput = new JWSInput(token);
        String wireString = jwsInput.getWireString();
        log.tracef("\t%s: %s", name, wireString.substring(0, wireString.lastIndexOf(".")) + ".signature");
    } catch (JWSInputException e) {
        log.errorf(e, "Failed to parse %s: %s", name, token);
    }
}
Also used : JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput)

Example 33 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class CookieTokenStore method getPrincipalFromCookie.

public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore) {
    OIDCHttpFacade.Cookie cookie = facade.getRequest().getCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE);
    if (cookie == null) {
        log.debug("Not found adapter state cookie in current request");
        return null;
    }
    String cookieVal = cookie.getValue();
    String[] tokens = cookieVal.split(DELIM);
    if (tokens.length != 3) {
        log.warnf("Invalid format of %s cookie. Count of tokens: %s, expected 3", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, tokens.length);
        return null;
    }
    String accessTokenString = tokens[0];
    String idTokenString = tokens[1];
    String refreshTokenString = tokens[2];
    try {
        // Skip check if token is active now. It's supposed to be done later by the caller
        TokenVerifier<AccessToken> tokenVerifier = AdapterTokenVerifier.createVerifier(accessTokenString, deployment, true, AccessToken.class).checkActive(false).verify();
        AccessToken accessToken = tokenVerifier.getToken();
        IDToken idToken;
        if (idTokenString != null && idTokenString.length() > 0) {
            try {
                JWSInput input = new JWSInput(idTokenString);
                idToken = input.readJsonContent(IDToken.class);
            } catch (JWSInputException e) {
                throw new VerificationException(e);
            }
        } else {
            idToken = null;
        }
        log.debug("Token Verification succeeded!");
        RefreshableKeycloakSecurityContext secContext = new RefreshableKeycloakSecurityContext(deployment, tokenStore, accessTokenString, accessToken, idTokenString, idToken, refreshTokenString);
        return new KeycloakPrincipal<>(AdapterUtils.getPrincipalName(deployment, accessToken), secContext);
    } catch (VerificationException ve) {
        log.warn("Failed verify token", ve);
        return null;
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) JWSInput(org.keycloak.jose.jws.JWSInput) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 34 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class PreAuthActionsHandler method handleLogout.

protected void handleLogout() {
    if (log.isTraceEnabled()) {
        log.trace("K_LOGOUT sent");
    }
    try {
        JWSInput token = verifyAdminRequest();
        if (token == null) {
            return;
        }
        LogoutAction action = JsonSerialization.readValue(token.getContent(), LogoutAction.class);
        if (!validateAction(action))
            return;
        if (action.getAdapterSessionIds() != null) {
            userSessionManagement.logoutHttpSessions(action.getAdapterSessionIds());
        } else {
            log.debugf("logout of all sessions for application '%s'", action.getResource());
            if (action.getNotBefore() > deployment.getNotBefore()) {
                deployment.updateNotBefore(action.getNotBefore());
            }
            userSessionManagement.logoutAll();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : LogoutAction(org.keycloak.representations.adapters.action.LogoutAction) JWSInput(org.keycloak.jose.jws.JWSInput) VerificationException(org.keycloak.common.VerificationException)

Example 35 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class JOSEParser method parse.

/**
 * Parses the given encoded {@code jwt} and returns either a {@link JWSInput} or {@link JWE}
 * depending on the JOSE header configuration.
 *
 * @param jwt the encoded JWT
 * @return a {@link JOSE}
 */
public static JOSE parse(String jwt) {
    String[] parts = jwt.split("\\.");
    if (parts.length == 0) {
        throw new RuntimeException("Could not infer header from JWT");
    }
    JsonNode header;
    try {
        header = JsonSerialization.readValue(Base64Url.decode(parts[0]), JsonNode.class);
    } catch (IOException cause) {
        throw new RuntimeException("Failed to parse JWT header", cause);
    }
    if (header.has("enc")) {
        return new JWE(jwt);
    }
    try {
        return new JWSInput(jwt);
    } catch (JWSInputException cause) {
        throw new RuntimeException("Failed to build JWS", cause);
    }
}
Also used : JWE(org.keycloak.jose.jwe.JWE) JWSInputException(org.keycloak.jose.jws.JWSInputException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) JWSInput(org.keycloak.jose.jws.JWSInput)

Aggregations

JWSInput (org.keycloak.jose.jws.JWSInput)62 AccessToken (org.keycloak.representations.AccessToken)29 OAuthClient (org.keycloak.testsuite.util.OAuthClient)20 JWSInputException (org.keycloak.jose.jws.JWSInputException)16 Test (org.junit.Test)15 JWSHeader (org.keycloak.jose.jws.JWSHeader)11 Response (javax.ws.rs.core.Response)10 RefreshToken (org.keycloak.representations.RefreshToken)10 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)9 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)8 IOException (java.io.IOException)7 VerificationException (org.keycloak.common.VerificationException)7 JsonWebToken (org.keycloak.representations.JsonWebToken)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 PublicKey (java.security.PublicKey)5 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)5 Client (javax.ws.rs.client.Client)4 IDToken (org.keycloak.representations.IDToken)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 List (java.util.List)3