KEYCLOAK-286 Allow login with username or email. KEYCLOAK-287 Remove recover username as we now support login with email

This commit is contained in:
Stian Thorgersen 2014-02-21 15:25:40 +00:00
parent cd68462cf3
commit 05bd92d765
14 changed files with 133 additions and 207 deletions

View file

@ -8,10 +8,10 @@
<form id="kc-reset-password-form" class="${properties.kcFormClass!}" action="${url.loginPasswordResetUrl}" method="post"> <form id="kc-reset-password-form" class="${properties.kcFormClass!}" action="${url.loginPasswordResetUrl}" method="post">
<div class="${properties.kcFormGroupClass!}"> <div class="${properties.kcFormGroupClass!}">
<div class="${properties.kcLabelWrapperClass!}"> <div class="${properties.kcLabelWrapperClass!}">
<label for="email" class="${properties.kcLabelClass!}">${rb.email}</label> <label for="username" class="${properties.kcLabelClass!}">${rb.usernameOrEmail}</label>
</div> </div>
<div class="${properties.kcInputWrapperClass!}"> <div class="${properties.kcInputWrapperClass!}">
<input type="text" id="email" name="email" class="${properties.kcInputClass!}" /> <input type="text" id="username" name="username" class="${properties.kcInputClass!}" />
</div> </div>
</div> </div>

View file

@ -8,7 +8,7 @@
<form id="kc-form-login" class="${properties.kcFormClass!}" action="${url.loginAction}" method="post"> <form id="kc-form-login" class="${properties.kcFormClass!}" action="${url.loginAction}" method="post">
<div class="${properties.kcFormGroupClass!}"> <div class="${properties.kcFormGroupClass!}">
<div class="${properties.kcLabelWrapperClass!}"> <div class="${properties.kcLabelWrapperClass!}">
<label for="username" class="${properties.kcLabelClass!}">${rb.username}</label> <label for="username" class="${properties.kcLabelClass!}">${rb.usernameOrEmail}</label>
</div> </div>
<div class="${properties.kcInputWrapperClass!}"> <div class="${properties.kcInputWrapperClass!}">
@ -33,7 +33,7 @@
<span>${rb.noAccount} <a href="${url.registrationUrl}">${rb.register}</a></span> <span>${rb.noAccount} <a href="${url.registrationUrl}">${rb.register}</a></span>
</#if> </#if>
<#if realm.resetPasswordAllowed> <#if realm.resetPasswordAllowed>
<span>${rb.loginForgot} <a href="${url.loginUsernameReminderUrl}">${rb.username}</a> or <a href="${url.loginPasswordResetUrl}">${rb.password}</a>?</span> <span>${rb.loginForgot} <a href="${url.loginPasswordResetUrl}">${rb.password}</a>?</span>
</#if> </#if>
</div> </div>
</div> </div>

View file

@ -10,12 +10,13 @@ alreadyHaveAccount=Already have an account?
poweredByKeycloak=Powered by Keycloak poweredByKeycloak=Powered by Keycloak
username=Username username=Username
usernameOrEmail=Username or email
fullName=Full name fullName=Full name
firstName=First name firstName=First name
lastName=Last name lastName=Last name
email=Email email=Email
password=Password password=Password
passwordConfirm=Confirmation passwordConfirm=Confirm password
passwordNew=New Password passwordNew=New Password
passwordNewConfirm=New Password confirmation passwordNewConfirm=New Password confirmation
cancel=Cancel cancel=Cancel
@ -97,11 +98,7 @@ emailSent=You should receive an email shortly with further instructions.
emailSendError=Failed to send email, please try again later emailSendError=Failed to send email, please try again later
emailError=Invalid email. emailError=Invalid email.
emailErrorInfo=Please, fill in the fields again. emailErrorInfo=Please, fill in the fields again.
emailInstruction=Enter your email address and we will send you instructions on how to create a new password. emailInstruction=Enter your username or email address and we will send you instructions on how to create a new password.
emailUsernameForgotHeader=Forgot Your Username?
emailUsernameInstruction=Enter your email address and we will send you an email with your username.
emailUsernameSent=You should receive an email shortly with your username.
accountUpdated=Your account has been updated accountUpdated=Your account has been updated
accountPasswordUpdated=Your password has been updated accountPasswordUpdated=Your password has been updated

