Search in sources :

Example 1 with Details

use of org.keycloak.events.Details in project keycloak by keycloak.

the class LoginTest method loginWithLongRedirectUri.

@AuthServerContainerExclude(value = { AuthServerContainerExclude.AuthServer.REMOTE }, details = "Remote testsuite: max-detail-length is set to zero in standalone.xml, proposed fix - KEYCLOAK-17659")
@Test
public void loginWithLongRedirectUri() throws Exception {
    try (AutoCloseable c = new RealmAttributeUpdater(adminClient.realm("test")).updateWith(r -> r.setEventsEnabled(true)).update()) {
        String randomLongString = RandomStringUtils.random(2500, true, true);
        String longRedirectUri = oauth.getRedirectUri() + "?longQueryParameterValue=" + randomLongString;
        UriBuilder longLoginUri = UriBuilder.fromUri(oauth.getLoginFormUrl()).replaceQueryParam(OAuth2Constants.REDIRECT_URI, longRedirectUri);
        DroneUtils.getCurrentDriver().navigate().to(longLoginUri.build().toString());
        loginPage.assertCurrent();
        loginPage.login("login-test", "password");
        events.expectLogin().user(userId).detail(OAuth2Constants.REDIRECT_URI, longRedirectUri).assertEvent();
    }
}
Also used : JavascriptBrowser(org.keycloak.testsuite.util.JavascriptBrowser) AUTHORIZATION(org.keycloak.common.Profile.Feature.AUTHORIZATION) Arrays(java.util.Arrays) AssertEvents(org.keycloak.testsuite.AssertEvents) Page(org.jboss.arquillian.graphene.page.Page) OAuthClient(org.keycloak.testsuite.util.OAuthClient) LoginPasswordUpdatePage(org.keycloak.testsuite.pages.LoginPasswordUpdatePage) AdminClientUtil(org.keycloak.testsuite.util.AdminClientUtil) BrowserSecurityHeaders(org.keycloak.models.BrowserSecurityHeaders) AdminConsole(org.keycloak.testsuite.console.page.AdminConsole) UriBuilder(javax.ws.rs.core.UriBuilder) ClientResource(org.keycloak.admin.client.resource.ClientResource) ApiUtil.findClientByClientId(org.keycloak.testsuite.admin.ApiUtil.findClientByClientId) DYNAMIC_SCOPES(org.keycloak.common.Profile.Feature.DYNAMIC_SCOPES) ClientScopeModel(org.keycloak.models.ClientScopeModel) Matchers(org.keycloak.testsuite.util.Matchers) DisableFeature(org.keycloak.testsuite.arquillian.annotation.DisableFeature) UUID(java.util.UUID) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) List(java.util.List) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) LoginPage(org.keycloak.testsuite.pages.LoginPage) Assert.assertFalse(org.junit.Assert.assertFalse) SessionTimeoutHelper(org.keycloak.models.utils.SessionTimeoutHelper) Matchers.equalTo(org.hamcrest.Matchers.equalTo) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) SERVER_ROOT(org.keycloak.testsuite.util.OAuthClient.SERVER_ROOT) OAuth2Constants(org.keycloak.OAuth2Constants) Profile(org.keycloak.common.Profile) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) WebDriver(org.openqa.selenium.WebDriver) Client(javax.ws.rs.client.Client) ContainerAssume(org.keycloak.testsuite.util.ContainerAssume) DroneUtils(org.keycloak.testsuite.util.DroneUtils) Algorithm(org.keycloak.crypto.Algorithm) HashMap(java.util.HashMap) ServerURLs.getAuthServerContextRoot(org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot) AccountUpdateProfilePage(org.keycloak.testsuite.pages.AccountUpdateProfilePage) JWSInputException(org.keycloak.jose.jws.JWSInputException) EnableFeature(org.keycloak.testsuite.arquillian.annotation.EnableFeature) RealmBuilder(org.keycloak.testsuite.util.RealmBuilder) Drone(org.jboss.arquillian.drone.api.annotation.Drone) UserBuilder(org.keycloak.testsuite.util.UserBuilder) UserResource(org.keycloak.admin.client.resource.UserResource) OIDCLoginProtocolService(org.keycloak.protocol.oidc.OIDCLoginProtocolService) ProfileAssume(org.keycloak.testsuite.ProfileAssume) Retry(org.keycloak.common.util.Retry) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) JWSInput(org.keycloak.jose.jws.JWSInput) WaitUtils(org.keycloak.testsuite.util.WaitUtils) AUTH_SERVER_ROOT(org.keycloak.testsuite.util.OAuthClient.AUTH_SERVER_ROOT) AppPage(org.keycloak.testsuite.pages.AppPage) Errors(org.keycloak.events.Errors) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) EventType(org.keycloak.events.EventType) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest) URLAssert.assertCurrentUrlStartsWithLoginUrlOf(org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWithLoginUrlOf) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) TokenSignatureUtil(org.keycloak.testsuite.util.TokenSignatureUtil) RequestType(org.keycloak.testsuite.pages.AppPage.RequestType) ErrorPage(org.keycloak.testsuite.pages.ErrorPage) Closeable(java.io.Closeable) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) Matchers.containsString(org.hamcrest.Matchers.containsString) UriBuilder(javax.ws.rs.core.UriBuilder) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 2 with Details

