8000 fix: allows verify email working in incognito browser tab after Keycloak restart by pchorus · Pull Request #51089 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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
10000
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ public Response handleToken(VerifyEmailActionToken token, ActionTokenContext<Ver
// Email verified in other browser than the one originally started. Removing original authSession. This authenticationSession would be finished after requiredAction
AuthenticationSessionCompoundId origAuthSession = AuthenticationSessionCompoundId.encoded(token.getCompoundOriginalAuthenticationSessionId());
RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().getRootAuthenticationSession(realm, origAuthSession.getRootSessionId());
session.authenticationSessions().removeRootAuthenticationSession(realm, rootAuthSession);
if (rootAuthSession != null) {
session.authenticationSessions().removeRootAuthenticationSession(realm, rootAuthSession);
}
Comment thread
pchorus marked this conversation as resolved.
Resolved
Comment on lines +140 to +142

if (nextAction == null) {
AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

import org.keycloak.admin.client.resource.AuthenticationManagementResource;
import org.keycloak.authentication.forms.RegistrationPassword;
import org.keycloak.cookie.CookieType;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
Expand All @@ -19,6 +21,8 @@
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RequiredActionProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.services.managers.AuthenticationSessionManager;
import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.testframework.annotations.InjectEvents;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
Expand All @@ -32,13 +36,17 @@
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.remote.timeoffset.InjectT 10000 imeOffSet;
import org.keycloak.testframework.remote.timeoffset.TimeOffSet;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.annotations.InjectWebDriver;
import org.keycloak.testframework.ui.page.InfoPage;
import org.keycloak.testframework.ui.page.LoginPage;
import org.keycloak.testframework.ui.page.LoginPasswordResetPage;
import org.keycloak.testframework.ui.page.LoginPasswordUpdatePage;
import org.keycloak.testframework.ui.page.ProceedPage;
import org.keycloak.testframework.ui.page.RegisterPage;
import org.keycloak.testframework.ui.page.VerifyEmailPage;
import org.keycloak.testframework.ui.webdriver.ManagedWebDriver;
Expand Down Expand Up @@ -77,6 +85,9 @@ public class RegisterWithEmailVerificationTest {
@InjectMailServer
MailServer mailServer;

@InjectRunOnServer
RunOnServerClient runOnServer;

@InjectPage(ref = "loginPage", webDriverRef = "driver")
LoginPage loginPage;

Expand Down Expand Up @@ -110,6 +121,12 @@ public class RegisterWithEmailVerificationTest {
@InjectPage(ref = "changePasswordPage2", webDriverRef = "driver2")
protected LoginPasswordUpdatePage changePasswordPage2;

@InjectPage(ref = "proceedPage2", webDriverRef = "driver2")
ProceedPage proceedPage2;

@InjectPage(ref = "infoPage2", webDriverRef = "driver2")
InfoPage infoPage2;

@Test
public void registerUserSuccessWithEmailVerification() {
realm.updateWithCleanup((realmm) -> realmm.verifyEmail(true));
Expand Down Expand Up @@ -364,6 +381,89 @@ public void registerUserSuccessWithEmailVerification_passwordOnRegisterForm() th
}
}

// Issue 51088 - Verify email link opened in a fresh browser (e.g. incognito tab) after Keycloak was restarted,
// so the original root authentication session no longer exists.
@Test
public void registerUserSuccessWithEmailVerificationInFreshBrowserAfterRestart() throws Exception {
String authConfigId = enableAlwaysSetPasswordOnRegisterForm();
realm.updateWithCleanup((realmm) -> realmm.verifyEmail(true));
String userId = null;
try {
oauth.openLoginForm();
loginPage.clickRegister();
registerPage.assertCurrent();

registerPage.register("firstName", "lastName", "registerUserSuccessWithEmailVerification@email", "registerUserSuccessWithEmailVerification", generatePassword());
verifyEmailPage.assertCurrent();

EventRepresentation registerEvent = events.poll();
EventAssertion.assertSuccess(registerEvent)
.clientId("test-app-oauth")
.details(Details.USERNAME, "registerUserSuccessWithEmailVerification")
.details(Details.EMAIL, "registerUserSuccessWithEmailVerification@email")
.details(Details.REGISTER_METHOD, "form")
.type(EventType.REGISTER);
userId = registerEvent.getUserId();

EventRepresentation sendVerifyEmailEvent = events.poll();
EventAssertion.assertSuccess(sendVerifyEmailEvent)
.details(Details.EMAIL, "registerUserSuccessWithEmailVerification@email".toLowerCase())
.userId(userId)
.type(EventType.SEND_VERIFY_EMAIL);

MimeMessage message = mailServer.getReceivedMessages()[0];
String link = MailUtils.getPasswordResetEmailLink(message);
Comment on lines +414 to +415

// Simulate a Keycloak restart before the user clicks the link: the in-memory root authentication
// session created during registration is lost.
removeRootAuthenticationSession();

// Open the verification link in a fresh browser (e.g. an incognito tab) without any auth session cookie.
// As the original authentication session is gone, a confirmation page asking to proceed is shown.
driver2.open(link);
proceedPage2.assertCurrent();
proceedPage2.clickProceedLink();

// Before the fix this failed with a NullPointerException because the original root authentication
// session referenced by the token no longer existed. Now the email is verified successfully.
infoPage2.assertCurrent();
assertThat(infoPage2.getInfo(), is("Your email address has been verified."));

EventRepresentation reqActionEmailEvent = events.poll();
EventAssertion.assertSuccess(reqActionEmailEvent)
.details(Details.EMAIL, "registerUserSuccessWithEmailVerification@email".toLowerCase())
.userId(userId)
.type(EventType.VERIFY_EMAIL);

assertTrue(getUser(userId).isEmailVerified());
} finally {
disableAlwaysSetPasswordOnRegisterForm(authConfigId);
if (userId != null) {
realm.admin().users().delete(userId).close();
}
}
}

/**
* Removes the root authentication session held by the first browser on the server, simulating the loss of
* in-memory authentication sessions that happens when Keycloak is restarted.
*/
private void removeRootAuthenticationSession() {
String encodedAuthSessionId = driver.driver().manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()).getValue();
String realmId = realm.getId();
runOnServer.run(session -> {
RealmModel realmModel = session.realms().getRealm(realmId);
session.getContext().setRealm(realmModel);

AuthenticationSessionManager authenticationSessionManager = new AuthenticationSessionManager(session);
String rootAuthSessionId = authenticationSessionManager.decodeBase64AndValidateSignature(encodedAuthSessionId);
RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().getRootAuthenticationSession(realmModel, rootAuthSessionId);
if (rootAuthSession != null) {
session.authenticationSessions().removeRootAuthenticationSession(realmModel, rootAuthSession);
}
});
}

private void updatePasswordOnChangePasswordPage(String userId) {
changePasswordPage.assertCurrent();
String password = generatePassword();
Expand Down
Loading
0