Search in sources :

Example 6 with JWSInputException

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

the class AdminRoot method authenticateRealmAdminRequest.

protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = AppAuthManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null)
        throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error");
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = new AppAuthManager.BearerTokenAuthenticator(session).setRealm(realm).setConnection(clientConnection).setHeaders(headers).authenticate();
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }
    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), authResult.getClient());
}
Also used : RealmModel(org.keycloak.models.RealmModel) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) JWSInput(org.keycloak.jose.jws.JWSInput) RealmManager(org.keycloak.services.managers.RealmManager)

Example 7 with JWSInputException

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

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

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

use of org.keycloak.jose.jws.JWSInputException 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)16 JWSInputException (org.keycloak.jose.jws.JWSInputException)16 AccessToken (org.keycloak.representations.AccessToken)8 IOException (java.io.IOException)3 RefreshToken (org.keycloak.representations.RefreshToken)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 RefreshableKeycloakSecurityContext (org.keycloak.adapters.RefreshableKeycloakSecurityContext)2 VerificationException (org.keycloak.common.VerificationException)2 JsonWebToken (org.keycloak.representations.JsonWebToken)2 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)2 AuthenticationManager (org.keycloak.services.managers.AuthenticationManager)2 X509Certificate (javax.security.cert.X509Certificate)1 BadRequestException (javax.ws.rs.BadRequestException)1 Consumes (javax.ws.rs.Consumes)1 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 MediaType (javax.ws.rs.core.MediaType)1 Response (javax.ws.rs.core.Response)1