org.keycloak.jose.jws.JWSInput Java Examples

The following examples show how to use org.keycloak.jose.jws.JWSInput. 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: VertxHttpFacade.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public KeycloakSecurityContext getSecurityContext() {
    SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(routingContext, null);
    if (identity == null) {
        return null;
    }
    TokenCredential credential = identity.getCredential(AccessTokenCredential.class);

    if (credential == null) {
        return null;
    }

    String token = credential.getToken();

    try {
        return new KeycloakSecurityContext(token, new JWSInput(token).readJsonContent(AccessToken.class), null, null);
    } catch (JWSInputException e) {
        throw new RuntimeException("Failed to create access token", e);
    }
}
 
Example #2
Source File: OpenshiftClientStorageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertSuccessfulRedirect(String... expectedScopes) {
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, null);
    String accessToken = tokenResponse.getAccessToken();
    Assert.assertNotNull(accessToken);

    try {
        AccessToken token = new JWSInput(accessToken).readJsonContent(AccessToken.class);

        for (String expectedScope : expectedScopes) {
            token.getScope().contains(expectedScope);
        }
    } catch (Exception e) {
        fail("Failed to parse access token");
        e.printStackTrace();
    }

    Assert.assertNotNull(tokenResponse.getRefreshToken());
    oauth.doLogout(tokenResponse.getRefreshToken(), null);
    events.clear();
}
 