View file

@ -24,6 +24,7 @@
#kc-login { #kc-login {
float: right; float: right;
margin-left: 10px; margin-left: 10px;
margin-bottom: 10px;
} }

View file

@ -15,10 +15,10 @@ kcFormAreaClass=col-sm-7 col-md-6 col-lg-5 login
kcFormClass=form-horizontal kcFormClass=form-horizontal
kcFormGroupClass=form-group kcFormGroupClass=form-group
kcLabelClass=control-label kcLabelClass=control-label
kcLabelWrapperClass=col-sm-2 col-md-2 kcLabelWrapperClass=col-sm-4 col-md-4 col-lg-3
kcInputClass=form-control kcInputClass=form-control
kcInputWrapperClass=col-sm-10 col-md-10 kcInputWrapperClass=col-sm-8 col-md-8 col-lg-9
kcFormOptionsClass=col-xs-8 col-sm-offset-2 col-sm-5 col-md-offset-2 col-md-5 kcFormOptionsClass=col-sm-offset-4 col-sm-4 col-md-offset-4 col-md-4 col-lg-offset-3 col-lg-5
kcFormButtonsClass=col-xs-4 col-sm-5 col-md-5 submit kcFormButtonsClass=col-sm-4 col-md-4 col-lg-4 submit
kcInfoAreaClass=col-sm-5 col-md-6 col-lg-7 details kcInfoAreaClass=col-sm-5 col-md-6 col-lg-7 details

View file