use of org.keycloak.events.Details in project keycloak by keycloak.

the class AuthenticationManager method finishBrowserLogout.

public static Response finishBrowserLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers) {
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);
    checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    // For resolving artifact we don't need any cookie, all details are stored in session storage so we can remove
    expireIdentityCookie(realm, uriInfo, connection);
    expireRememberMeCookie(realm, uriInfo, connection);
    String method = userSession.getNote(KEYCLOAK_LOGOUT_PROTOCOL);
    EventBuilder event = new EventBuilder(realm, session, connection);
    LoginProtocol protocol = session.getProvider(LoginProtocol.class, method);
    protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo).setEventBuilder(event);
    Response response = protocol.finishLogout(userSession);
    // It may be possible that there are some client sessions that are still in LOGGING_OUT state
    long numberOfUnconfirmedSessions = userSession.getAuthenticatedClientSessions().values().stream().filter(clientSessionModel -> CommonClientSessionModel.Action.LOGGING_OUT.name().equals(clientSessionModel.getAction())).count();
    // If logout flow end up correctly there should be at maximum 1 client session in LOGGING_OUT action, if there are more, something went wrong
    if (numberOfUnconfirmedSessions > 1) {
        logger.warnf("There are more than one clientSession in logging_out state. Perhaps some client did not finish logout flow correctly.");
    }
    // LOGGED_OUT action can remove UserSession
    if (numberOfUnconfirmedSessions >= 1) {
        userSession.setState(UserSessionModel.State.LOGGED_OUT_UNCONFIRMED);
    } else {
        userSession.setState(UserSessionModel.State.LOGGED_OUT);
    }
    // Do not remove user session, it will be removed when last clientSession will be logged out
    if (numberOfUnconfirmedSessions < 1) {
        session.sessions().removeUserSession(realm, userSession);
    }
    session.authenticationSessions().removeRootAuthenticationSession(realm, logoutAuthSession.getParentSession());
    return response;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ActionTokenStoreProvider(org.keycloak.models.ActionTokenStoreProvider) Error(org.keycloak.protocol.LoginProtocol.Error) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) Set(java.util.Set) AbstractUsernameFormAuthenticator(org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator) SecretGenerator(org.keycloak.common.util.SecretGenerator) Stream(java.util.stream.Stream) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) SessionTimeoutHelper(org.keycloak.models.utils.SessionTimeoutHelper) LoginActionsService(org.keycloak.services.resources.LoginActionsService) UriInfo(javax.ws.rs.core.UriInfo) OAuth2Constants(org.keycloak.OAuth2Constants) LoginProtocol(org.keycloak.protocol.LoginProtocol) Constants(org.keycloak.models.Constants) TokenManager(org.keycloak.protocol.oidc.TokenManager) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) Predicate(org.keycloak.TokenVerifier.Predicate) TokenVerifier(org.keycloak.TokenVerifier) CommonClientSessionModel(org.keycloak.sessions.CommonClientSessionModel) Base64Url(org.keycloak.common.util.Base64Url) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) ConsoleDisplayMode(org.keycloak.authentication.ConsoleDisplayMode) IdentityBrokerService(org.keycloak.services.resources.IdentityBrokerService) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails) HttpRequest(org.jboss.resteasy.spi.HttpRequest) EventType(org.keycloak.events.EventType) P3PHelper(org.keycloak.services.util.P3PHelper) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) URLDecoder(java.net.URLDecoder) ActionTokenKeyModel(org.keycloak.models.ActionTokenKeyModel) RequiredActionContextResult(org.keycloak.authentication.RequiredActionContextResult) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) NewCookie(javax.ws.rs.core.NewCookie) Messages(org.keycloak.services.messages.Messages) DefaultActionTokenKey(org.keycloak.authentication.actiontoken.DefaultActionTokenKey) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) URI(java.net.URI) SystemClientUtil(org.keycloak.models.utils.SystemClientUtil) VerificationException(org.keycloak.common.VerificationException) DeviceGrantType.isOAuth2DeviceVerificationFlow(org.keycloak.protocol.oidc.grants.device.DeviceGrantType.isOAuth2DeviceVerificationFlow) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) InitiatedActionSupport(org.keycloak.authentication.InitiatedActionSupport) AuthenticatorUtil(org.keycloak.authentication.AuthenticatorUtil) Collectors(java.util.stream.Collectors) Cookie(javax.ws.rs.core.Cookie) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ClientModel(org.keycloak.models.ClientModel) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) SameSiteAttributeValue(org.keycloak.common.util.ServerCookie.SameSiteAttributeValue) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ServicesLogger(org.keycloak.services.ServicesLogger) TokenTypeCheck(org.keycloak.TokenVerifier.TokenTypeCheck) RequiredActionContext(org.keycloak.authentication.RequiredActionContext) SignatureProvider(org.keycloak.crypto.SignatureProvider) EventBuilder(org.keycloak.events.EventBuilder) CookieHelper(org.keycloak.services.util.CookieHelper) UserConsentModel(org.keycloak.models.UserConsentModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) LinkedList(java.util.LinkedList) DisplayTypeRequiredActionFactory(org.keycloak.authentication.DisplayTypeRequiredActionFactory) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) Errors(org.keycloak.events.Errors) CORRESPONDING_SESSION_ID(org.keycloak.models.UserSessionModel.CORRESPONDING_SESSION_ID) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationContextUtil(org.keycloak.services.util.AuthorizationContextUtil) URLEncoder(java.net.URLEncoder) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) CookieHelper.getCookie(org.keycloak.services.util.CookieHelper.getCookie) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) LoginProtocol(org.keycloak.protocol.LoginProtocol) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol)