Example #3
Source File: AbstractShowTokensServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String renderTokens(HttpServletRequest req)  throws ServletException, IOException {
    RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
    String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(ctx.getToken());
    RefreshToken refreshToken;
    try {
        refreshToken = new JWSInput(ctx.getRefreshToken()).readJsonContent(RefreshToken.class);
    } catch (JWSInputException e) {
        throw new IOException(e);
    }
    String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken);

    return new StringBuilder("<span id=\"accessToken\">" + accessTokenPretty + "</span>")
            .append("<span id=\"refreshToken\">" + refreshTokenPretty + "</span>")
            .append("<span id=\"accessTokenString\">" + ctx.getTokenString() + "</span>")
            .toString();
}
 
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: 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 #6
Source File: PreAuthActionsHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void handlePushNotBefore()  {
    if (log.isTraceEnabled()) {
        log.trace("K_PUSH_NOT_BEFORE sent");
    }
    try {
        JWSInput token = verifyAdminRequest();
        if (token == null) {
            return;
        }
        PushNotBeforeAction action = JsonSerialization.readValue(token.getContent(), PushNotBeforeAction.class);
        if (!validateAction(action)) return;
        deployment.updateNotBefore(action.getNotBefore());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: PreAuthActionsHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
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 #9
Source File: TokenIntrospectionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void testIntrospectAccessToken(String jwaAlgorithm) throws Exception {
    try {
        TokenSignatureUtil.changeClientAccessTokenSignatureProvider(ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"), jwaAlgorithm);

        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");

        assertEquals(jwaAlgorithm, new JWSInput(accessTokenResponse.getAccessToken()).getHeader().getAlgorithm().name());

        String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());

        TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);

        assertTrue(rep.isActive());
        assertEquals("test-user@localhost", rep.getUserName());
        assertEquals("test-app", rep.getClientId());
        assertEquals(loginEvent.getUserId(), rep.getSubject());

        // Assert expected scope
        OIDCScopeTest.assertScopes("openid email profile", rep.getScope());
    } finally {
        TokenSignatureUtil.changeClientAccessTokenSignatureProvider(ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"), Algorithm.RS256);
    }
}
 
Example #10
Source File: AuthzEndpointRequestObjectParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AuthzEndpointRequestObjectParser(KeycloakSession session, String requestObject, ClientModel client) throws Exception {
    JWSInput input = new JWSInput(requestObject);
    JWSHeader header = input.getHeader();
    Algorithm headerAlgorithm = header.getAlgorithm();

    Algorithm requestedSignatureAlgorithm = OIDCAdvancedConfigWrapper.fromClientModel(client).getRequestObjectSignatureAlg();

    if (headerAlgorithm == null) {
        throw new RuntimeException("Request object signed algorithm not specified");
    }
    if (requestedSignatureAlgorithm != null && requestedSignatureAlgorithm != headerAlgorithm) {
        throw new RuntimeException("Request object signed with different algorithm than client requested algorithm");
    }

    if (header.getAlgorithm() == Algorithm.none) {
        this.requestParams = JsonSerialization.readValue(input.getContent(), JsonNode.class);
    } else {
        this.requestParams = session.tokens().decodeClientJWT(requestObject, client, JsonNode.class);
        if (this.requestParams == null) {
        	throw new RuntimeException("Failed to verify signature on 'request' object");
        }
    }
}
 
Example #11
Source File: MyResourcesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ResourceRepresentation createResource(AuthzClient authzClient, AuthorizationResource authorization, int i) {
    ResourceRepresentation resource = new ResourceRepresentation();

    resource.setOwnerManagedAccess(true);

    try {
        final byte[] content = new JWSInput(authzClient.obtainAccessToken("jdoe", PASSWORD).getToken()).getContent();
        final AccessToken accessToken = JsonSerialization.readValue(content, AccessToken.class);
        resource.setOwner(accessToken.getSubject());
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }

    resource.setName("Resource " + i);
    resource.setDisplayName("Display Name " + i);
    resource.setIconUri("Icon Uri " + i);
    resource.addScope("Scope A", "Scope B", "Scope C", "Scope D");
    resource.setUri("http://resourceServer.com/resources/" + i);

    try (Response response1 = authorization.resources().create(resource)) {
        resource.setId(response1.readEntity(ResourceRepresentation.class).getId());
    }
    return resource;
}
 
Example #12
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 #13
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 #14
Source File: RSAProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verify(JWSInput input, PublicKey publicKey) {
    try {
        Signature verifier = getSignature(input.getHeader().getAlgorithm());
        verifier.initVerify(publicKey);
        verifier.update(input.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8));
        return verifier.verify(input.getSignature());
    } catch (Exception e) {
        return false;
    }

}
 
Example #15
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 #16
Source File: RSAProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verifyViaCertificate(JWSInput input, String cert) {
    X509Certificate certificate = null;
    try {
        certificate = PemUtils.decodeCertificate(cert);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return verify(input, certificate.getPublicKey());
}
 
Example #17
Source File: HMACProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verify(JWSInput input, byte[] sharedSecret) {
    try {
        byte[] signature = sign(input.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8), input.getHeader().getAlgorithm(), sharedSecret);
        return MessageDigest.isEqual(signature, Base64Url.decode(input.getEncodedSignature()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: PreAuthActionsHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void handleTestAvailable()  {
    if (log.isTraceEnabled()) {
        log.trace("K_TEST_AVAILABLE sent");
    }
    try {
        JWSInput token = verifyAdminRequest();
        if (token == null) {
            return;
        }
        TestAvailabilityAction action = JsonSerialization.readValue(token.getContent(), TestAvailabilityAction.class);
        validateAction(action);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
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: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #21
Source File: PublicKeyStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static PublicKey getIdentityProviderPublicKey(KeycloakSession session, RealmModel realm, OIDCIdentityProviderConfig idpConfig, JWSInput input) {
    boolean keyIdSetInConfiguration = idpConfig.getPublicKeySignatureVerifierKeyId() != null
      && ! idpConfig.getPublicKeySignatureVerifierKeyId().trim().isEmpty();

    String kid = input.getHeader().getKeyId();

    PublicKeyStorageProvider keyStorage = session.getProvider(PublicKeyStorageProvider.class);

    String modelKey = PublicKeyStorageUtils.getIdpModelCacheKey(realm.getId(), idpConfig.getInternalId());
    PublicKeyLoader loader;
    if (idpConfig.isUseJwksUrl()) {
        loader = new OIDCIdentityProviderPublicKeyLoader(session, idpConfig);
    } else {
        String pem = idpConfig.getPublicKeySignatureVerifier();

        if (pem == null || pem.trim().isEmpty()) {
            logger.warnf("No public key saved on identityProvider %s", idpConfig.getAlias());
            return null;
        }

        loader = new HardcodedPublicKeyLoader(
          keyIdSetInConfiguration
            ? idpConfig.getPublicKeySignatureVerifierKeyId().trim()
            : kid, pem);
    }

    return (PublicKey)keyStorage.getPublicKey(modelKey, kid, loader).getPublicKey();
}
 
Example #22
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 #23
Source File: JWTClientAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected PublicKey getSignatureValidationKey(ClientModel client, ClientAuthenticationFlowContext context, JWSInput jws) {
    PublicKey publicKey = PublicKeyStorageManager.getClientPublicKey(context.getSession(), client, jws);
    if (publicKey == null) {
        Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "unauthorized_client", "Unable to load public key");
        context.failure(AuthenticationFlowError.CLIENT_CREDENTIALS_SETUP_REQUIRED, challengeResponse);
        return null;
    } else {
        return publicKey;
    }
}
 
Example #24
Source File: HmacTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testHmacSignatures() throws Exception {
    SecretKey secret = new SecretKeySpec(UUID.randomUUID().toString().getBytes(), "HmacSHA256");
    String encoded = new JWSBuilder().content("12345678901234567890".getBytes())
            .hmac256(secret);
    System.out.println("length: " + encoded.length());
    JWSInput input = new JWSInput(encoded);
    Assert.assertTrue(HMACProvider.verify(input, secret));
}
 
Example #25
Source File: PrincipalExtractor.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
public String getPrincipal(AccessToken token, JWSInput jws) {
    if (usernameClaim != null) {
        try {
            return getPrincipal(jws.readJsonContent(JsonNode.class));
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse access token", e);
        }
    }
    return null;
}
 
Example #26
Source File: KcOidcBrokerNonceParameterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected IDToken toIdToken(String encoded) {
    IDToken idToken;

    try {
        idToken = new JWSInput(encoded).readJsonContent(IDToken.class);
    } catch (JWSInputException cause) {
        throw new RuntimeException("Failed to deserialize RPT", cause);
    }
    return idToken;
}
 
Example #27
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertTokenIssuer(String realm, String expectedBaseUrl) throws Exception {
    oauth.realm(realm);

    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");

    AccessToken token = new JWSInput(tokenResponse.getAccessToken()).readJsonContent(AccessToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, token.getIssuer());

    String introspection = oauth.introspectAccessTokenWithClientCredential(oauth.getClientId(), "password", tokenResponse.getAccessToken());
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode introspectionNode = objectMapper.readTree(introspection);
    assertTrue(introspectionNode.get("active").asBoolean());
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, introspectionNode.get("iss").asText());
}
 
Example #28
Source File: DefaultHostnameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertTokenIssuer(String realm, String expectedBaseUrl) throws Exception {
    oauth.realm(realm);

    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");

    AccessToken token = new JWSInput(tokenResponse.getAccessToken()).readJsonContent(AccessToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, token.getIssuer());

    String introspection = oauth.introspectAccessTokenWithClientCredential(oauth.getClientId(), "password", tokenResponse.getAccessToken());
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode introspectionNode = objectMapper.readTree(introspection);
    assertTrue(introspectionNode.get("active").asBoolean());
    assertEquals(expectedBaseUrl + "/realms/" + realm, introspectionNode.get("iss").asText());
}
 
Example #29
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testZipException() throws Exception {
    // KEYCLOAK-2479
    // Example of LogoutAction, which shows the exception to STDERR during Base64.decode . Need to use flag DONT_GUNZIP to avoid it.
    String logoutAction = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6ImUwYmRmMjQyLWJjZGItNGVjMy1hMGU4LTNjN2YyOTUzOTk5MC0xNDU1NzgyNTU2NjAyIiwiZXhwaXJhdGlvbiI6MTQ1NTc4MjU4NiwicmVzb3VyY2UiOiJwcm9kdWN0LXBvcnRhbCIsImFjdGlvbiI6IkxPR09VVCIsImFkYXB0ZXJTZXNzaW9uSWRzIjpbImx2c0oxNUpSX01XUE13aTIwbWRhTkJFRVZQZzQtMTkzVUZKem42M1EiXSwibm90QmVmb3JlIjowLCJrZXljbG9ha1Nlc3Npb25JZHMiOlsiOThkNWE3YTYtYjNmNi00ZTg3LWI5OTktOTg1N2YzMDRiZjY4Il19.H4vo7YXW8oQgYsIo9VPYeSsp1jXJR0TwJUwmiXjQJSyxFoKhHgIh3Y63ldVUeBRppxX9xhjOdYEckeppAn-1XnNxUmbExXWXirRIw8tiEtUPPCPztdkKsM0y6xWRd3Sjgg4fWB_1sMn6EWvCAvO7ahs6Rbb2Vo18nlHfxYRSTWw";
    JWSInput input = new JWSInput(logoutAction);
}
 
Example #30
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean verify(JWSInput jws) {
    if (!getConfig().isValidateSignature()) return true;

    try {
        PublicKey publicKey = PublicKeyStorageManager.getIdentityProviderPublicKey(session, session.getContext().getRealm(), getConfig(), jws);

        return publicKey != null && RSAProvider.verify(jws, publicKey);
    } catch (Exception e) {
        logger.debug("Failed to verify token", e);
        return false;
    }
}