Search in sources :

Example 16 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class AccessTokenTest method accessTokenCodeHasRequiredAction.

@Test
public void accessTokenCodeHasRequiredAction() {
    UserResource user = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    UserManager.realm(adminClient.realm("test")).user(user).addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE.toString());
    oauth.doLogin("test-user@localhost", "password");
    String actionURI = ActionURIUtils.getActionURIFromPageSource(driver.getPageSource());
    String code = ActionURIUtils.parseQueryParamsFromActionURI(actionURI).get("code");
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertEquals(400, response.getStatusCode());
    EventRepresentation event = events.poll();
    assertNull(event.getDetails().get(Details.CODE_ID));
    UserManager.realm(adminClient.realm("test")).user(user).removeRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE.toString());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) UserResource(org.keycloak.admin.client.resource.UserResource) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 17 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class AccessTokenTest method testAuthorizationNegotiateHeaderIgnored.

// KEYCLOAK-1595 Assert that public client is able to retrieve token even if header "Authorization: Negotiate something" was used (parameter client_id has preference in this case)
@Test
public void testAuthorizationNegotiateHeaderIgnored() throws Exception {
    adminClient.realm("test").clients().create(ClientBuilder.create().clientId("sample-public-client").authenticatorType("client-secret").redirectUris(oauth.getRedirectUri() + "/*").publicClient().build());
    oauth.clientId("sample-public-client");
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().client("sample-public-client").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpPost post = new HttpPost(oauth.getAccessTokenUrl());
        List<NameValuePair> parameters = new LinkedList<>();
        parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
        parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
        parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
        parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, oauth.getClientId()));
        post.setHeader("Authorization", "Negotiate something-which-will-be-ignored");
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        post.setEntity(formEntity);
        OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
        Assert.assertEquals(200, response.getStatusCode());
        AccessToken token = oauth.verifyToken(response.getAccessToken());
        events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LinkedList(java.util.LinkedList) AccessToken(org.keycloak.representations.AccessToken) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 18 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class AccessTokenTest method accessTokenRequest.