Example 3 with Details

use of org.keycloak.events.Details in project keycloak by keycloak.

the class ImpersonationTest method impersonate.

private Set<Cookie> impersonate(Keycloak adminClient, String admin, String adminRealm) {
    BasicCookieStore cookieStore = new BasicCookieStore();
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build()) {
        HttpUriRequest req = RequestBuilder.post().setUri(AUTH_SERVER_ROOT + "/admin/realms/test/users/" + impersonatedUserId + "/impersonation").addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.tokenManager().getAccessTokenString()).build();
        HttpResponse res = httpClient.execute(req);
        String resBody = EntityUtils.toString(res.getEntity());
        Assert.assertNotNull(resBody);
        Assert.assertTrue(resBody.contains("redirect"));
        events.expect(EventType.IMPERSONATE).session(AssertEvents.isUUID()).user(impersonatedUserId).detail(Details.IMPERSONATOR, admin).detail(Details.IMPERSONATOR_REALM, adminRealm).client((String) null).assertEvent();
        // Fetch user session notes
        final String userId = impersonatedUserId;
        final UserSessionNotesHolder notesHolder = testingClient.server("test").fetch(session -> {
            final RealmModel realm = session.realms().getRealmByName("test");
            final UserModel user = session.users().getUserById(realm, userId);
            final UserSessionModel userSession = session.sessions().getUserSessionsStream(realm, user).findFirst().get();
            return new UserSessionNotesHolder(userSession.getNotes());
        }, UserSessionNotesHolder.class);
        // Check impersonation details
        final Map<String, String> notes = notesHolder.getNotes();
        Assert.assertNotNull(notes.get(ImpersonationSessionNote.IMPERSONATOR_ID.toString()));
        Assert.assertEquals(admin, notes.get(ImpersonationSessionNote.IMPERSONATOR_USERNAME.toString()));
        Set<Cookie> cookies = cookieStore.getCookies().stream().filter(c -> c.getName().startsWith(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE)).map(c -> new Cookie(c.getName(), c.getValue(), c.getDomain(), c.getPath(), c.getExpiryDate(), c.isSecure(), true)).collect(Collectors.toSet());
        Assert.assertNotNull(cookies);
        Assert.assertThat(cookies, is(not(empty())));
        return cookies;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Cookie(org.openqa.selenium.Cookie) org.keycloak.representations.idm(org.keycloak.representations.idm) URL(java.net.URL) AssertEvents(org.keycloak.testsuite.AssertEvents) Config(org.keycloak.Config) Page(org.jboss.arquillian.graphene.page.Page) ClientErrorException(javax.ws.rs.ClientErrorException) EntityUtils(org.apache.http.util.EntityUtils) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) ClientResource(org.keycloak.admin.client.resource.ClientResource) RealmModel(org.keycloak.models.RealmModel) RealmResource(org.keycloak.admin.client.resource.RealmResource) Collectors(java.util.stream.Collectors) Keycloak(org.keycloak.admin.client.Keycloak) AuthRealm(org.keycloak.testsuite.auth.page.AuthRealm) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) LoginPage(org.keycloak.testsuite.pages.LoginPage) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) OAuth2Constants(org.keycloak.OAuth2Constants) java.util(java.util) BeforeClass(org.junit.BeforeClass) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AdminRoles(org.keycloak.models.AdminRoles) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Constants(org.keycloak.models.Constants) ServerURLs.getAuthServerContextRoot(org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) UserModel(org.keycloak.models.UserModel) RequestBuilder(org.apache.http.client.methods.RequestBuilder) Assume(org.junit.Assume) UserResource(org.keycloak.admin.client.resource.UserResource) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) Before(org.junit.Before) AUTH_SERVER_ROOT(org.keycloak.testsuite.util.OAuthClient.AUTH_SERVER_ROOT) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) AppPage(org.keycloak.testsuite.pages.AppPage) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) EventType(org.keycloak.events.EventType) IOException(java.io.IOException) UserSessionModel(org.keycloak.models.UserSessionModel) ImpersonationSessionNote(org.keycloak.models.ImpersonationSessionNote) org.keycloak.testsuite.util(org.keycloak.testsuite.util) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Rule(org.junit.Rule) ImpersonationConstants(org.keycloak.models.ImpersonationConstants) Cookie(org.openqa.selenium.Cookie) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Assert(org.junit.Assert) KeycloakBuilder(org.keycloak.admin.client.KeycloakBuilder) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UserSessionModel(org.keycloak.models.UserSessionModel) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore)

Aggregations

Response (javax.ws.rs.core.Response)3 OAuth2Constants (org.keycloak.OAuth2Constants)3 Details (org.keycloak.events.Details)3 EventType (org.keycloak.events.EventType)3 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 HttpHeaders (javax.ws.rs.core.HttpHeaders)2 UriBuilder (javax.ws.rs.core.UriBuilder)2 Page (org.jboss.arquillian.graphene.page.Page)2 Constants (org.keycloak.models.Constants)2 RealmModel (org.keycloak.models.RealmModel)2 UserModel (org.keycloak.models.UserModel)2 UserSessionModel (org.keycloak.models.UserSessionModel)2 KeycloakModelUtils (org.keycloak.models.utils.KeycloakModelUtils)2 Closeable (java.io.Closeable)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 URL (java.net.URL)1 URLDecoder (java.net.URLDecoder)1