Java Code Examples for org.keycloak.jose.jws.JWSInput#readJsonContent()

The following examples show how to use org.keycloak.jose.jws.JWSInput#readJsonContent() . 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: 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 2
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRSA() throws Exception {
    AccessToken token = createSimpleToken();
    token.id("111");
    token.addAccess("foo").addRole("admin");
    token.addAccess("bar").addRole("user");

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

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

    JWSInput input = new JWSInput(encoded);

    token = input.readJsonContent(AccessToken.class);
    Assert.assertEquals("111", token.getId());
    Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
 
Example 3
Source File: ExportResourceProvider.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This code has been copied from keycloak org.keycloak.services.resources.admin.AdminRoot;
 * it allows to check if a user as realm/master admin
 * at each upgrade check that it hasn't been modified
 */
private AdminAuth authenticateRealmAdminRequest(HttpHeaders headers, UriInfo uriInfo) {
    String tokenString = authManager.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", e);
    }
    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 = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null) {
        throw new NotFoundException("Could not find client for authorization");

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example 4
Source File: AssertAdminEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AuthDetailsRepresentation defaultAuthDetails() {
    String accessTokenString = context.getAdminClient().tokenManager().getAccessTokenString();
    try {
        JWSInput input = new JWSInput(accessTokenString);
        AccessToken token = input.readJsonContent(AccessToken.class);

        AuthDetailsRepresentation authDetails = new AuthDetailsRepresentation();
        String realmId = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
        authDetails.setRealmId(realmId);
        authDetails.setUserId(token.getSubject());
        return authDetails;
    } catch (JWSInputException jwe) {
        throw new RuntimeException(jwe);
    }
}
 
Example 5
Source File: AdminRoot.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = authManager.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 = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null) {
        throw new NotFoundException("Could not find client for authorization");

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example 6
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private IDToken getIdToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException {
    JWSInput input = new JWSInput(tokenResponse.getIdToken());
    return input.readJsonContent(IDToken.class);
}
 
Example 7
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private AccessToken getAccessToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException {
    JWSInput input = new JWSInput(tokenResponse.getToken());
    return input.readJsonContent(AccessToken.class);
}
 
Example 8
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected JsonWebToken validateToken(String encodedToken, boolean ignoreAudience) {
    if (encodedToken == null) {
        throw new IdentityBrokerException("No token from server.");
    }

    JsonWebToken token;
    try {
        JWSInput jws = new JWSInput(encodedToken);
        if (!verify(jws)) {
            throw new IdentityBrokerException("token signature validation failed");
        }
        token = jws.readJsonContent(JsonWebToken.class);
    } catch (JWSInputException e) {
        throw new IdentityBrokerException("Invalid token", e);
    }

    String iss = token.getIssuer();

    if (!token.isActive(getConfig().getAllowedClockSkew())) {
        throw new IdentityBrokerException("Token is no longer valid");
    }

    if (!ignoreAudience && !token.hasAudience(getConfig().getClientId())) {
        throw new IdentityBrokerException("Wrong audience from token.");
    }
    
    if (!ignoreAudience && (token.getIssuedFor() != null && !getConfig().getClientId().equals(token.getIssuedFor()))) {
        throw new IdentityBrokerException("Token issued for does not match client id");
    }

    String trustedIssuers = getConfig().getIssuer();

    if (trustedIssuers != null && trustedIssuers.length() > 0) {
        String[] issuers = trustedIssuers.split(",");

        for (String trustedIssuer : issuers) {
            if (iss != null && iss.equals(trustedIssuer.trim())) {
                return token;
            }
        }

        throw new IdentityBrokerException("Wrong issuer from token. Got: " + iss + " expected: " + getConfig().getIssuer());
    }

    return token;
}
 
Example 9
Source File: CookieTokenStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
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;
    }
}