Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,11 @@ public Response authenticateOnly() throws AuthenticationFlowException {

// May create userSession too
public ClientSessionContext attachSession() {
ClientSessionContext clientSessionCtx = attachSession(authenticationSession, userSession, session, realm, connection, event);
return attachSession(true);
}

public ClientSessionContext attachSession(boolean isCookie) {
ClientSessionContext clientSessionCtx = attachSession(authenticationSession, userSession, session, realm, connection, event, isCookie);

if (userSession == null) {
userSession = clientSessionCtx.getClientSession().getUserSession();
Expand All @@ -1149,6 +1153,10 @@ public ClientSessionContext attachSession() {

// May create new userSession too (if userSession argument is null)
public static ClientSessionContext attachSession(AuthenticationSessionModel authSession, UserSessionModel userSession, KeycloakSession session, RealmModel realm, ClientConnection connection, EventBuilder event) {
return attachSession(authSession, userSession, session, realm, connection, event, true);
}

public static ClientSessionContext attachSession(AuthenticationSessionModel authSession, UserSessionModel userSession, KeycloakSession session, RealmModel realm, ClientConnection connection, EventBuilder event, boolean isCookie) {
UserModel authenticatedUser = authSession.getAuthenticatedUser();

if (authenticatedUser == null) {
Expand All @@ -1166,7 +1174,20 @@ public static ClientSessionContext attachSession(AuthenticationSessionModel auth

if (userSession == null) { // if no authenticator attached a usersession

userSession = session.sessions().getUserSession(realm, authSession.getParentSession().getId());
// check if user session can be retrieved using cookie
if (isCookie) {
AuthenticationManager.AuthResult result = AuthenticationManager.authenticateIdentityCookie(session, realm, true);
Comment thread
rmartinc marked this conversation as resolved.
Resolved
Comment thread
pedroigor marked this conversation as resolved.
Resolved
if (result != null) {
userSession = result.session();
Comment thread
rmartinc marked this conversation as resolved.
Resolved
} else {
userSession = session.sessions().getUserSession(realm, authSession.getParentSession().getId());
}
if (userSession != null && userSession.getState() != UserSessionModel.State.LOGGED_IN) {
event.error(Errors.SESSION_EXPIRED);
throw new ErrorPageException(session, authSession, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
}

if (userSession == null) {
// an attempt to re-authenticate but attaching a user session that does not exist
if (isSSOAuthentication(authSession)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public Response process(Context context) {

AuthenticationManager.setClientScopesInSession(session, authSession);

ClientSessionContext clientSessionCtx = processor.attachSession();
ClientSessionContext clientSessionCtx = processor.attachSession(false);
clientSessionCtx.setAttribute(Constants.GRANT_TYPE, context.getGrantType());
clientSessionCtx.setAttribute(OAuth2Constants.RESOURCE, formParams.getFirst(OAuth2Constants.RESOURCE));
UserSessionModel userSession = processor.getUserSession();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ private UserSessionModel createUserSession(CIBAAuthenticationRequest request, Ma
}

ClientSessionContext context = AuthenticationProcessor
.attachSession(authSession, null, session, realm, session.getContext().getConnection(), event);
.attachSession(authSession, null, session, realm, session.getContext().getConnection(), event, false);
UserSessionModel userSession = context.getClientSession().getUserSession();

if (userSession == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,11 @@
return this;
}

public RealmBuilder accessCodeLifespanLogin(int accessCodeLifespanLogin) {
rep.setAccessCodeLifespanLogin(accessCodeLifespanLogin);
return this;
}

public RealmBuilder actionTokenGeneratedByUserLifespan(int actionTokenGeneratedByUserLifespan) {
rep.setActionTokenGeneratedByUserLifespan(actionTokenGeneratedByUserLifespan);
return this;
Expand Down Expand Up @@ -838,7 +843,7 @@
* @return this
* @deprecated
*/
public RealmBuilder update(RealmUpdate... update) {

Check warning on line 846 in test-framework/builders/src/main/java/org/keycloak/testframework/realm/RealmBuilder.java

View workflow job for this annotation

GitHub Actions / Test Framework

deprecated item is not annotated with @deprecated
Arrays.stream(update).forEach(u -> u.update(rep));
return this;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package org.keycloak.tests.forms;

import java.time.Duration;

import org.keycloak.authentication.authenticators.browser.CookieAuthenticatorFactory;
import org.keycloak.authentication.authenticators.browser.PasswordFormFactory;
import org.keycloak.authentication.authenticators.browser.UsernamePasswordFormFactory;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.InjectUser;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.injection.LifeCycle;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.AuthenticationExecutionExportBuilder;
import org.keycloak.testframework.realm.AuthenticationFlowBuilder;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.ManagedUser;
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.remote.providers.timeoffset.InfinispanTimeUtil;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.remote.timeoffset.InjectTimeOffSet;
import org.keycloak.testframework.remote.timeoffset.TimeOffSet;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.page.PasswordPage;
import org.keycloak.tests.common.BasicUserConfig;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
*
* @author rmartinc
*/
@KeycloakIntegrationTest
public class AuthCookieAndPasswordLoginTest {

@InjectRealm(config = AuthCookieAndPasswordLoginRealmConfig.class)
ManagedRealm managedRealm;

@InjectUser(config = BasicUserConfig.class, lifecycle = LifeCycle.METHOD)
ManagedUser testUser;

@InjectOAuthClient
OAuthClient oauth;

@InjectPage
PasswordPage passwordPage;

@InjectTimeOffSet
TimeOffSet timeOffSet;

@InjectRunOnServer
RunOnServerClient runOnServer;

@Test
public void cookieAndPasswordLogin() throws Exception {
// login normally using the username and password page
oauth.doLogin(testUser.getUsername(), testUser.getPassword());
Assertions.assertTrue(oauth.parseLoginResponse().isSuccess());

// using cookie and password
oauth.openLoginForm();
passwordPage.assertCurrent();
Assertions.assertEquals(testUser.getUsername(), passwordPage.getAttemptedUsername());
passwordPage.fillPassword(testUser.getPassword());
passwordPage.submit();
Assertions.assertTrue(oauth.parseLoginResponse().isSuccess());

runOnServer.run(InfinispanTimeUtil.enableTestingTimeService());
try {
// expire the login using 10 seconds for login
managedRealm.updateWithCleanup(r -> r.accessCodeLifespanUserAction(10).accessCodeLifespanLogin(10));
oauth.openLoginForm();
passwordPage.assertCurrent();
Assertions.assertEquals(testUser.getUsername(), passwordPage.getAttemptedUsername());
timeOffSet.set(Duration.ofSeconds(70));
passwordPage.fillPassword(testUser.getPassword());
passwordPage.submit();
Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.",
passwordPage.getErrorMessage().orElse(null));

// login again should success
passwordPage.fillPassword(testUser.getPassword());
passwordPage.submit();
Assertions.assertTrue(oauth.parseLoginResponse().isSuccess());
} finally {
runOnServer.run(InfinispanTimeUtil.disableTestingTimeService());
}
}

static class AuthCookieAndPasswordLoginRealmConfig implements RealmConfig {

@Override
public RealmBuilder configure(RealmBuilder realm) {
return realm.name("test").authenticationFlows(
AuthenticationFlowBuilder.create("step-cookie", "SSO auth-cookie flow", "basic-flow", false, false)
.authenticationExecutions(
AuthenticationExecutionExportBuilder.authenticator(CookieAuthenticatorFactory.PROVIDER_ID,
AuthenticationExecutionModel.Requirement.REQUIRED.name(), 10, false),
AuthenticationExecutionExportBuilder.authenticator(PasswordFormFactory.PROVIDER_ID,
AuthenticationExecutionModel.Requirement.REQUIRED.name(), 20, false)),
AuthenticationFlowBuilder.create("step-forms", "Username Password flow", "basic-flow", false, false)
.authenticationExecutions(
AuthenticationExecutionExportBuilder.authenticator(UsernamePasswordFormFactory.PROVIDER_ID,
AuthenticationExecutionModel.Requirement.REQUIRED.name(), 10, false)),
AuthenticationFlowBuilder.create("cookie-password-browser", "Cookie and password browser", "basic-flow", true, false)
.authenticationExecutions(
AuthenticationExecutionExportBuilder.alias("step-cookie",
AuthenticationExecutionModel.Requirement.ALTERNATIVE.name(), 10, false),
AuthenticationExecutionExportBuilder.alias("step-forms",
AuthenticationExecutionModel.Requirement.ALTERNATIVE.name(), 20, false)))
.browserFlow("cookie-password-browser");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,12 @@ public abstract class AbstractAppInitiatedActionTest extends AbstractChangeImpor
protected abstract String getAiaAction();

protected void doAIA() {
doAIA(getAiaAction());
}

protected void doAIA(String action) {
UriBuilder builder = OIDCLoginProtocolService.authUrl(authServerPage.createUriBuilder());
String uri = builder.queryParam(KC_ACTION, getAiaAction())
String uri = builder.queryParam(KC_ACTION, action)
.queryParam(RESPONSE_TYPE, "code")
.queryParam(CLIENT_ID, "test-app")
.queryParam(SCOPE, "openid")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import org.keycloak.common.VerificationException;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
Expand All @@ -38,6 +40,7 @@
import org.keycloak.testsuite.arquillian.annotation.IgnoreBrowserDriver;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.InfoPage;
import org.keycloak.testsuite.pages.LoginPasswordUpdatePage;
import org.keycloak.testsuite.util.MailServer;
import org.keycloak.testsuite.util.MailUtils;
import org.keycloak.testsuite.util.WaitUtils;
Expand Down Expand Up @@ -69,6 +72,9 @@ public class AppInitiatedActionUpdateEmailWithVerificationTest extends AbstractA
@Page
protected ErrorPage errorPage;

@Page
protected LoginPasswordUpdatePage changePasswordPage;

@Override
public void configureTestRealm(RealmRepresentation testRealm) {
testRealm.setVerifyEmail(true);
Expand All @@ -81,8 +87,14 @@ protected void prepareUser(UserRepresentation user) {

@Override
protected void changeEmailUsingAIA(String newEmail) throws Exception {
changeEmailUsingAIA(newEmail, true);
}

protected void changeEmailUsingAIA(String newEmail, boolean login) throws Exception {
doAIA();
loginPage.login("test-user@localhost", "password");
if (login) {
loginPage.login("test-user@localhost", "password");
}

emailUpdatePage.assertCurrent();
assertTrue(emailUpdatePage.isCancelDisplayed());
Expand All @@ -108,6 +120,32 @@ public void updateEmail() throws Exception {
Assertions.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail());
}

@Test
public void updateEmailAlreadyLoggedIn() throws Exception {
oauth.doLogin("test-user@localhost", "password");
EventAssertion.expectLoginSuccess(events.poll());

changeEmailUsingAIA("new@localhost", false);

EventAssertion.assertSuccess(events.poll()).type(EventType.UPDATE_EMAIL)
.details(Details.PREVIOUS_EMAIL, "test-user@localhost")
.details(Details.UPDATED_EMAIL, "new@localhost");

Assertions.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail());

doAIA(UserModel.RequiredAction.UPDATE_PASSWORD.name());
changePasswordPage.assertCurrent();
assertTrue(changePasswordPage.isCancelDisplayed());

changePasswordPage.changePassword("password", "password");
Assertions.assertNotNull(oauth.parseLoginResponse().getCode());
assertKcActionStatus(SUCCESS);

EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_PASSWORD);
EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_CREDENTIAL).details(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE);
EventAssertion.expectLoginSuccess(events.poll());
}

@Test
public void confirmEmailUpdateAfterThirdPartyEmailUpdate() throws MessagingException, IOException {
doAIA();
Expand Down
Loading