code formatting patched to be close to original and produce better difs

This commit is contained in:
Vlastimil Elias 2015-03-11 09:50:21 +01:00
parent b117409531
commit a49a2f1dc4
19 changed files with 8845 additions and 8834 deletions

View file

@ -19,15 +19,12 @@ public interface RealmModel extends RoleContainerModel {
interface RealmCreationEvent extends ProviderEvent { interface RealmCreationEvent extends ProviderEvent {
RealmModel getCreatedRealm(); RealmModel getCreatedRealm();
} }
interface ClientCreationEvent extends ProviderEvent { interface ClientCreationEvent extends ProviderEvent {
ClientModel getCreatedClient(); ClientModel getCreatedClient();
} }
interface ApplicationCreationEvent extends ClientCreationEvent { interface ApplicationCreationEvent extends ClientCreationEvent {
ApplicationModel getCreatedApplication(); ApplicationModel getCreatedApplication();
} }
interface OAuthClientCreationEvent extends ClientCreationEvent { interface OAuthClientCreationEvent extends ClientCreationEvent {
OAuthClientModel getCreatedOAuthClient(); OAuthClientModel getCreatedOAuthClient();
} }
@ -62,36 +59,23 @@ public interface RealmModel extends RoleContainerModel {
void setRememberMe(boolean rememberMe); void setRememberMe(boolean rememberMe);
// --- brute force settings //--- brute force settings
boolean isBruteForceProtected(); boolean isBruteForceProtected();
void setBruteForceProtected(boolean value); void setBruteForceProtected(boolean value);
int getMaxFailureWaitSeconds(); int getMaxFailureWaitSeconds();
void setMaxFailureWaitSeconds(int val); void setMaxFailureWaitSeconds(int val);
int getWaitIncrementSeconds(); int getWaitIncrementSeconds();
void setWaitIncrementSeconds(int val); void setWaitIncrementSeconds(int val);
int getMinimumQuickLoginWaitSeconds(); int getMinimumQuickLoginWaitSeconds();
void setMinimumQuickLoginWaitSeconds(int val); void setMinimumQuickLoginWaitSeconds(int val);
long getQuickLoginCheckMilliSeconds(); long getQuickLoginCheckMilliSeconds();
void setQuickLoginCheckMilliSeconds(long val); void setQuickLoginCheckMilliSeconds(long val);
int getMaxDeltaTimeSeconds(); int getMaxDeltaTimeSeconds();
void setMaxDeltaTimeSeconds(int val); void setMaxDeltaTimeSeconds(int val);
int getFailureFactor(); int getFailureFactor();
void setFailureFactor(int failureFactor); void setFailureFactor(int failureFactor);
//--- end brute force settings
// --- end brute force settings
boolean isVerifyEmail(); boolean isVerifyEmail();
@ -102,11 +86,9 @@ public interface RealmModel extends RoleContainerModel {
void setResetPasswordAllowed(boolean resetPasswordAllowed); void setResetPasswordAllowed(boolean resetPasswordAllowed);
int getSsoSessionIdleTimeout(); int getSsoSessionIdleTimeout();
void setSsoSessionIdleTimeout(int seconds); void setSsoSessionIdleTimeout(int seconds);
int getSsoSessionMaxLifespan(); int getSsoSessionMaxLifespan();
void setSsoSessionMaxLifespan(int seconds); void setSsoSessionMaxLifespan(int seconds);
int getAccessTokenLifespan(); int getAccessTokenLifespan();
@ -144,11 +126,8 @@ public interface RealmModel extends RoleContainerModel {
void setCodeSecret(String codeSecret); void setCodeSecret(String codeSecret);
X509Certificate getCertificate(); X509Certificate getCertificate();
void setCertificate(X509Certificate certificate); void setCertificate(X509Certificate certificate);
String getCertificatePem(); String getCertificatePem();
void setCertificatePem(String certificate); void setCertificatePem(String certificate);
PrivateKey getPrivateKey(); PrivateKey getPrivateKey();
@ -184,7 +163,6 @@ public interface RealmModel extends RoleContainerModel {
boolean removeApplication(String id); boolean removeApplication(String id);
ApplicationModel getApplicationById(String id); ApplicationModel getApplicationById(String id);
ApplicationModel getApplicationByName(String name); ApplicationModel getApplicationByName(String name);
void updateRequiredCredentials(Set<String> creds); void updateRequiredCredentials(Set<String> creds);
@ -194,9 +172,7 @@ public interface RealmModel extends RoleContainerModel {
OAuthClientModel addOAuthClient(String id, String name); OAuthClientModel addOAuthClient(String id, String name);
OAuthClientModel getOAuthClient(String name); OAuthClientModel getOAuthClient(String name);
OAuthClientModel getOAuthClientById(String id); OAuthClientModel getOAuthClientById(String id);
boolean removeOAuthClient(String id); boolean removeOAuthClient(String id);
List<OAuthClientModel> getOAuthClients(); List<OAuthClientModel> getOAuthClients();

View file

@ -76,8 +76,7 @@ import static org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_APP;
import static org.keycloak.models.UserModel.RequiredAction.UPDATE_PROFILE; import static org.keycloak.models.UserModel.RequiredAction.UPDATE_PROFILE;
/** /**
* <p> * <p></p>
* </p>
* *
* @author Pedro Igor * @author Pedro Igor
*/ */

View file

@ -160,22 +160,19 @@ public class LoginActionsService {
return false; return false;
} else if (!clientCode.isValid(requiredAction)) { } else if (!clientCode.isValid(requiredAction)) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Invalid code, please login again through your application.");
"Invalid code, please login again through your application.");
return false; return false;
} else { } else {
return true; return true;
} }
} }
boolean check(String code, ClientSessionModel.Action requiredAction, boolean check(String code, ClientSessionModel.Action requiredAction, ClientSessionModel.Action alternativeRequiredAction) {
ClientSessionModel.Action alternativeRequiredAction) {
if (!check(code)) { if (!check(code)) {
return false; return false;
} else if (!(clientCode.isValid(requiredAction) || clientCode.isValid(alternativeRequiredAction))) { } else if (!(clientCode.isValid(requiredAction) || clientCode.isValid(alternativeRequiredAction))) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Invalid code, please login again through your application.");
"Invalid code, please login again through your application.");
return false; return false;
} else { } else {
return true; return true;
@ -196,8 +193,7 @@ public class LoginActionsService {
clientCode = ClientSessionCode.parse(code, session, realm); clientCode = ClientSessionCode.parse(code, session, realm);
if (clientCode == null) { if (clientCode == null) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown code, please login again through your application.");
"Unknown code, please login again through your application.");
return false; return false;
} }
return true; return true;
@ -228,8 +224,8 @@ public class LoginActionsService {
clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE); clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE);
} }
LoginFormsProvider forms = Flows.forms(session, realm, clientSession.getClient(), uriInfo).setClientSessionCode( LoginFormsProvider forms = Flows.forms(session, realm, clientSession.getClient(), uriInfo)
clientSessionCode.getCode()); .setClientSessionCode(clientSessionCode.getCode());
return forms.createLogin(); return forms.createLogin();
} }
@ -260,7 +256,8 @@ public class LoginActionsService {
authManager.expireIdentityCookie(realm, uriInfo, clientConnection); authManager.expireIdentityCookie(realm, uriInfo, clientConnection);
return Flows.forms(session, realm, clientSession.getClient(), uriInfo) return Flows.forms(session, realm, clientSession.getClient(), uriInfo)
.setClientSessionCode(clientSessionCode.getCode()).createRegistration(); .setClientSessionCode(clientSessionCode.getCode())
.createRegistration();
} }
/** /**
@ -273,7 +270,8 @@ public class LoginActionsService {
@Path("request/login") @Path("request/login")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processLogin(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response processLogin(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.LOGIN); event.event(EventType.LOGIN);
if (!checkSsl()) { if (!checkSsl()) {
event.error(Errors.SSL_REQUIRED); event.error(Errors.SSL_REQUIRED);
@ -287,8 +285,7 @@ public class LoginActionsService {
ClientSessionCode clientCode = ClientSessionCode.parse(code, session, realm); ClientSessionCode clientCode = ClientSessionCode.parse(code, session, realm);
if (clientCode == null) { if (clientCode == null) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown code, please login again through your application.");
"Unknown code, please login again through your application.");
} }
ClientSessionModel clientSession = clientCode.getClientSession(); ClientSessionModel clientSession = clientCode.getClientSession();
@ -298,7 +295,8 @@ public class LoginActionsService {
clientCode.setAction(ClientSessionModel.Action.AUTHENTICATE); clientCode.setAction(ClientSessionModel.Action.AUTHENTICATE);
event.client(clientSession.getClient()).error(Errors.EXPIRED_CODE); event.client(clientSession.getClient()).error(Errors.EXPIRED_CODE);
return Flows.forms(this.session, realm, clientSession.getClient(), uriInfo).setError(Messages.EXPIRED_CODE) return Flows.forms(this.session, realm, clientSession.getClient(), uriInfo).setError(Messages.EXPIRED_CODE)
.setClientSessionCode(clientCode.getCode()).createLogin(); .setClientSessionCode(clientCode.getCode())
.createLogin();
} }
String username = formData.getFirst(AuthenticationManager.FORM_USERNAME); String username = formData.getFirst(AuthenticationManager.FORM_USERNAME);
@ -306,8 +304,11 @@ public class LoginActionsService {
String rememberMe = formData.getFirst("rememberMe"); String rememberMe = formData.getFirst("rememberMe");
boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on"); boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on");
event.client(clientSession.getClient().getClientId()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) event.client(clientSession.getClient().getClientId())
.detail(Details.RESPONSE_TYPE, "code").detail(Details.AUTH_METHOD, "form").detail(Details.USERNAME, username); .detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.AUTH_METHOD, "form")
.detail(Details.USERNAME, username);
if (remember) { if (remember) {
event.detail(Details.REMEMBER_ME, "true"); event.detail(Details.REMEMBER_ME, "true");
@ -326,12 +327,12 @@ public class LoginActionsService {
if (formData.containsKey("cancel")) { if (formData.containsKey("cancel")) {
event.error(Errors.REJECTED_BY_USER); event.error(Errors.REJECTED_BY_USER);
LoginProtocol protocol = session.getProvider(LoginProtocol.class, clientSession.getAuthMethod()); LoginProtocol protocol = session.getProvider(LoginProtocol.class, clientSession.getAuthMethod());
protocol.setRealm(realm).setUriInfo(uriInfo); protocol.setRealm(realm)
.setUriInfo(uriInfo);
return protocol.cancelLogin(clientSession); return protocol.cancelLogin(clientSession);
} }
AuthenticationManager.AuthenticationStatus status = authManager.authenticateForm(session, clientConnection, realm, AuthenticationManager.AuthenticationStatus status = authManager.authenticateForm(session, clientConnection, realm, formData);
formData);
if (remember) { if (remember) {
authManager.createRememberMeCookie(realm, username, uriInfo, clientConnection); authManager.createRememberMeCookie(realm, username, uriInfo, clientConnection);
@ -347,37 +348,45 @@ public class LoginActionsService {
switch (status) { switch (status) {
case SUCCESS: case SUCCESS:
case ACTIONS_REQUIRED: case ACTIONS_REQUIRED:
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", remember);
clientConnection.getRemoteAddr(), "form", remember);
TokenManager.attachClientSession(userSession, clientSession); TokenManager.attachClientSession(userSession, clientSession);
event.session(userSession); event.session(userSession);
return authManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, return authManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, uriInfo, event);
uriInfo, event);
case ACCOUNT_TEMPORARILY_DISABLED: case ACCOUNT_TEMPORARILY_DISABLED:
event.error(Errors.USER_TEMPORARILY_DISABLED); event.error(Errors.USER_TEMPORARILY_DISABLED);
return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.ACCOUNT_TEMPORARILY_DISABLED) return Flows.forms(this.session, realm, client, uriInfo)
.setFormData(formData).setClientSessionCode(clientCode.getCode()).createLogin(); .setError(Messages.ACCOUNT_TEMPORARILY_DISABLED)
.setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createLogin();
case ACCOUNT_DISABLED: case ACCOUNT_DISABLED:
event.error(Errors.USER_DISABLED); event.error(Errors.USER_DISABLED);
return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.ACCOUNT_DISABLED) return Flows.forms(this.session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).setFormData(formData).createLogin(); .setError(Messages.ACCOUNT_DISABLED)
.setClientSessionCode(clientCode.getCode())
.setFormData(formData).createLogin();
case MISSING_TOTP: case MISSING_TOTP:
formData.remove(CredentialRepresentation.PASSWORD); formData.remove(CredentialRepresentation.PASSWORD);
String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), user.getId())).rsa256( String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), user.getId())).rsa256(realm.getPrivateKey());
realm.getPrivateKey());
formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken); formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);
return Flows.forms(this.session, realm, client, uriInfo).setFormData(formData) return Flows.forms(this.session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).createLoginTotp(); .setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createLoginTotp();
case INVALID_USER: case INVALID_USER:
event.error(Errors.USER_NOT_FOUND); event.error(Errors.USER_NOT_FOUND);
return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER).setFormData(formData) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER)
.setClientSessionCode(clientCode.getCode()).createLogin(); .setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createLogin();
default: default:
event.error(Errors.INVALID_USER_CREDENTIALS); event.error(Errors.INVALID_USER_CREDENTIALS);
return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER).setFormData(formData) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER)
.setClientSessionCode(clientCode.getCode()).createLogin(); .setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createLogin();
} }
} }
@ -391,7 +400,8 @@ public class LoginActionsService {
@Path("request/registration") @Path("request/registration")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processRegister(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response processRegister(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.REGISTER); event.event(EventType.REGISTER);
if (!checkSsl()) { if (!checkSsl()) {
event.error(Errors.SSL_REQUIRED); event.error(Errors.SSL_REQUIRED);
@ -409,13 +419,11 @@ public class LoginActionsService {
ClientSessionCode clientCode = ClientSessionCode.parse(code, session, realm); ClientSessionCode clientCode = ClientSessionCode.parse(code, session, realm);
if (clientCode == null) { if (clientCode == null) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown code, please login again through your application.");
"Unknown code, please login again through your application.");
} }
if (!clientCode.isValid(ClientSessionModel.Action.AUTHENTICATE)) { if (!clientCode.isValid(ClientSessionModel.Action.AUTHENTICATE)) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Invalid code, please login again through your application.");
"Invalid code, please login again through your application.");
} }
String username = formData.getFirst("username"); String username = formData.getFirst("username");
@ -425,8 +433,11 @@ public class LoginActionsService {
formData.putSingle(AuthenticationManager.FORM_USERNAME, username); formData.putSingle(AuthenticationManager.FORM_USERNAME, username);
} }
ClientSessionModel clientSession = clientCode.getClientSession(); ClientSessionModel clientSession = clientCode.getClientSession();
event.client(clientSession.getClient()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) event.client(clientSession.getClient())
.detail(Details.RESPONSE_TYPE, "code").detail(Details.USERNAME, username).detail(Details.EMAIL, email) .detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.USERNAME, username)
.detail(Details.EMAIL, email)
.detail(Details.REGISTER_METHOD, "form"); .detail(Details.REGISTER_METHOD, "form");
if (!realm.isEnabled()) { if (!realm.isEnabled()) {
@ -457,22 +468,31 @@ public class LoginActionsService {
if (error != null) { if (error != null) {
event.error(Errors.INVALID_REGISTRATION); event.error(Errors.INVALID_REGISTRATION);
return Flows.forms(session, realm, client, uriInfo).setError(error).setFormData(formData) return Flows.forms(session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).createRegistration(); .setError(error)
.setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createRegistration();
} }
// Validate that user with this username doesn't exist in realm or any federation provider // Validate that user with this username doesn't exist in realm or any federation provider
if (session.users().getUserByUsername(username, realm) != null) { if (session.users().getUserByUsername(username, realm) != null) {
event.error(Errors.USERNAME_IN_USE); event.error(Errors.USERNAME_IN_USE);
return Flows.forms(session, realm, client, uriInfo).setError(Messages.USERNAME_EXISTS).setFormData(formData) return Flows.forms(session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).createRegistration(); .setError(Messages.USERNAME_EXISTS)
.setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createRegistration();
} }
// Validate that user with this email doesn't exist in realm or any federation provider // Validate that user with this email doesn't exist in realm or any federation provider
if (session.users().getUserByEmail(email, realm) != null) { if (session.users().getUserByEmail(email, realm) != null) {
event.error(Errors.EMAIL_IN_USE); event.error(Errors.EMAIL_IN_USE);
return Flows.forms(session, realm, client, uriInfo).setError(Messages.EMAIL_EXISTS).setFormData(formData) return Flows.forms(session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).createRegistration(); .setError(Messages.EMAIL_EXISTS)
.setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createRegistration();
} }
UserModel user = session.users().addUser(realm, username); UserModel user = session.users().addUser(realm, username);
@ -500,8 +520,10 @@ public class LoginActionsService {
// User already registered, but force him to update password // User already registered, but force him to update password
if (!passwordUpdateSuccessful) { if (!passwordUpdateSuccessful) {
user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
return Flows.forms(session, realm, client, uriInfo).setError(passwordUpdateError) return Flows.forms(session, realm, client, uriInfo)
.setClientSessionCode(clientCode.getCode()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD); .setError(passwordUpdateError)
.setClientSessionCode(clientCode.getCode())
.createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
} }
} }
@ -541,8 +563,10 @@ public class LoginActionsService {
String redirect = clientSession.getRedirectUri(); String redirect = clientSession.getRedirectUri();
event.client(clientSession.getClient()).user(clientSession.getUserSession().getUser()) event.client(clientSession.getClient())
.detail(Details.RESPONSE_TYPE, "code").detail(Details.REDIRECT_URI, redirect); .user(clientSession.getUserSession().getUser())
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.REDIRECT_URI, redirect);
UserSessionModel userSession = clientSession.getUserSession(); UserSessionModel userSession = clientSession.getUserSession();
if (userSession != null) { if (userSession != null) {
@ -561,7 +585,8 @@ public class LoginActionsService {
event.session(userSession); event.session(userSession);
LoginProtocol protocol = session.getProvider(LoginProtocol.class, clientSession.getAuthMethod()); LoginProtocol protocol = session.getProvider(LoginProtocol.class, clientSession.getAuthMethod());
protocol.setRealm(realm).setUriInfo(uriInfo); protocol.setRealm(realm)
.setUriInfo(uriInfo);
if (formData.containsKey("cancel")) { if (formData.containsKey("cancel")) {
event.error(Errors.REJECTED_BY_USER); event.error(Errors.REJECTED_BY_USER);
return protocol.consentDenied(clientSession); return protocol.consentDenied(clientSession);
@ -569,14 +594,14 @@ public class LoginActionsService {
event.success(); event.success();
return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, clientConnection);
clientConnection);
} }
@Path("profile") @Path("profile")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateProfile(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response updateProfile(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.UPDATE_PROFILE); event.event(EventType.UPDATE_PROFILE);
Checks checks = new Checks(); Checks checks = new Checks();
if (!checks.check(code, ClientSessionModel.Action.UPDATE_PROFILE)) { if (!checks.check(code, ClientSessionModel.Action.UPDATE_PROFILE)) {
@ -592,7 +617,8 @@ public class LoginActionsService {
String error = Validation.validateUpdateProfileForm(formData); String error = Validation.validateUpdateProfileForm(formData);
if (error != null) { if (error != null) {
return Flows.forms(session, realm, null, uriInfo).setUser(user).setError(error) return Flows.forms(session, realm, null, uriInfo).setUser(user).setError(error)
.setClientSessionCode(accessCode.getCode()).createResponse(RequiredAction.UPDATE_PROFILE); .setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PROFILE);
} }
user.setFirstName(formData.getFirst("firstName")); user.setFirstName(formData.getFirst("firstName"));
@ -609,7 +635,8 @@ public class LoginActionsService {
// check for duplicated email // check for duplicated email
if (userByEmail != null && !userByEmail.getId().equals(user.getId())) { if (userByEmail != null && !userByEmail.getId().equals(user.getId())) {
return Flows.forms(session, realm, null, uriInfo).setUser(user).setError(Messages.EMAIL_EXISTS) return Flows.forms(session, realm, null, uriInfo).setUser(user).setError(Messages.EMAIL_EXISTS)
.setClientSessionCode(accessCode.getCode()).createResponse(RequiredAction.UPDATE_PROFILE); .setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PROFILE);
} }
user.setEmail(email); user.setEmail(email);
@ -620,8 +647,7 @@ public class LoginActionsService {
event.clone().event(EventType.UPDATE_PROFILE).success(); event.clone().event(EventType.UPDATE_PROFILE).success();
if (emailChanged) { if (emailChanged) {
event.clone().event(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, oldEmail) event.clone().event(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, oldEmail).detail(Details.UPDATED_EMAIL, email).success();
.detail(Details.UPDATED_EMAIL, email).success();
} }
return redirectOauth(user, accessCode, clientSession, userSession); return redirectOauth(user, accessCode, clientSession, userSession);
@ -630,7 +656,8 @@ public class LoginActionsService {
@Path("totp") @Path("totp")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateTotp(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response updateTotp(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.UPDATE_TOTP); event.event(EventType.UPDATE_TOTP);
Checks checks = new Checks(); Checks checks = new Checks();
if (!checks.check(code, ClientSessionModel.Action.CONFIGURE_TOTP)) { if (!checks.check(code, ClientSessionModel.Action.CONFIGURE_TOTP)) {
@ -648,10 +675,12 @@ public class LoginActionsService {
LoginFormsProvider loginForms = Flows.forms(session, realm, null, uriInfo).setUser(user); LoginFormsProvider loginForms = Flows.forms(session, realm, null, uriInfo).setUser(user);
if (Validation.isEmpty(totp)) { if (Validation.isEmpty(totp)) {
return loginForms.setError(Messages.MISSING_TOTP).setClientSessionCode(accessCode.getCode()) return loginForms.setError(Messages.MISSING_TOTP)
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.CONFIGURE_TOTP); .createResponse(RequiredAction.CONFIGURE_TOTP);
} else if (!new TimeBasedOTP().validate(totp, totpSecret.getBytes())) { } else if (!new TimeBasedOTP().validate(totp, totpSecret.getBytes())) {
return loginForms.setError(Messages.INVALID_TOTP).setClientSessionCode(accessCode.getCode()) return loginForms.setError(Messages.INVALID_TOTP)
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.CONFIGURE_TOTP); .createResponse(RequiredAction.CONFIGURE_TOTP);
} }
@ -690,17 +719,20 @@ public class LoginActionsService {
LoginFormsProvider loginForms = Flows.forms(session, realm, null, uriInfo).setUser(user); LoginFormsProvider loginForms = Flows.forms(session, realm, null, uriInfo).setUser(user);
if (Validation.isEmpty(passwordNew)) { if (Validation.isEmpty(passwordNew)) {
return loginForms.setError(Messages.MISSING_PASSWORD).setClientSessionCode(accessCode.getCode()) return loginForms.setError(Messages.MISSING_PASSWORD)
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} else if (!passwordNew.equals(passwordConfirm)) { } else if (!passwordNew.equals(passwordConfirm)) {
return loginForms.setError(Messages.NOTMATCH_PASSWORD).setClientSessionCode(accessCode.getCode()) return loginForms.setError(Messages.NOTMATCH_PASSWORD)
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} }
try { try {
session.users().updateCredential(realm, user, UserCredentialModel.password(passwordNew)); session.users().updateCredential(realm, user, UserCredentialModel.password(passwordNew));
} catch (Exception ape) { } catch (Exception ape) {
return loginForms.setError(ape.getMessage()).setClientSessionCode(accessCode.getCode()) return loginForms.setError(ape.getMessage())
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} }
@ -711,8 +743,7 @@ public class LoginActionsService {
if (clientSession.getAction().equals(ClientSessionModel.Action.RECOVER_PASSWORD)) { if (clientSession.getAction().equals(ClientSessionModel.Action.RECOVER_PASSWORD)) {
String actionCookieValue = getActionCookie(); String actionCookieValue = getActionCookie();
if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) { if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) {
return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("passwordUpdated") return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("passwordUpdated").createInfoPage();
.createInfoPage();
} }
} }
@ -743,8 +774,7 @@ public class LoginActionsService {
String actionCookieValue = getActionCookie(); String actionCookieValue = getActionCookie();
if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) { if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) {
return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("emailVerified") return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("emailVerified").createInfoPage();
.createInfoPage();
} }
event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN); event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN);
@ -762,8 +792,10 @@ public class LoginActionsService {
createActionCookie(realm, uriInfo, clientConnection, userSession.getId()); createActionCookie(realm, uriInfo, clientConnection, userSession.getId());
return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(accessCode.getCode()) return Flows.forms(session, realm, null, uriInfo)
.setUser(userSession.getUser()).createResponse(RequiredAction.VERIFY_EMAIL); .setClientSessionCode(accessCode.getCode())
.setUser(userSession.getUser())
.createResponse(RequiredAction.VERIFY_EMAIL);
} }
} }
@ -777,10 +809,13 @@ public class LoginActionsService {
return checks.response; return checks.response;
} }
ClientSessionCode accessCode = checks.clientCode; ClientSessionCode accessCode = checks.clientCode;
return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(accessCode.getCode()) return Flows.forms(session, realm, null, uriInfo)
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} else { } else {
return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(code).createPasswordReset(); return Flows.forms(session, realm, null, uriInfo)
.setClientSessionCode(code)
.createPasswordReset();
} }
} }
@ -799,8 +834,7 @@ public class LoginActionsService {
ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm); ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm);
if (accessCode == null) { if (accessCode == null) {
event.error(Errors.INVALID_CODE); event.error(Errors.INVALID_CODE);
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown code, please login again through your application.");
"Unknown code, please login again through your application.");
} }
ClientSessionModel clientSession = accessCode.getClientSession(); ClientSessionModel clientSession = accessCode.getClientSession();
@ -808,14 +842,19 @@ public class LoginActionsService {
ClientModel client = clientSession.getClient(); ClientModel client = clientSession.getClient();
if (client == null) { if (client == null) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown login requester."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Unknown login requester.");
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Login requester not enabled.");
} }
event.client(client.getClientId()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) event.client(client.getClientId())
.detail(Details.RESPONSE_TYPE, "code").detail(Details.AUTH_METHOD, "form").detail(Details.USERNAME, username); .detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.AUTH_METHOD, "form")
.detail(Details.USERNAME, username);
UserModel user = session.users().getUserByUsername(username, realm); UserModel user = session.users().getUserByUsername(username, realm);
if (user == null && username.contains("@")) { if (user == null && username.contains("@")) {
@ -831,8 +870,7 @@ public class LoginActionsService {
} else { } else {
event.user(user); event.user(user);
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false);
clientConnection.getRemoteAddr(), "form", false);
event.session(userSession); event.session(userSession);
TokenManager.attachClientSession(userSession, clientSession); TokenManager.attachClientSession(userSession, clientSession);
@ -852,14 +890,14 @@ public class LoginActionsService {
event.error(Errors.EMAIL_SEND_FAILED); event.error(Errors.EMAIL_SEND_FAILED);
logger.error("Failed to send password reset email", e); logger.error("Failed to send password reset email", e);
return Flows.forms(this.session, realm, client, uriInfo).setError("emailSendError") return Flows.forms(this.session, realm, client, uriInfo).setError("emailSendError")
.setClientSessionCode(accessCode.getCode()).createErrorPage(); .setClientSessionCode(accessCode.getCode())
.createErrorPage();
} }
createActionCookie(realm, uriInfo, clientConnection, userSession.getId()); createActionCookie(realm, uriInfo, clientConnection, userSession.getId());
} }
return Flows.forms(session, realm, client, uriInfo).setSuccess("emailSent") return Flows.forms(session, realm, client, uriInfo).setSuccess("emailSent").setClientSessionCode(accessCode.getCode()).createPasswordReset();
.setClientSessionCode(accessCode.getCode()).createPasswordReset();
} }
private String getActionCookie() { private String getActionCookie() {
@ -882,9 +920,12 @@ public class LoginActionsService {
} }
private void initEvent(ClientSessionModel clientSession) { private void initEvent(ClientSessionModel clientSession) {
event.event(EventType.LOGIN).client(clientSession.getClient()).user(clientSession.getUserSession().getUser()) event.event(EventType.LOGIN).client(clientSession.getClient())
.session(clientSession.getUserSession().getId()).detail(Details.CODE_ID, clientSession.getId()) .user(clientSession.getUserSession().getUser())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri()).detail(Details.RESPONSE_TYPE, "code"); .session(clientSession.getUserSession().getId())
.detail(Details.CODE_ID, clientSession.getId())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.RESPONSE_TYPE, "code");
UserSessionModel userSession = clientSession.getUserSession(); UserSessionModel userSession = clientSession.getUserSession();

View file

@ -13,11 +13,9 @@ import org.keycloak.services.messages.Messages;
public class Validation { public class Validation {
// Actually allow same emails like angular. See ValidationTest.testEmailValidation() // Actually allow same emails like angular. See ValidationTest.testEmailValidation()
private static final Pattern EMAIL_PATTERN = Pattern private static final Pattern EMAIL_PATTERN = Pattern.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*");
.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*");
public static String validateRegistrationForm(RealmModel realm, MultivaluedMap<String, String> formData, public static String validateRegistrationForm(RealmModel realm, MultivaluedMap<String, String> formData, List<String> requiredCredentialTypes) {
List<String> requiredCredentialTypes) {
if (isEmpty(formData.getFirst("firstName"))) { if (isEmpty(formData.getFirst("firstName"))) {
return Messages.MISSING_FIRST_NAME; return Messages.MISSING_FIRST_NAME;
} }

View file

@ -79,10 +79,8 @@ public class AdminAPITest {
ApplicationModel adminConsole = adminRealm.getApplicationByName(Constants.ADMIN_CONSOLE_APPLICATION); ApplicationModel adminConsole = adminRealm.getApplicationByName(Constants.ADMIN_CONSOLE_APPLICATION);
TokenManager tm = new TokenManager(); TokenManager tm = new TokenManager();
UserModel admin = session.users().getUserByUsername("admin", adminRealm); UserModel admin = session.users().getUserByUsername("admin", adminRealm);
UserSessionModel userSession = session.sessions().createUserSession(adminRealm, admin, "admin", null, "form", UserSessionModel userSession = session.sessions().createUserSession(adminRealm, admin, "admin", null, "form", false);
false); AccessToken token = tm.createClientAccessToken(session, tm.getAccess(null, adminConsole, admin), adminRealm, adminConsole, admin, userSession, null);
AccessToken token = tm.createClientAccessToken(session, tm.getAccess(null, adminConsole, admin), adminRealm,
adminConsole, admin, userSession, null);
return tm.encodeToken(adminRealm, token); return tm.encodeToken(adminRealm, token);
} finally { } finally {
keycloakRule.stopSession(session, true); keycloakRule.stopSession(session, true);
@ -140,8 +138,7 @@ public class AdminAPITest {
CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class); CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class);
if (appRep.getSecret() != null) if (appRep.getSecret() != null)
Assert.assertEquals(appRep.getSecret(), cred.getValue()); Assert.assertEquals(appRep.getSecret(), cred.getValue());
CredentialRepresentation newCred = appTarget.path("client-secret").request() CredentialRepresentation newCred = appTarget.path("client-secret").request().post(null, CredentialRepresentation.class);
.post(null, CredentialRepresentation.class);
Assert.assertNotEquals(newCred.getValue(), cred.getValue()); Assert.assertNotEquals(newCred.getValue(), cred.getValue());
Response appUpdateResponse = appTarget.request().put(Entity.json(appRep)); Response appUpdateResponse = appTarget.request().put(Entity.json(appRep));