@ -18,8 +18,6 @@ public interface LoginForms {
public Response createPasswordReset(); public Response createPasswordReset();
public Response createUsernameReminder();
public Response createLoginTotp(); public Response createLoginTotp();
public Response createRegistration(); public Response createRegistration();

View file

@ -23,8 +23,6 @@ public class Templates {
return "login-reset-password.ftl"; return "login-reset-password.ftl";
case LOGIN_UPDATE_PASSWORD: case LOGIN_UPDATE_PASSWORD:
return "login-update-password.ftl"; return "login-update-password.ftl";
case LOGIN_USERNAME_REMINDER:
return "login-username-reminder.ftl";
case REGISTER: case REGISTER:
return "register.ftl"; return "register.ftl";
case ERROR: case ERROR:

View file

@ -145,16 +145,6 @@ public class EmailSender {
send(user.getEmail(), "Reset password link", sb.toString()); send(user.getEmail(), "Reset password link", sb.toString());
} }
public void sendUsernameReminder(UserModel user) throws EmailException {
StringBuilder sb = getHeader(user);
sb.append("The username for your Keycloak account is ").append(user.getLoginName()).append(".\n");
addFooter(sb);
send(user.getEmail(), "Username reminder", sb.toString());
}
private StringBuilder getHeader(UserModel user) { private StringBuilder getHeader(UserModel user) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View file

@ -237,7 +237,7 @@ public class RequiredActionsService {
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendPasswordReset(final MultivaluedMap<String, String> formData) { public Response sendPasswordReset(final MultivaluedMap<String, String> formData) {
String email = formData.getFirst("email"); String username = formData.getFirst("username");
String scopeParam = uriInfo.getQueryParameters().getFirst("scope"); String scopeParam = uriInfo.getQueryParameters().getFirst("scope");
String state = uriInfo.getQueryParameters().getFirst("state"); String state = uriInfo.getQueryParameters().getFirst("state");
@ -254,11 +254,14 @@ public class RequiredActionsService {
"Login requester not enabled."); "Login requester not enabled.");
} }
UserModel user = realm.getUserByEmail(email); UserModel user = realm.getUser(username);
if (user == null) { if (user == null && username.contains("@")) {
return Flows.forms(realm, request, uriInfo).setError("emailError").createPasswordReset(); user = realm.getUserByEmail(username);
} }
if (user == null) {
logger.warn("Failed to send password reset email: user not found");
} else {
Set<RequiredAction> requiredActions = new HashSet<RequiredAction>(user.getRequiredActions()); Set<RequiredAction> requiredActions = new HashSet<RequiredAction>(user.getRequiredActions());
requiredActions.add(RequiredAction.UPDATE_PASSWORD); requiredActions.add(RequiredAction.UPDATE_PASSWORD);
@ -272,49 +275,11 @@ public class RequiredActionsService {
logger.error("Failed to send password reset email", e); logger.error("Failed to send password reset email", e);
return Flows.forms(realm, request, uriInfo).setError("emailSendError").createErrorPage(); return Flows.forms(realm, request, uriInfo).setError("emailSendError").createErrorPage();
} }
}
return Flows.forms(realm, request, uriInfo).setSuccess("emailSent").createPasswordReset(); return Flows.forms(realm, request, uriInfo).setSuccess("emailSent").createPasswordReset();
} }
@Path("username-reminder")
@GET
public Response usernameReminder() {
return Flows.forms(realm, request, uriInfo).createUsernameReminder();
}
@Path("username-reminder")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendUsernameReminder(final MultivaluedMap<String, String> formData) {
String email = formData.getFirst("email");
String clientId = uriInfo.getQueryParameters().getFirst("client_id");
UserModel client = realm.getUser(clientId);
if (client == null) {
return Flows.oauth(realm, request, uriInfo, authManager, tokenManager).forwardToSecurityFailure(
"Unknown login requester.");
}
if (!client.isEnabled()) {
return Flows.oauth(realm, request, uriInfo, authManager, tokenManager).forwardToSecurityFailure(
"Login requester not enabled.");
}
UserModel user = realm.getUserByEmail(email);
if (user == null) {
return Flows.forms(realm, request, uriInfo).setError("emailError").createUsernameReminder();
}
try {
new EmailSender(realm.getSmtpConfig()).sendUsernameReminder(user);
} catch (EmailException e) {
logger.error("Failed to send username reminder email", e);
return Flows.forms(realm, request, uriInfo).setError("emailSendError").createErrorPage();
}
return Flows.forms(realm, request, uriInfo).setSuccess("emailUsernameSent").createLogin();
}
private AccessCodeEntry getAccessCodeEntry(RequiredAction requiredAction) { private AccessCodeEntry getAccessCodeEntry(RequiredAction requiredAction) {
String code = uriInfo.getQueryParameters().getFirst("code"); String code = uriInfo.getQueryParameters().getFirst("code");
if (code == null) { if (code == null) {

View file

@ -226,6 +226,9 @@ public class TokenService {
String username = formData.getFirst("username"); String username = formData.getFirst("username");
UserModel user = realm.getUser(username); UserModel user = realm.getUser(username);
if (user == null && username.contains("@")) {
user = realm.getUserByEmail(username);
}
if (user == null){ if (user == null){
return Flows.forms(realm, request, uriInfo).setError(Messages.INVALID_USER).setFormData(formData).createLogin(); return Flows.forms(realm, request, uriInfo).setError(Messages.INVALID_USER).setFormData(formData).createLogin();

View file

@ -1,109 +0,0 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.testsuite.forms;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.AppPage.RequestType;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginPasswordResetPage;
import org.keycloak.testsuite.pages.LoginPasswordUpdatePage;
import org.keycloak.testsuite.pages.LoginRecoverUsernamePage;
import org.keycloak.testsuite.rule.GreenMailRule;
import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.openqa.selenium.WebDriver;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class LoginRecoverUsernameTest {
@ClassRule
public static KeycloakRule keycloakRule = new KeycloakRule();
@Rule
public WebRule webRule = new WebRule(this);
@Rule
public GreenMailRule greenMail = new GreenMailRule();
@WebResource
protected WebDriver driver;
@WebResource
protected OAuthClient oauth;
@WebResource
protected AppPage appPage;
@WebResource
protected LoginPage loginPage;
@WebResource
protected LoginRecoverUsernamePage recoverUsernamePage;
@Test
public void resetPassword() throws IOException, MessagingException {
loginPage.open();
loginPage.recoverUsername();
recoverUsernamePage.assertCurrent();
recoverUsernamePage.recoverUsername("test-user@localhost");
loginPage.assertCurrent();
Assert.assertTrue(driver.getPageSource().contains("You should receive an email shortly with your username"));
Assert.assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String body = (String) message.getContent();
Assert.assertTrue(body.contains("The username for your Keycloak account is test-user@localhost"));
}
@Test
public void resetPasswordWrongEmail() throws IOException, MessagingException {
loginPage.open();
loginPage.recoverUsername();
recoverUsernamePage.assertCurrent();
recoverUsernamePage.recoverUsername("invalid");
recoverUsernamePage.assertCurrent();
Assert.assertEquals("Invalid email.", recoverUsernamePage.getMessage());
}
}

View file

@ -25,6 +25,11 @@ import org.junit.Assert;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.OAuthClient; import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.AppPage.RequestType; import org.keycloak.testsuite.pages.AppPage.RequestType;
@ -40,7 +45,20 @@ import org.openqa.selenium.WebDriver;
public class LoginTest { public class LoginTest {
@ClassRule @ClassRule
public static KeycloakRule keycloakRule = new KeycloakRule(); public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
UserModel user = appRealm.addUser("login-test");
user.setEmail("login@test.com");
user.setEnabled(true);
UserCredentialModel creds = new UserCredentialModel();
creds.setType(CredentialRepresentation.PASSWORD);
creds.setValue("password");
appRealm.updateCredential(user, creds);
}
});
@Rule @Rule
public WebRule webRule = new WebRule(this); public WebRule webRule = new WebRule(this);
@ -48,7 +66,6 @@ public class LoginTest {
@WebResource @WebResource
protected OAuthClient oauth; protected OAuthClient oauth;
@WebResource @WebResource
protected WebDriver driver; protected WebDriver driver;
@ -61,7 +78,7 @@ public class LoginTest {
@Test @Test
public void loginInvalidPassword() { public void loginInvalidPassword() {
loginPage.open(); loginPage.open();
loginPage.login("test-user@localhost", "invalid"); loginPage.login("login-test", "invalid");
loginPage.assertCurrent(); loginPage.assertCurrent();
@ -81,7 +98,16 @@ public class LoginTest {
@Test @Test
public void loginSuccess() { public void loginSuccess() {
loginPage.open(); loginPage.open();
loginPage.login("test-user@localhost", "password"); loginPage.login("login-test", "password");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
Assert.assertNotNull(oauth.getCurrentQuery().get("code"));
}
@Test
public void loginWithEmailSuccess() {
loginPage.open();
loginPage.login("login@test.com", "password");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
Assert.assertNotNull(oauth.getCurrentQuery().get("code")); Assert.assertNotNull(oauth.getCurrentQuery().get("code"));

View file

@ -27,6 +27,9 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.keycloak.models.PasswordPolicy; import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.OAuthClient; import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.AppPage;
@ -50,7 +53,20 @@ import java.io.IOException;
public class ResetPasswordTest { public class ResetPasswordTest {
@ClassRule @ClassRule
public static KeycloakRule keycloakRule = new KeycloakRule(); public static KeycloakRule keycloakRule = new KeycloakRule((new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
UserModel user = appRealm.addUser("login-test");
user.setEmail("login@test.com");
user.setEnabled(true);
UserCredentialModel creds = new UserCredentialModel();
creds.setType(CredentialRepresentation.PASSWORD);
creds.setValue("password");
appRealm.updateCredential(user, creds);
}
}));
@Rule @Rule
public WebRule webRule = new WebRule(this); public WebRule webRule = new WebRule(this);
@ -83,7 +99,7 @@ public class ResetPasswordTest {
resetPasswordPage.assertCurrent(); resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("test-user@localhost"); resetPasswordPage.changePassword("login-test");
resetPasswordPage.assertCurrent(); resetPasswordPage.assertCurrent();
@ -100,7 +116,7 @@ public class ResetPasswordTest {
updatePasswordPage.assertCurrent(); updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("new-password", "new-password"); updatePasswordPage.changePassword("resetPassword", "resetPassword");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
@ -108,13 +124,50 @@ public class ResetPasswordTest {
loginPage.open(); loginPage.open();
loginPage.login("test-user@localhost", "new-password"); loginPage.login("login-test", "resetPassword");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
} }
@Test @Test
public void resetPasswordWrongEmail() throws IOException, MessagingException { public void resetPasswordByEmail() throws IOException, MessagingException {
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login@test.com");
resetPasswordPage.assertCurrent();
Assert.assertEquals("You should receive an email shortly with further instructions.", resetPasswordPage.getSuccessMessage());
Assert.assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String body = (String) message.getContent();
String changePasswordUrl = body.split("\n")[3];
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("resetPassword", "resetPassword");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
oauth.openLogout();
loginPage.open();
loginPage.login("login@test.com", "resetPassword");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
}
@Test
public void resetPasswordWrongEmail() throws IOException, MessagingException, InterruptedException {
loginPage.open(); loginPage.open();
loginPage.resetPassword(); loginPage.resetPassword();
@ -124,7 +177,11 @@ public class ResetPasswordTest {
resetPasswordPage.assertCurrent(); resetPasswordPage.assertCurrent();
Assert.assertEquals("Invalid email.", resetPasswordPage.getErrorMessage()); Assert.assertEquals("You should receive an email shortly with further instructions.", resetPasswordPage.getSuccessMessage());
Thread.sleep(1000);
Assert.assertEquals(0, greenMail.getReceivedMessages().length);
} }
@Test @Test
@ -141,7 +198,7 @@ public class ResetPasswordTest {
resetPasswordPage.assertCurrent(); resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("test-user@localhost"); resetPasswordPage.changePassword("login-test");
resetPasswordPage.assertCurrent(); resetPasswordPage.assertCurrent();
@ -162,7 +219,7 @@ public class ResetPasswordTest {
Assert.assertEquals("Invalid password: minimum length 8", resetPasswordPage.getErrorMessage()); Assert.assertEquals("Invalid password: minimum length 8", resetPasswordPage.getErrorMessage());
updatePasswordPage.changePassword("new-password", "new-password"); updatePasswordPage.changePassword("resetPasswordWithPasswordPolicy", "resetPasswordWithPasswordPolicy");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
@ -170,7 +227,7 @@ public class ResetPasswordTest {
loginPage.open(); loginPage.open();
loginPage.login("test-user@localhost", "new-password"); loginPage.login("login-test", "resetPasswordWithPasswordPolicy");
Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
} }

View file

@ -29,8 +29,8 @@ import org.openqa.selenium.support.FindBy;
*/ */
public class LoginPasswordResetPage extends AbstractPage { public class LoginPasswordResetPage extends AbstractPage {
@FindBy(id = "email") @FindBy(id = "username")
private WebElement emailInput; private WebElement usernameInput;
@FindBy(css = "input[type=\"submit\"]") @FindBy(css = "input[type=\"submit\"]")
private WebElement submitButton; private WebElement submitButton;
@ -41,8 +41,8 @@ public class LoginPasswordResetPage extends AbstractPage {
@FindBy(className = "feedback-error") @FindBy(className = "feedback-error")
private WebElement emailErrorMessage; private WebElement emailErrorMessage;
public void changePassword(String email) { public void changePassword(String username) {
emailInput.sendKeys(email); usernameInput.sendKeys(username);
submitButton.click(); submitButton.click();
} }