@Test
public void accessTokenRequest() throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(200, response.getStatusCode());
    Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
    Assert.assertThat(response.getRefreshExpiresIn(), allOf(greaterThanOrEqualTo(1750), lessThanOrEqualTo(1800)));
    assertEquals("Bearer", response.getTokenType());
    String expectedKid = oauth.doCertsRequest("test").getKeys()[0].getKeyId();
    JWSHeader header = new JWSInput(response.getAccessToken()).getHeader();
    assertEquals("RS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertEquals(expectedKid, header.getKeyId());
    assertNull(header.getContentType());
    header = new JWSInput(response.getIdToken()).getHeader();
    assertEquals("RS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertEquals(expectedKid, header.getKeyId());
    assertNull(header.getContentType());
    header = new JWSInput(response.getRefreshToken()).getHeader();
    assertEquals("HS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), token.getSubject());
    assertNotEquals("test-user@localhost", token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    JWSInput idToken = new JWSInput(response.getIdToken());
    ObjectMapper mapper = JsonSerialization.mapper;
    JsonParser parser = mapper.getFactory().createParser(idToken.readContentAsString());
    TreeNode treeNode = mapper.readTree(parser);
    String sid = ((TextNode) treeNode.get("sid")).asText();
    assertEquals(sessionId, sid);
    assertNull(token.getNbf());
    assertEquals(0, token.getNotBefore());
    assertNotNull(token.getIat());
    assertEquals(token.getIat().intValue(), token.getIssuedAt());
    assertNotNull(token.getExp());
    assertEquals(token.getExp().intValue(), token.getExpiration());
    assertEquals(1, token.getRealmAccess().getRoles().size());
    assertTrue(token.getRealmAccess().isUserInRole("user"));
    assertEquals(1, token.getResourceAccess(oauth.getClientId()).getRoles().size());
    assertTrue(token.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));
    EventRepresentation event = events.expectCodeToToken(codeId, sessionId).assertEvent();
    assertEquals(token.getId(), event.getDetails().get(Details.TOKEN_ID));
    assertEquals(oauth.parseRefreshToken(response.getRefreshToken()).getId(), event.getDetails().get(Details.REFRESH_TOKEN_ID));
    assertEquals(sessionId, token.getSessionState());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) TreeNode(com.fasterxml.jackson.core.TreeNode) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) TextNode(com.fasterxml.jackson.databind.node.TextNode) JWSInput(org.keycloak.jose.jws.JWSInput) JWSHeader(org.keycloak.jose.jws.JWSHeader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.fasterxml.jackson.core.JsonParser) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 19 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class AccessTokenTest method accessTokenInvalidRedirectUri.

@Test
public void accessTokenInvalidRedirectUri() throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    // @TODO This new and was necesssary to not mess up with other tests cases
    String redirectUri = oauth.getRedirectUri();
    oauth.redirectUri("http://invalid");
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(400, response.getStatusCode());
    assertEquals("invalid_grant", response.getError());
    assertEquals("Incorrect redirect_uri", response.getErrorDescription());
    events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_code").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_TYPE).assertEvent();
    // @TODO Reset back to the original URI. Maybe we should have something to reset to the original state at OAuthClient
    oauth.redirectUri(redirectUri);
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 20 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class BackchannelLogoutTest method assertLogoutEvent.

private void assertLogoutEvent(String sessionId, String userId, String realmName) {
    String realmId = adminClient.realm(realmName).toRepresentation().getId();
    List<EventRepresentation> eventList = adminClient.realm(realmName).getEvents();
    Optional<EventRepresentation> logoutEventOptional = eventList.stream().filter(event -> sessionId.equals(event.getSessionId())).findAny();
    if (logoutEventOptional.isPresent()) {
        EventRepresentation logoutEvent = logoutEventOptional.get();
        this.events.expectLogout(sessionId).realm(realmId).user(userId).removeDetail(Details.REDIRECT_URI).assertEvent(logoutEvent);
    } else {
        fail("No Logout event found for session " + sessionId);
    }
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ApiUtil.createUserWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserWithAdminClient) KeyPair(java.security.KeyPair) LogoutTokenValidationCode(org.keycloak.protocol.oidc.LogoutTokenValidationCode) Arrays(java.util.Arrays) AssertEvents(org.keycloak.testsuite.AssertEvents) Assert.assertThat(org.junit.Assert.assertThat) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ClientResource(org.keycloak.admin.client.resource.ClientResource) RealmManager(org.keycloak.testsuite.util.RealmManager) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) RealmResource(org.keycloak.admin.client.resource.RealmResource) Matchers(org.keycloak.testsuite.util.Matchers) LogoutTokenUtil(org.keycloak.testsuite.util.LogoutTokenUtil) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) IdentityProviderResource(org.keycloak.admin.client.resource.IdentityProviderResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) List(java.util.List) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) Optional(java.util.Optional) OAuth2Constants(org.keycloak.OAuth2Constants) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) OidcBackchannelLogoutBrokerConfiguration(org.keycloak.testsuite.broker.OidcBackchannelLogoutBrokerConfiguration) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) SecondBrowser(org.keycloak.testsuite.util.SecondBrowser) CredentialBuilder(org.keycloak.testsuite.util.CredentialBuilder) WebDriver(org.openqa.selenium.WebDriver) BrokerTestTools.getConsumerRoot(org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot) ApiUtil.resetUserPassword(org.keycloak.testsuite.admin.ApiUtil.resetUserPassword) Drone(org.jboss.arquillian.drone.api.annotation.Drone) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) KeyUtils(org.keycloak.common.util.KeyUtils) Base64Url(org.keycloak.common.util.Base64Url) Before(org.junit.Before) AbstractNestedBrokerTest(org.keycloak.testsuite.broker.AbstractNestedBrokerTest) Errors(org.keycloak.events.Errors) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test) EventType(org.keycloak.events.EventType) IOException(java.io.IOException) JsonSerialization(org.keycloak.util.JsonSerialization) Rule(org.junit.Rule) NestedBrokerConfiguration(org.keycloak.testsuite.broker.NestedBrokerConfiguration) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString)

Aggregations

EventRepresentation (org.keycloak.representations.idm.EventRepresentation)164 Test (org.junit.Test)124 OAuthClient (org.keycloak.testsuite.util.OAuthClient)93 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)60 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)44 RefreshToken (org.keycloak.representations.RefreshToken)27 ClientResource (org.keycloak.admin.client.resource.ClientResource)26 AccessToken (org.keycloak.representations.AccessToken)26 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)25 IDToken (org.keycloak.representations.IDToken)23 Matchers.containsString (org.hamcrest.Matchers.containsString)15 AbstractAdminTest (org.keycloak.testsuite.admin.AbstractAdminTest)15 Response (javax.ws.rs.core.Response)13 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)13 AccessTokenResponse (org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse)12 IOException (java.io.IOException)11 RealmResource (org.keycloak.admin.client.resource.RealmResource)11 AssertEvents (org.keycloak.testsuite.AssertEvents)10 JWSInput (org.keycloak.jose.jws.JWSInput)9 TestAuthenticationChannelRequest (org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest)9