KEYCLOAK-1074 - Allow registration with email as username (without

username as separate field)
This commit is contained in:
Vlastimil Elias 2015-03-10 16:28:57 +01:00
parent 453d29f188
commit b117409531
24 changed files with 9103 additions and 8703 deletions

View file

@ -93,6 +93,7 @@
<addColumn tableName="REALM"> <addColumn tableName="REALM">
<column name="LOGIN_LIFESPAN" type="INT"/> <column name="LOGIN_LIFESPAN" type="INT"/>
<column name="REGISTRATION_EMAIL_AS_USERNAME" type="BOOLEAN" defaultValueBoolean="false"/>
</addColumn> </addColumn>
</changeSet> </changeSet>
</databaseChangeLog> </databaseChangeLog>

View file

@ -24,6 +24,7 @@ public class RealmRepresentation {
protected String sslRequired; protected String sslRequired;
protected Boolean passwordCredentialGrantAllowed; protected Boolean passwordCredentialGrantAllowed;
protected Boolean registrationAllowed; protected Boolean registrationAllowed;
protected Boolean registrationEmailAsUsername;
protected Boolean rememberMe; protected Boolean rememberMe;
protected Boolean verifyEmail; protected Boolean verifyEmail;
protected Boolean resetPasswordAllowed; protected Boolean resetPasswordAllowed;
@ -31,7 +32,7 @@ public class RealmRepresentation {
protected Boolean userCacheEnabled; protected Boolean userCacheEnabled;
protected Boolean realmCacheEnabled; protected Boolean realmCacheEnabled;
//--- brute force settings // --- brute force settings
protected Boolean bruteForceProtected; protected Boolean bruteForceProtected;
protected Integer maxFailureWaitSeconds; protected Integer maxFailureWaitSeconds;
protected Integer minimumQuickLoginWaitSeconds; protected Integer minimumQuickLoginWaitSeconds;
@ -39,7 +40,7 @@ public class RealmRepresentation {
protected Long quickLoginCheckMilliSeconds; protected Long quickLoginCheckMilliSeconds;
protected Integer maxDeltaTimeSeconds; protected Integer maxDeltaTimeSeconds;
protected Integer failureFactor; protected Integer failureFactor;
//--- end brute force settings // --- end brute force settings
protected String privateKey; protected String privateKey;
protected String publicKey; protected String publicKey;
@ -94,7 +95,8 @@ public class RealmRepresentation {
public ApplicationRepresentation resource(String name) { public ApplicationRepresentation resource(String name) {
ApplicationRepresentation resource = new ApplicationRepresentation(); ApplicationRepresentation resource = new ApplicationRepresentation();
if (applications == null) applications = new ArrayList<ApplicationRepresentation>(); if (applications == null)
applications = new ArrayList<ApplicationRepresentation>();
applications.add(resource); applications.add(resource);
resource.setName(name); resource.setName(name);
return resource; return resource;
@ -107,7 +109,8 @@ public class RealmRepresentation {
public UserRepresentation user(String username) { public UserRepresentation user(String username) {
UserRepresentation user = new UserRepresentation(); UserRepresentation user = new UserRepresentation();
user.setUsername(username); user.setUsername(username);
if (users == null) users = new ArrayList<UserRepresentation>(); if (users == null)
users = new ArrayList<UserRepresentation>();
users.add(user); users.add(user);
return user; return user;
} }
@ -163,7 +166,8 @@ public class RealmRepresentation {
public ScopeMappingRepresentation scopeMapping(String username) { public ScopeMappingRepresentation scopeMapping(String username) {
ScopeMappingRepresentation mapping = new ScopeMappingRepresentation(); ScopeMappingRepresentation mapping = new ScopeMappingRepresentation();
mapping.setClient(username); mapping.setClient(username);
if (scopeMappings == null) scopeMappings = new ArrayList<ScopeMappingRepresentation>(); if (scopeMappings == null)
scopeMappings = new ArrayList<ScopeMappingRepresentation>();
scopeMappings.add(mapping); scopeMappings.add(mapping);
return mapping; return mapping;
} }
@ -264,6 +268,14 @@ public class RealmRepresentation {
this.registrationAllowed = registrationAllowed; this.registrationAllowed = registrationAllowed;
} }
public Boolean isRegistrationEmailAsUsername() {
return registrationEmailAsUsername;
}
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
this.registrationEmailAsUsername = registrationEmailAsUsername;
}
public Boolean isRememberMe() { public Boolean isRememberMe() {
return rememberMe; return rememberMe;
} }
@ -497,7 +509,8 @@ public class RealmRepresentation {
} }
public void addProtocolMapper(ProtocolMapperRepresentation rep) { public void addProtocolMapper(ProtocolMapperRepresentation rep) {
if (protocolMappers == null) protocolMappers = new LinkedList<ProtocolMapperRepresentation>(); if (protocolMappers == null)
protocolMappers = new LinkedList<ProtocolMapperRepresentation>();
protocolMappers.add(rep); protocolMappers.add(rep);
} }

View file

@ -36,6 +36,7 @@ public interface Errors {
String NOT_ALLOWED = "not_allowed"; String NOT_ALLOWED = "not_allowed";
String FEDERATED_IDENTITY_EMAIL_EXISTS = "federated_identity_email_exists"; String FEDERATED_IDENTITY_EMAIL_EXISTS = "federated_identity_email_exists";
String FEDERATED_IDENTITY_REGISTRATION_EMAIL_MISSING = "federated_identity_registration_email_missing";
String FEDERATED_IDENTITY_USERNAME_EXISTS = "federated_identity_username_exists"; String FEDERATED_IDENTITY_USERNAME_EXISTS = "federated_identity_username_exists";
String SSL_REQUIRED = "ssl_required"; String SSL_REQUIRED = "ssl_required";

View file

@ -14,6 +14,13 @@
</div> </div>
<span tooltip-placement="right" tooltip="Enable/disable the registration page. A link for registration will show on login page too." class="fa fa-info-circle"></span> <span tooltip-placement="right" tooltip="Enable/disable the registration page. A link for registration will show on login page too." class="fa fa-info-circle"></span>
</div> </div>
<div class="form-group" ng-show="registrationAllowed">
<label for="registrationEmailAsUsername" class="col-sm-2 control-label">Email as username</label>
<div class="col-sm-4">
<input ng-model="realm.registrationEmailAsUsername" name="registrationEmailAsUsername" id="registrationEmailAsUsername" onoffswitch />
</div>
<span tooltip-placement="right" tooltip="If enabled then username field is hidden from registration form and email is used as username for new user." class="fa fa-info-circle"></span>
</div>
<div class="form-group"> <div class="form-group">
<label for="resetPasswordAllowed" class="col-sm-2 control-label">Forget password</label> <label for="resetPasswordAllowed" class="col-sm-2 control-label">Forget password</label>
<div class="col-sm-4"> <div class="col-sm-4">

View file

@ -62,6 +62,7 @@ emailExists=Email already exists
federatedIdentityEmailExists=User with email already exists. Please login to account management to link the account. federatedIdentityEmailExists=User with email already exists. Please login to account management to link the account.
federatedIdentityUsernameExists=User with username already exists. Please login to account management to link the account. federatedIdentityUsernameExists=User with username already exists. Please login to account management to link the account.
federatedIdentityRegistrationEmailMissing=Email is not provided. Use another provider to create account please.
loginTitle=Log in to loginTitle=Log in to
loginOauthTitle=Temporary access. loginOauthTitle=Temporary access.

View file

@ -6,6 +6,7 @@
${rb.registerWith} <strong>${realm.name}</strong> ${rb.registerWith} <strong>${realm.name}</strong>
<#elseif section = "form"> <#elseif section = "form">
<form id="kc-register-form" class="${properties.kcFormClass!}" action="${url.registrationAction}" method="post"> <form id="kc-register-form" class="${properties.kcFormClass!}" action="${url.registrationAction}" method="post">
<#if !realm.registrationEmailAsUsername>
<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.username}</label>
@ -14,7 +15,7 @@
<input type="text" id="username" class="${properties.kcInputClass!}" name="username" value="${(register.formData.username!'')?html}" /> <input type="text" id="username" class="${properties.kcInputClass!}" name="username" value="${(register.formData.username!'')?html}" />
</div> </div>
</div> </div>
</#if>
<div class="${properties.kcFormGroupClass!}"> <div class="${properties.kcFormGroupClass!}">
<div class="${properties.kcLabelWrapperClass!}"> <div class="${properties.kcLabelWrapperClass!}">
<label for="firstName" class="${properties.kcLabelClass!}">${rb.firstName}</label> <label for="firstName" class="${properties.kcLabelClass!}">${rb.firstName}</label>

View file

@ -48,6 +48,10 @@ public class RealmBean {
return realm.isRegistrationAllowed(); return realm.isRegistrationAllowed();
} }
public boolean isRegistrationEmailAsUsername() {
return realm.isRegistrationEmailAsUsername();
}
public boolean isResetPasswordAllowed() { public boolean isResetPasswordAllowed() {
return realm.isResetPasswordAllowed(); return realm.isResetPasswordAllowed();
} }

View file

@ -1,8 +1,5 @@
package org.keycloak.models; package org.keycloak.models;
import org.keycloak.enums.SslRequired;
import org.keycloak.provider.ProviderEvent;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -11,6 +8,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.provider.ProviderEvent;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -19,12 +19,15 @@ 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();
} }
@ -47,6 +50,10 @@ public interface RealmModel extends RoleContainerModel {
void setRegistrationAllowed(boolean registrationAllowed); void setRegistrationAllowed(boolean registrationAllowed);
public boolean isRegistrationEmailAsUsername();
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername);
boolean isPasswordCredentialGrantAllowed(); boolean isPasswordCredentialGrantAllowed();
void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed); void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed);
@ -55,23 +62,36 @@ 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);
int getMaxFailureWaitSeconds();
void setMaxFailureWaitSeconds(int val);
int getWaitIncrementSeconds();
void setWaitIncrementSeconds(int val);
int getMinimumQuickLoginWaitSeconds();
void setMinimumQuickLoginWaitSeconds(int val);
long getQuickLoginCheckMilliSeconds();
void setQuickLoginCheckMilliSeconds(long val);
int getMaxDeltaTimeSeconds();
void setMaxDeltaTimeSeconds(int val);
int getFailureFactor();
void setFailureFactor(int failureFactor);
//--- end brute force settings
void setBruteForceProtected(boolean value);
int getMaxFailureWaitSeconds();
void setMaxFailureWaitSeconds(int val);
int getWaitIncrementSeconds();
void setWaitIncrementSeconds(int val);
int getMinimumQuickLoginWaitSeconds();
void setMinimumQuickLoginWaitSeconds(int val);
long getQuickLoginCheckMilliSeconds();
void setQuickLoginCheckMilliSeconds(long val);
int getMaxDeltaTimeSeconds();
void setMaxDeltaTimeSeconds(int val);
int getFailureFactor();
void setFailureFactor(int failureFactor);
// --- end brute force settings
boolean isVerifyEmail(); boolean isVerifyEmail();
@ -82,9 +102,11 @@ 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();
@ -122,8 +144,11 @@ 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();
@ -159,6 +184,7 @@ 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);
@ -168,12 +194,15 @@ 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();
Map<String, String> getBrowserSecurityHeaders(); Map<String, String> getBrowserSecurityHeaders();
void setBrowserSecurityHeaders(Map<String, String> headers); void setBrowserSecurityHeaders(Map<String, String> headers);
Map<String, String> getSmtpConfig(); Map<String, String> getSmtpConfig();
@ -181,16 +210,24 @@ public interface RealmModel extends RoleContainerModel {
void setSmtpConfig(Map<String, String> smtpConfig); void setSmtpConfig(Map<String, String> smtpConfig);
List<IdentityProviderModel> getIdentityProviders(); List<IdentityProviderModel> getIdentityProviders();
IdentityProviderModel getIdentityProviderById(String identityProviderId); IdentityProviderModel getIdentityProviderById(String identityProviderId);
void addIdentityProvider(IdentityProviderModel identityProvider); void addIdentityProvider(IdentityProviderModel identityProvider);
void removeIdentityProviderById(String providerId); void removeIdentityProviderById(String providerId);
void updateIdentityProvider(IdentityProviderModel identityProvider); void updateIdentityProvider(IdentityProviderModel identityProvider);
List<UserFederationProviderModel> getUserFederationProviders(); List<UserFederationProviderModel> getUserFederationProviders();
UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync); UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority,
String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync);
void updateUserFederationProvider(UserFederationProviderModel provider); void updateUserFederationProvider(UserFederationProviderModel provider);
void removeUserFederationProvider(UserFederationProviderModel provider); void removeUserFederationProvider(UserFederationProviderModel provider);
void setUserFederationProviders(List<UserFederationProviderModel> providers); void setUserFederationProviders(List<UserFederationProviderModel> providers);
String getLoginTheme(); String getLoginTheme();
@ -209,7 +246,6 @@ public interface RealmModel extends RoleContainerModel {
void setEmailTheme(String name); void setEmailTheme(String name);
/** /**
* Time in seconds since epoc * Time in seconds since epoc
* *

View file

@ -14,12 +14,13 @@ public class RealmEntity extends AbstractIdentifiableEntity {
private boolean enabled; private boolean enabled;
private String sslRequired; private String sslRequired;
private boolean registrationAllowed; private boolean registrationAllowed;
protected boolean registrationEmailAsUsername;
private boolean rememberMe; private boolean rememberMe;
private boolean verifyEmail; private boolean verifyEmail;
private boolean passwordCredentialGrantAllowed; private boolean passwordCredentialGrantAllowed;
private boolean resetPasswordAllowed; private boolean resetPasswordAllowed;
private String passwordPolicy; private String passwordPolicy;
//--- brute force settings // --- brute force settings
private boolean bruteForceProtected; private boolean bruteForceProtected;
private int maxFailureWaitSeconds; private int maxFailureWaitSeconds;
private int minimumQuickLoginWaitSeconds; private int minimumQuickLoginWaitSeconds;
@ -27,7 +28,7 @@ public class RealmEntity extends AbstractIdentifiableEntity {
private long quickLoginCheckMilliSeconds; private long quickLoginCheckMilliSeconds;
private int maxDeltaTimeSeconds; private int maxDeltaTimeSeconds;
private int failureFactor; private int failureFactor;
//--- end brute force settings // --- end brute force settings
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@ -104,6 +105,14 @@ public class RealmEntity extends AbstractIdentifiableEntity {
this.registrationAllowed = registrationAllowed; this.registrationAllowed = registrationAllowed;
} }
public boolean isRegistrationEmailAsUsername() {
return registrationEmailAsUsername;
}
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
this.registrationEmailAsUsername = registrationEmailAsUsername;
}
public boolean isRememberMe() { public boolean isRememberMe() {
return rememberMe; return rememberMe;
} }
@ -231,6 +240,7 @@ public class RealmEntity extends AbstractIdentifiableEntity {
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }
@ -399,5 +409,3 @@ public class RealmEntity extends AbstractIdentifiableEntity {
this.certificatePem = certificatePem; this.certificatePem = certificatePem;
} }
} }

View file

@ -1,5 +1,13 @@
package org.keycloak.models.utils; package org.keycloak.models.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimMask; import org.keycloak.models.ClaimMask;
import org.keycloak.models.ClientIdentityProviderMappingModel; import org.keycloak.models.ClientIdentityProviderMappingModel;
@ -31,14 +39,6 @@ import org.keycloak.representations.idm.UserFederationProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.UserSessionRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -57,7 +57,7 @@ public class ModelToRepresentation {
rep.setFederationLink(user.getFederationLink()); rep.setFederationLink(user.getFederationLink());
List<String> reqActions = new ArrayList<String>(); List<String> reqActions = new ArrayList<String>();
for (UserModel.RequiredAction ra : user.getRequiredActions()){ for (UserModel.RequiredAction ra : user.getRequiredActions()) {
reqActions.add(ra.name()); reqActions.add(ra.name());
} }
@ -99,6 +99,7 @@ public class ModelToRepresentation {
rep.setCertificate(realm.getCertificatePem()); rep.setCertificate(realm.getCertificatePem());
rep.setPasswordCredentialGrantAllowed(realm.isPasswordCredentialGrantAllowed()); rep.setPasswordCredentialGrantAllowed(realm.isPasswordCredentialGrantAllowed());
rep.setRegistrationAllowed(realm.isRegistrationAllowed()); rep.setRegistrationAllowed(realm.isRegistrationAllowed());
rep.setRegistrationEmailAsUsername(realm.isRegistrationEmailAsUsername());
rep.setRememberMe(realm.isRememberMe()); rep.setRememberMe(realm.isRememberMe());
rep.setBruteForceProtected(realm.isBruteForceProtected()); rep.setBruteForceProtected(realm.isBruteForceProtected());
rep.setMaxFailureWaitSeconds(realm.getMaxFailureWaitSeconds()); rep.setMaxFailureWaitSeconds(realm.getMaxFailureWaitSeconds());
@ -204,8 +205,8 @@ public class ModelToRepresentation {
public static UserSessionRepresentation toRepresentation(UserSessionModel session) { public static UserSessionRepresentation toRepresentation(UserSessionModel session) {
UserSessionRepresentation rep = new UserSessionRepresentation(); UserSessionRepresentation rep = new UserSessionRepresentation();
rep.setId(session.getId()); rep.setId(session.getId());
rep.setStart(((long)session.getStarted()) * 1000L); rep.setStart(((long) session.getStarted()) * 1000L);
rep.setLastAccess(((long)session.getLastSessionRefresh())* 1000L); rep.setLastAccess(((long) session.getLastSessionRefresh()) * 1000L);
rep.setUser(session.getUser().getUsername()); rep.setUser(session.getUser().getUsername());
rep.setIpAddress(session.getIpAddress()); rep.setIpAddress(session.getIpAddress());
for (ClientSessionModel clientSession : session.getClientSessions()) { for (ClientSessionModel clientSession : session.getClientSessions()) {
@ -269,7 +270,8 @@ public class ModelToRepresentation {
return rep; return rep;
} }
private static List<ClientIdentityProviderMappingRepresentation> toRepresentation(List<ClientIdentityProviderMappingModel> identityProviders) { private static List<ClientIdentityProviderMappingRepresentation> toRepresentation(
List<ClientIdentityProviderMappingModel> identityProviders) {
ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>(); ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>();
for (ClientIdentityProviderMappingModel model : identityProviders) { for (ClientIdentityProviderMappingModel model : identityProviders) {

View file

@ -1,6 +1,16 @@
package org.keycloak.models.utils; package org.keycloak.models.utils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.iharder.Base64; import net.iharder.Base64;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
@ -34,60 +44,81 @@ import org.keycloak.representations.idm.ScopeMappingRepresentation;
import org.keycloak.representations.idm.UserFederationProviderRepresentation; import org.keycloak.representations.idm.UserFederationProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserRepresentation;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RepresentationToModel { public class RepresentationToModel {
private static Logger logger = Logger.getLogger(RepresentationToModel.class); private static Logger logger = Logger.getLogger(RepresentationToModel.class);
public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) { public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) {
newRealm.setName(rep.getRealm()); newRealm.setName(rep.getRealm());
if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); if (rep.isEnabled() != null)
if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected()); newRealm.setEnabled(rep.isEnabled());
if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); if (rep.isBruteForceProtected() != null)
if (rep.getMinimumQuickLoginWaitSeconds() != null) newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); newRealm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); if (rep.getMaxFailureWaitSeconds() != null)
if (rep.getQuickLoginCheckMilliSeconds() != null) newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); if (rep.getMinimumQuickLoginWaitSeconds() != null)
if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor()); newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.isEventsEnabled() != null) newRealm.setEventsEnabled(rep.isEventsEnabled()); if (rep.getWaitIncrementSeconds() != null)
if (rep.getEventsExpiration() != null) newRealm.setEventsExpiration(rep.getEventsExpiration()); newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
if (rep.getEventsListeners() != null) newRealm.setEventsListeners(new HashSet<String>(rep.getEventsListeners())); if (rep.getQuickLoginCheckMilliSeconds() != null)
newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null)
newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
if (rep.getFailureFactor() != null)
newRealm.setFailureFactor(rep.getFailureFactor());
if (rep.isEventsEnabled() != null)
newRealm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null)
newRealm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null)
newRealm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore()); if (rep.getNotBefore() != null)
newRealm.setNotBefore(rep.getNotBefore());
if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); if (rep.getAccessTokenLifespan() != null)
else newRealm.setAccessTokenLifespan(300); newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
else
newRealm.setAccessTokenLifespan(300);
if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); if (rep.getSsoSessionIdleTimeout() != null)
else newRealm.setSsoSessionIdleTimeout(1800); newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); else
else newRealm.setSsoSessionMaxLifespan(36000); newRealm.setSsoSessionIdleTimeout(1800);
if (rep.getSsoSessionMaxLifespan() != null)
newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
else
newRealm.setSsoSessionMaxLifespan(36000);
if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); if (rep.getAccessCodeLifespan() != null)
else newRealm.setAccessCodeLifespan(60); newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
else
newRealm.setAccessCodeLifespan(60);
if (rep.getAccessCodeLifespanUserAction() != null) if (rep.getAccessCodeLifespanUserAction() != null)
newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
else newRealm.setAccessCodeLifespanUserAction(300); else
newRealm.setAccessCodeLifespanUserAction(300);
if (rep.getAccessCodeLifespanLogin() != null) if (rep.getAccessCodeLifespanLogin() != null)
newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin()); newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
else newRealm.setAccessCodeLifespanLogin(1800); else
newRealm.setAccessCodeLifespanLogin(1800);
if (rep.getSslRequired() != null) newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase())); if (rep.getSslRequired() != null)
if (rep.isPasswordCredentialGrantAllowed() != null) newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isPasswordCredentialGrantAllowed() != null)
if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe()); newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed());
if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); if (rep.isRegistrationAllowed() != null)
if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null)
newRealm.setRememberMe(rep.isRememberMe());
if (rep.isVerifyEmail() != null)
newRealm.setVerifyEmail(rep.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null)
newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { if (rep.getPrivateKey() == null || rep.getPublicKey() == null) {
KeycloakModelUtils.generateRealmKeys(newRealm); KeycloakModelUtils.generateRealmKeys(newRealm);
} else { } else {
@ -105,10 +136,14 @@ public class RepresentationToModel {
newRealm.setCodeSecret(rep.getCodeSecret()); newRealm.setCodeSecret(rep.getCodeSecret());
} }
if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme()); if (rep.getLoginTheme() != null)
if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme()); newRealm.setLoginTheme(rep.getLoginTheme());
if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme()); if (rep.getAccountTheme() != null)
if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme()); newRealm.setAccountTheme(rep.getAccountTheme());
if (rep.getAdminTheme() != null)
newRealm.setAdminTheme(rep.getAdminTheme());
if (rep.getEmailTheme() != null)
newRealm.setEmailTheme(rep.getEmailTheme());
if (rep.getRequiredCredentials() != null) { if (rep.getRequiredCredentials() != null) {
for (String requiredCred : rep.getRequiredCredentials()) { for (String requiredCred : rep.getRequiredCredentials()) {
@ -118,7 +153,8 @@ public class RepresentationToModel {
addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD);
} }
if (rep.getPasswordPolicy() != null) newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); if (rep.getPasswordPolicy() != null)
newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
importIdentityProviders(rep, newRealm); importIdentityProviders(rep, newRealm);
@ -140,7 +176,8 @@ public class RepresentationToModel {
} }
for (RoleRepresentation roleRep : entry.getValue()) { for (RoleRepresentation roleRep : entry.getValue()) {
// Application role may already exists (for example if it is defaultRole) // Application role may already exists (for example if it is defaultRole)
RoleModel role = roleRep.getId()!=null ? app.addRole(roleRep.getId(), roleRep.getName()) : app.addRole(roleRep.getName()); RoleModel role = roleRep.getId() != null ? app.addRole(roleRep.getId(), roleRep.getName()) : app
.addRole(roleRep.getName());
role.setDescription(roleRep.getDescription()); role.setDescription(roleRep.getDescription());
} }
} }
@ -186,7 +223,6 @@ public class RepresentationToModel {
createOAuthClients(rep, newRealm); createOAuthClients(rep, newRealm);
} }
// Now that all possible roles and applications are created, create scope mappings // Now that all possible roles and applications are created, create scope mappings
Map<String, ApplicationModel> appMap = newRealm.getApplicationNameMap(); Map<String, ApplicationModel> appMap = newRealm.getApplicationNameMap();
@ -247,39 +283,70 @@ public class RepresentationToModel {
if (rep.getRealm() != null) { if (rep.getRealm() != null) {
realm.setName(rep.getRealm()); realm.setName(rep.getRealm());
} }
if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled()); if (rep.isEnabled() != null)
if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected()); realm.setEnabled(rep.isEnabled());
if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); if (rep.isBruteForceProtected() != null)
if (rep.getMinimumQuickLoginWaitSeconds() != null) realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); realm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); if (rep.getMaxFailureWaitSeconds() != null)
if (rep.getQuickLoginCheckMilliSeconds() != null) realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); if (rep.getMinimumQuickLoginWaitSeconds() != null)
if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor()); realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.isPasswordCredentialGrantAllowed() != null) realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); if (rep.getWaitIncrementSeconds() != null)
if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed()); realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe()); if (rep.getQuickLoginCheckMilliSeconds() != null)
if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail()); realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); if (rep.getMaxDeltaTimeSeconds() != null)
if (rep.getSslRequired() != null) realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase())); realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); if (rep.getFailureFactor() != null)
if (rep.getAccessCodeLifespanUserAction() != null) realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); realm.setFailureFactor(rep.getFailureFactor());
if (rep.getAccessCodeLifespanLogin() != null) realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin()); if (rep.isPasswordCredentialGrantAllowed() != null)
if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore()); realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed());
if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); if (rep.isRegistrationAllowed() != null)
if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); realm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); if (rep.isRegistrationEmailAsUsername() != null)
realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null)
realm.setRememberMe(rep.isRememberMe());
if (rep.isVerifyEmail() != null)
realm.setVerifyEmail(rep.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null)
realm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.getSslRequired() != null)
realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
if (rep.getAccessCodeLifespan() != null)
realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null)
realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
if (rep.getAccessCodeLifespanLogin() != null)
realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
if (rep.getNotBefore() != null)
realm.setNotBefore(rep.getNotBefore());
if (rep.getAccessTokenLifespan() != null)
realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
if (rep.getSsoSessionIdleTimeout() != null)
realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
if (rep.getSsoSessionMaxLifespan() != null)
realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
if (rep.getRequiredCredentials() != null) { if (rep.getRequiredCredentials() != null) {
realm.updateRequiredCredentials(rep.getRequiredCredentials()); realm.updateRequiredCredentials(rep.getRequiredCredentials());
} }
if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme()); if (rep.getLoginTheme() != null)
if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme()); realm.setLoginTheme(rep.getLoginTheme());
if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme()); if (rep.getAccountTheme() != null)
if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme()); realm.setAccountTheme(rep.getAccountTheme());
if (rep.isEventsEnabled() != null) realm.setEventsEnabled(rep.isEventsEnabled()); if (rep.getAdminTheme() != null)
if (rep.getEventsExpiration() != null) realm.setEventsExpiration(rep.getEventsExpiration()); realm.setAdminTheme(rep.getAdminTheme());
if (rep.getEventsListeners() != null) realm.setEventsListeners(new HashSet<String>(rep.getEventsListeners())); if (rep.getEmailTheme() != null)
realm.setEmailTheme(rep.getEmailTheme());
if (rep.isEventsEnabled() != null)
realm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null)
realm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null)
realm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
if (rep.getPasswordPolicy() != null) realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); if (rep.getPasswordPolicy() != null)
realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
if (rep.getDefaultRoles() != null) { if (rep.getDefaultRoles() != null) {
realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()])); realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()]));
@ -309,14 +376,15 @@ public class RepresentationToModel {
newRealm.addRequiredCredential(requiredCred); newRealm.addRequiredCredential(requiredCred);
} }
private static List<UserFederationProviderModel> convertFederationProviders(
private static List<UserFederationProviderModel> convertFederationProviders(List<UserFederationProviderRepresentation> providers) { List<UserFederationProviderRepresentation> providers) {
List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>();
for (UserFederationProviderRepresentation representation : providers) { for (UserFederationProviderRepresentation representation : providers) {
UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(), representation.getProviderName(), UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(),
representation.getConfig(), representation.getPriority(), representation.getDisplayName(), representation.getProviderName(), representation.getConfig(), representation.getPriority(),
representation.getFullSyncPeriod(), representation.getChangedSyncPeriod(), representation.getLastSync()); representation.getDisplayName(), representation.getFullSyncPeriod(), representation.getChangedSyncPeriod(),
representation.getLastSync());
result.add(model); result.add(model);
} }
return result; return result;
@ -325,16 +393,20 @@ public class RepresentationToModel {
// Roles // Roles
public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) { public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) {
RoleModel role = roleRep.getId()!=null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName()); RoleModel role = roleRep.getId() != null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm
if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription()); .addRole(roleRep.getName());
if (roleRep.getDescription() != null)
role.setDescription(roleRep.getDescription());
} }
private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) { private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) {
if (roleRep.getComposites() == null) return; if (roleRep.getComposites() == null)
return;
if (roleRep.getComposites().getRealm() != null) { if (roleRep.getComposites().getRealm() != null) {
for (String roleStr : roleRep.getComposites().getRealm()) { for (String roleStr : roleRep.getComposites().getRealm()) {
RoleModel realmRole = realm.getRole(roleStr); RoleModel realmRole = realm.getRole(roleStr);
if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr); if (realmRole == null)
throw new RuntimeException("Unable to find composite realm role: " + roleStr);
role.addCompositeRole(realmRole); role.addCompositeRole(realmRole);
} }
} }
@ -346,7 +418,8 @@ public class RepresentationToModel {
} }
for (String roleStr : entry.getValue()) { for (String roleStr : entry.getValue()) {
RoleModel appRole = app.getRole(roleStr); RoleModel appRole = app.getRole(roleStr);
if (appRole == null) throw new RuntimeException("Unable to find composite app role: " + roleStr); if (appRole == null)
throw new RuntimeException("Unable to find composite app role: " + roleStr);
role.addCompositeRole(appRole); role.addCompositeRole(appRole);
} }
@ -374,18 +447,25 @@ public class RepresentationToModel {
* @param resourceRep * @param resourceRep
* @return * @return
*/ */
public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep, boolean addDefaultRoles) { public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep,
boolean addDefaultRoles) {
logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName()); logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName());
ApplicationModel applicationModel = resourceRep.getId()!=null ? realm.addApplication(resourceRep.getId(), resourceRep.getName()) : realm.addApplication(resourceRep.getName()); ApplicationModel applicationModel = resourceRep.getId() != null ? realm.addApplication(resourceRep.getId(),
if (resourceRep.isEnabled() != null) applicationModel.setEnabled(resourceRep.isEnabled()); resourceRep.getName()) : realm.addApplication(resourceRep.getName());
if (resourceRep.isEnabled() != null)
applicationModel.setEnabled(resourceRep.isEnabled());
applicationModel.setManagementUrl(resourceRep.getAdminUrl()); applicationModel.setManagementUrl(resourceRep.getAdminUrl());
if (resourceRep.isSurrogateAuthRequired() != null) if (resourceRep.isSurrogateAuthRequired() != null)
applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired()); applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired());
applicationModel.setBaseUrl(resourceRep.getBaseUrl()); applicationModel.setBaseUrl(resourceRep.getBaseUrl());
if (resourceRep.isBearerOnly() != null) applicationModel.setBearerOnly(resourceRep.isBearerOnly()); if (resourceRep.isBearerOnly() != null)
if (resourceRep.isPublicClient() != null) applicationModel.setPublicClient(resourceRep.isPublicClient()); applicationModel.setBearerOnly(resourceRep.isBearerOnly());
if (resourceRep.isFrontchannelLogout() != null) applicationModel.setFrontchannelLogout(resourceRep.isFrontchannelLogout()); if (resourceRep.isPublicClient() != null)
if (resourceRep.getProtocol() != null) applicationModel.setProtocol(resourceRep.getProtocol()); applicationModel.setPublicClient(resourceRep.isPublicClient());
if (resourceRep.isFrontchannelLogout() != null)
applicationModel.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
if (resourceRep.getProtocol() != null)
applicationModel.setProtocol(resourceRep.getProtocol());
if (resourceRep.isFullScopeAllowed() != null) { if (resourceRep.isFullScopeAllowed() != null) {
applicationModel.setFullScopeAllowed(resourceRep.isFullScopeAllowed()); applicationModel.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
} else { } else {
@ -413,7 +493,6 @@ public class RepresentationToModel {
} }
} }
if (resourceRep.getRedirectUris() != null) { if (resourceRep.getRedirectUris() != null) {
for (String redirectUri : resourceRep.getRedirectUris()) { for (String redirectUri : resourceRep.getRedirectUris()) {
applicationModel.addRedirectUri(redirectUri); applicationModel.addRedirectUri(redirectUri);
@ -436,7 +515,7 @@ public class RepresentationToModel {
if (uri.getPort() != -1) { if (uri.getPort() != -1) {
origin += ":" + uri.getPort(); origin += ":" + uri.getPort();
} }
logger.debugv("adding default application origin: {0}" , origin); logger.debugv("adding default application origin: {0}", origin);
origins.add(origin); origins.add(origin);
} }
} }
@ -459,7 +538,8 @@ public class RepresentationToModel {
if (resourceRep.getProtocolMappers() != null) { if (resourceRep.getProtocolMappers() != null) {
// first, remove all default/built in mappers // first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = applicationModel.getProtocolMappers(); Set<ProtocolMapperModel> mappers = applicationModel.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) applicationModel.removeProtocolMapper(mapper); for (ProtocolMapperModel mapper : mappers)
applicationModel.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) { for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
applicationModel.addProtocolMapper(toModel(mapper)); applicationModel.addProtocolMapper(toModel(mapper));
@ -472,26 +552,36 @@ public class RepresentationToModel {
} }
public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) { public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) {
if (rep.getName() != null) resource.setName(rep.getName()); if (rep.getName() != null)
if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled()); resource.setName(rep.getName());
if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly()); if (rep.isEnabled() != null)
if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient()); resource.setEnabled(rep.isEnabled());
if (rep.isFullScopeAllowed() != null) resource.setFullScopeAllowed(rep.isFullScopeAllowed()); if (rep.isBearerOnly() != null)
if (rep.isFrontchannelLogout() != null) resource.setFrontchannelLogout(rep.isFrontchannelLogout()); resource.setBearerOnly(rep.isBearerOnly());
if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl()); if (rep.isPublicClient() != null)
if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl()); resource.setPublicClient(rep.isPublicClient());
if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired()); if (rep.isFullScopeAllowed() != null)
if (rep.getNodeReRegistrationTimeout() != null) resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout()); resource.setFullScopeAllowed(rep.isFullScopeAllowed());
if (rep.isFrontchannelLogout() != null)
resource.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.getAdminUrl() != null)
resource.setManagementUrl(rep.getAdminUrl());
if (rep.getBaseUrl() != null)
resource.setBaseUrl(rep.getBaseUrl());
if (rep.isSurrogateAuthRequired() != null)
resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired());
if (rep.getNodeReRegistrationTimeout() != null)
resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout());
resource.updateApplication(); resource.updateApplication();
if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol()); if (rep.getProtocol() != null)
resource.setProtocol(rep.getProtocol());
if (rep.getAttributes() != null) { if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) { for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
resource.setAttribute(entry.getKey(), entry.getValue()); resource.setAttribute(entry.getKey(), entry.getValue());
} }
} }
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
resource.setNotBefore(rep.getNotBefore()); resource.setNotBefore(rep.getNotBefore());
} }
@ -582,7 +672,7 @@ public class RepresentationToModel {
} }
public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) { public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) {
OAuthClientModel model = id!=null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name); OAuthClientModel model = id != null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name);
KeycloakModelUtils.generateSecret(model); KeycloakModelUtils.generateSecret(model);
return model; return model;
} }
@ -597,19 +687,26 @@ public class RepresentationToModel {
} }
public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) { public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) {
if (rep.getName() != null) model.setClientId(rep.getName()); if (rep.getName() != null)
if (rep.isEnabled() != null) model.setEnabled(rep.isEnabled()); model.setClientId(rep.getName());
if (rep.isPublicClient() != null) model.setPublicClient(rep.isPublicClient()); if (rep.isEnabled() != null)
if (rep.isFrontchannelLogout() != null) model.setFrontchannelLogout(rep.isFrontchannelLogout()); model.setEnabled(rep.isEnabled());
if (rep.isFullScopeAllowed() != null) model.setFullScopeAllowed(rep.isFullScopeAllowed()); if (rep.isPublicClient() != null)
if (rep.isDirectGrantsOnly() != null) model.setDirectGrantsOnly(rep.isDirectGrantsOnly()); model.setPublicClient(rep.isPublicClient());
if (rep.isFrontchannelLogout() != null)
model.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.isFullScopeAllowed() != null)
model.setFullScopeAllowed(rep.isFullScopeAllowed());
if (rep.isDirectGrantsOnly() != null)
model.setDirectGrantsOnly(rep.isDirectGrantsOnly());
if (rep.getClaims() != null) { if (rep.getClaims() != null) {
setClaims(model, rep.getClaims()); setClaims(model, rep.getClaims());
} }
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
model.setNotBefore(rep.getNotBefore()); model.setNotBefore(rep.getNotBefore());
} }
if (rep.getSecret() != null) model.setSecret(rep.getSecret()); if (rep.getSecret() != null)
model.setSecret(rep.getSecret());
List<String> redirectUris = rep.getRedirectUris(); List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
model.setRedirectUris(new HashSet<String>(redirectUris)); model.setRedirectUris(new HashSet<String>(redirectUris));
@ -623,7 +720,8 @@ public class RepresentationToModel {
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
model.setNotBefore(rep.getNotBefore()); model.setNotBefore(rep.getNotBefore());
} }
if (rep.getProtocol() != null) model.setProtocol(rep.getProtocol()); if (rep.getProtocol() != null)
model.setProtocol(rep.getProtocol());
if (rep.getAttributes() != null) { if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) { for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
model.setAttribute(entry.getKey(), entry.getValue()); model.setAttribute(entry.getKey(), entry.getValue());
@ -635,7 +733,8 @@ public class RepresentationToModel {
if (rep.getProtocolMappers() != null) { if (rep.getProtocolMappers() != null) {
// first, remove all default/built in mappers // first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = model.getProtocolMappers(); Set<ProtocolMapperModel> mappers = model.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) model.removeProtocolMapper(mapper); for (ProtocolMapperModel mapper : mappers)
model.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : rep.getProtocolMappers()) { for (ProtocolMapperRepresentation mapper : rep.getProtocolMappers()) {
model.addProtocolMapper(toModel(mapper)); model.addProtocolMapper(toModel(mapper));
@ -646,7 +745,8 @@ public class RepresentationToModel {
// Scope mappings // Scope mappings
public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel, List<ScopeMappingRepresentation> mappings) { public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel,
List<ScopeMappingRepresentation> mappings) {
for (ScopeMappingRepresentation mapping : mappings) { for (ScopeMappingRepresentation mapping : mappings) {
ClientModel client = realm.findClient(mapping.getClient()); ClientModel client = realm.findClient(mapping.getClient());
if (client == null) { if (client == null) {
@ -664,7 +764,8 @@ public class RepresentationToModel {
// Users // Users
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep, Map<String, ApplicationModel> appMap) { public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep,
Map<String, ApplicationModel> appMap) {
// Import users just to user storage. Don't federate // Import users just to user storage. Don't federate
UserModel user = session.userStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false); UserModel user = session.userStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false);
user.setEnabled(userRep.isEnabled()); user.setEnabled(userRep.isEnabled());
@ -690,7 +791,8 @@ public class RepresentationToModel {
} }
if (userRep.getFederatedIdentities() != null) { if (userRep.getFederatedIdentities() != null) {
for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) { for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName()); FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(),
identity.getUserId(), identity.getUserName());
session.users().addFederatedIdentity(newRealm, user, mappingModel); session.users().addFederatedIdentity(newRealm, user, mappingModel);
} }
} }
@ -726,7 +828,8 @@ public class RepresentationToModel {
hashedCred.setDevice(cred.getDevice()); hashedCred.setDevice(cred.getDevice());
hashedCred.setHashIterations(cred.getHashIterations()); hashedCred.setHashIterations(cred.getHashIterations());
try { try {
if (cred.getSalt() != null) hashedCred.setSalt(Base64.decode(cred.getSalt())); if (cred.getSalt() != null)
hashedCred.setSalt(Base64.decode(cred.getSalt()));
} catch (IOException ioe) { } catch (IOException ioe) {
throw new RuntimeException(ioe); throw new RuntimeException(ioe);
} }
@ -744,7 +847,8 @@ public class RepresentationToModel {
// Role mappings // Role mappings
public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user, List<String> roleNames) { public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user,
List<String> roleNames) {
if (user == null) { if (user == null) {
throw new RuntimeException("User not found"); throw new RuntimeException("User not found");
} }
@ -766,6 +870,7 @@ public class RepresentationToModel {
} }
} }
} }
public static IdentityProviderModel toModel(IdentityProviderRepresentation representation) { public static IdentityProviderModel toModel(IdentityProviderRepresentation representation) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
@ -794,7 +899,8 @@ public class RepresentationToModel {
return model; return model;
} }
private static List<ClientIdentityProviderMappingModel> toModel(List<ClientIdentityProviderMappingRepresentation> repIdentityProviders, RealmModel realm) { private static List<ClientIdentityProviderMappingModel> toModel(
List<ClientIdentityProviderMappingRepresentation> repIdentityProviders, RealmModel realm) {
List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>(); List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>();
if (repIdentityProviders == null || repIdentityProviders.isEmpty()) { if (repIdentityProviders == null || repIdentityProviders.isEmpty()) {
@ -821,7 +927,8 @@ public class RepresentationToModel {
return allowedIdentityProviders; return allowedIdentityProviders;
} }
private static void updateClientIdentityProvides(List<ClientIdentityProviderMappingRepresentation> identityProviders, ClientModel resource) { private static void updateClientIdentityProvides(List<ClientIdentityProviderMappingRepresentation> identityProviders,
ClientModel resource) {
if (identityProviders != null) { if (identityProviders != null) {
List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>(); List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>();

View file

@ -16,21 +16,6 @@
*/ */
package org.keycloak.models.file.adapter; package org.keycloak.models.file.adapter;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.entities.RequiredCredentialEntity;
import org.keycloak.models.entities.UserFederationProviderEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -46,14 +31,29 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.entities.ApplicationEntity; import org.keycloak.models.entities.ApplicationEntity;
import org.keycloak.models.entities.ClientEntity; import org.keycloak.models.entities.ClientEntity;
import org.keycloak.models.entities.OAuthClientEntity; import org.keycloak.models.entities.OAuthClientEntity;
import org.keycloak.models.entities.RealmEntity; import org.keycloak.models.entities.RealmEntity;
import org.keycloak.models.entities.RequiredCredentialEntity;
import org.keycloak.models.entities.RoleEntity; import org.keycloak.models.entities.RoleEntity;
import org.keycloak.models.entities.UserFederationProviderEntity;
import org.keycloak.models.file.InMemoryModel; import org.keycloak.models.file.InMemoryModel;
import org.keycloak.models.utils.KeycloakModelUtils;
/** /**
* RealmModel for JSON persistence. * RealmModel for JSON persistence.
@ -106,9 +106,11 @@ public class RealmAdapter implements RealmModel {
return; return;
} }
if (getName().equals(name)) return; // allow setting name to same value if (getName().equals(name))
return; // allow setting name to same value
if (inMemoryModel.getRealmByName(name) != null) throw new ModelDuplicateException("Realm " + name + " already exists."); if (inMemoryModel.getRealmByName(name) != null)
throw new ModelDuplicateException("Realm " + name + " already exists.");
realm.setName(name); realm.setName(name);
} }
@ -152,6 +154,16 @@ public class RealmAdapter implements RealmModel {
realm.setRegistrationAllowed(registrationAllowed); realm.setRegistrationAllowed(registrationAllowed);
} }
@Override
public boolean isRegistrationEmailAsUsername() {
return realm.isRegistrationEmailAsUsername();
}
@Override
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
realm.setRegistrationEmailAsUsername(registrationEmailAsUsername);
}
@Override @Override
public boolean isRememberMe() { public boolean isRememberMe() {
return realm.isRememberMe(); return realm.isRememberMe();
@ -212,7 +224,6 @@ public class RealmAdapter implements RealmModel {
realm.setMinimumQuickLoginWaitSeconds(val); realm.setMinimumQuickLoginWaitSeconds(val);
} }
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
return realm.getMaxDeltaTimeSeconds(); return realm.getMaxDeltaTimeSeconds();
@ -233,7 +244,6 @@ public class RealmAdapter implements RealmModel {
realm.setFailureFactor(failureFactor); realm.setFailureFactor(failureFactor);
} }
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
return realm.isVerifyEmail(); return realm.isVerifyEmail();
@ -278,7 +288,6 @@ public class RealmAdapter implements RealmModel {
realm.setNotBefore(notBefore); realm.setNotBefore(notBefore);
} }
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
return realm.getSsoSessionIdleTimeout(); return realm.getSsoSessionIdleTimeout();
@ -342,7 +351,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) return certificate; if (certificate != null)
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -365,7 +375,6 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
return realm.getPrivateKeyPem(); return realm.getPrivateKeyPem();
@ -379,7 +388,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) return publicKey; if (publicKey != null)
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -393,7 +403,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) return privateKey; if (privateKey != null)
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -466,7 +477,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleAdapter getRole(String name) { public RoleAdapter getRole(String name) {
for (RoleAdapter role : allRoles.values()) { for (RoleAdapter role : allRoles.values()) {
if (role.getName().equals(name)) return role; if (role.getName().equals(name))
return role;
} }
return null; return null;
} }
@ -478,9 +490,12 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel addRole(String id, String name) { public RoleModel addRole(String id, String name) {
if (id == null) throw new NullPointerException("id == null"); if (id == null)
if (name == null) throw new NullPointerException("name == null"); throw new NullPointerException("id == null");
if (hasRoleWithName(name)) throw new ModelDuplicateException("Realm already contains role with name " + name + "."); if (name == null)
throw new NullPointerException("name == null");
if (hasRoleWithName(name))
throw new ModelDuplicateException("Realm already contains role with name " + name + ".");
RoleEntity roleEntity = new RoleEntity(); RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id); roleEntity.setId(id);
@ -499,10 +514,12 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
if (id == null) throw new NullPointerException("id == null"); if (id == null)
throw new NullPointerException("id == null");
// try realm roles first // try realm roles first
if (allRoles.remove(id) != null) return true; if (allRoles.remove(id) != null)
return true;
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
for (RoleModel appRole : app.getRoles()) { for (RoleModel appRole : app.getRoles()) {
@ -518,17 +535,19 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
return new HashSet(allRoles.values()); return new HashSet<RoleModel>(allRoles.values());
} }
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
RoleModel found = allRoles.get(id); RoleModel found = allRoles.get(id);
if (found != null) return found; if (found != null)
return found;
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
for (RoleModel appRole : app.getRoles()) { for (RoleModel appRole : app.getRoles()) {
if (appRole.getId().equals(id)) return appRole; if (appRole.getId().equals(id))
return appRole;
} }
} }
@ -548,7 +567,8 @@ public class RealmAdapter implements RealmModel {
} }
List<String> roleNames = getDefaultRoles(); List<String> roleNames = getDefaultRoles();
if (roleNames.contains(name)) throw new IllegalArgumentException("Realm " + realm.getName() + " already contains default role named " + name); if (roleNames.contains(name))
throw new IllegalArgumentException("Realm " + realm.getName() + " already contains default role named " + name);
roleNames.add(name); roleNames.add(name);
realm.setDefaultRoles(roleNames); realm.setDefaultRoles(roleNames);
@ -556,7 +576,8 @@ public class RealmAdapter implements RealmModel {
boolean hasRoleWithName(String name) { boolean hasRoleWithName(String name) {
for (RoleModel role : allRoles.values()) { for (RoleModel role : allRoles.values()) {
if (role.getName().equals(name)) return true; if (role.getName().equals(name))
return true;
} }
return false; return false;
@ -580,19 +601,19 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) return model; if (model != null)
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel clientModel = getApplicationById(id); ClientModel clientModel = getApplicationById(id);
if (clientModel != null) return clientModel; if (clientModel != null)
return clientModel;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
return allApps.get(id); return allApps.get(id);
@ -601,7 +622,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
if (app.getName().equals(name)) return app; if (app.getName().equals(name))
return app;
} }
return null; return null;
@ -628,8 +650,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel addApplication(String id, String name) { public ApplicationModel addApplication(String id, String name) {
if (name == null) throw new NullPointerException("name == null"); if (name == null)
if (id == null) throw new NullPointerException("id == null"); throw new NullPointerException("name == null");
if (id == null)
throw new NullPointerException("id == null");
if (getApplicationNameMap().containsKey(name)) { if (getApplicationNameMap().containsKey(name)) {
throw new ModelDuplicateException("Application named '" + name + "' already exists."); throw new ModelDuplicateException("Application named '" + name + "' already exists.");
@ -668,11 +692,12 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeApplication(String id) { public boolean removeApplication(String id) {
ApplicationModel appToBeRemoved = this.getApplicationById(id); ApplicationModel appToBeRemoved = this.getApplicationById(id);
if (appToBeRemoved == null) return false; if (appToBeRemoved == null)
return false;
// remove any composite role assignments for this app // remove any composite role assignments for this app
for (RoleModel role : this.getRoles()) { for (RoleModel role : this.getRoles()) {
RoleAdapter roleAdapter = (RoleAdapter)role; RoleAdapter roleAdapter = (RoleAdapter) role;
roleAdapter.removeApplicationComposites(id); roleAdapter.removeApplicationComposites(id);
} }
@ -690,9 +715,12 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel addOAuthClient(String id, String name) { public OAuthClientModel addOAuthClient(String id, String name) {
if (id == null) throw new NullPointerException("id == null"); if (id == null)
if (name == null) throw new NullPointerException("name == null"); throw new NullPointerException("id == null");
if (hasOAuthClientWithName(name)) throw new ModelDuplicateException("OAuth Client with name " + name + " already exists."); if (name == null)
throw new NullPointerException("name == null");
if (hasOAuthClientWithName(name))
throw new ModelDuplicateException("OAuth Client with name " + name + " already exists.");
OAuthClientEntity oauthClient = new OAuthClientEntity(); OAuthClientEntity oauthClient = new OAuthClientEntity();
oauthClient.setId(id); oauthClient.setId(id);
oauthClient.setRealmId(getId()); oauthClient.setRealmId(getId());
@ -706,7 +734,8 @@ public class RealmAdapter implements RealmModel {
boolean hasOAuthClientWithName(String name) { boolean hasOAuthClientWithName(String name) {
for (OAuthClientAdapter oaClient : allOAuthClients.values()) { for (OAuthClientAdapter oaClient : allOAuthClients.values()) {
if (oaClient.getName().equals(name)) return true; if (oaClient.getName().equals(name))
return true;
} }
return false; return false;
@ -714,7 +743,8 @@ public class RealmAdapter implements RealmModel {
boolean hasOAuthClientWithClientId(String id) { boolean hasOAuthClientWithClientId(String id) {
for (OAuthClientAdapter oaClient : allOAuthClients.values()) { for (OAuthClientAdapter oaClient : allOAuthClients.values()) {
if (oaClient.getClientId().equals(id)) return true; if (oaClient.getClientId().equals(id))
return true;
} }
return false; return false;
@ -722,8 +752,10 @@ public class RealmAdapter implements RealmModel {
boolean hasUserWithEmail(String email) { boolean hasUserWithEmail(String email) {
for (UserModel user : inMemoryModel.getUsers(getId())) { for (UserModel user : inMemoryModel.getUsers(getId())) {
if (user.getEmail() == null) continue; if (user.getEmail() == null)
if (user.getEmail().equals(email)) return true; continue;
if (user.getEmail().equals(email))
return true;
} }
return false; return false;
@ -737,7 +769,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) { for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) {
if (oAuthClient.getName().equals(name)) return oAuthClient; if (oAuthClient.getName().equals(name))
return oAuthClient;
} }
return null; return null;
@ -746,7 +779,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClientById(String id) { public OAuthClientModel getOAuthClientById(String id) {
for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) { for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) {
if (oAuthClient.getId().equals(id)) return oAuthClient; if (oAuthClient.getId().equals(id))
return oAuthClient;
} }
return null; return null;
@ -754,7 +788,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
return new ArrayList(allOAuthClients.values()); return new ArrayList<OAuthClientModel>(allOAuthClients.values());
} }
@Override @Override
@ -763,7 +797,8 @@ public class RealmAdapter implements RealmModel {
addRequiredCredential(credentialModel, realm.getRequiredCredentials()); addRequiredCredential(credentialModel, realm.getRequiredCredentials());
} }
protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) { protected void addRequiredCredential(RequiredCredentialModel credentialModel,
List<RequiredCredentialEntity> persistentCollection) {
RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); RequiredCredentialEntity credEntity = new RequiredCredentialEntity();
credEntity.setType(credentialModel.getType()); credEntity.setType(credentialModel.getType());
credEntity.setFormLabel(credentialModel.getFormLabel()); credEntity.setFormLabel(credentialModel.getFormLabel());
@ -804,7 +839,8 @@ public class RealmAdapter implements RealmModel {
return convertRequiredCredentialEntities(realm.getRequiredCredentials()); return convertRequiredCredentialEntities(realm.getRequiredCredentials());
} }
protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) { protected List<RequiredCredentialModel> convertRequiredCredentialEntities(
Collection<RequiredCredentialEntity> credEntities) {
List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>();
for (RequiredCredentialEntity entity : credEntities) { for (RequiredCredentialEntity entity : credEntities) {
@ -849,7 +885,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
return new ArrayList(allIdProviders.values()); return new ArrayList<IdentityProviderModel>(allIdProviders.values());
} }
@Override @Override
@ -865,8 +901,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void addIdentityProvider(IdentityProviderModel identityProvider) { public void addIdentityProvider(IdentityProviderModel identityProvider) {
if (identityProvider.getId() == null) throw new NullPointerException("identityProvider.getId() == null"); if (identityProvider.getId() == null)
if (identityProvider.getInternalId() == null) identityProvider.setInternalId(KeycloakModelUtils.generateId()); throw new NullPointerException("identityProvider.getId() == null");
if (identityProvider.getInternalId() == null)
identityProvider.setInternalId(KeycloakModelUtils.generateId());
allIdProviders.put(identityProvider.getInternalId(), identityProvider); allIdProviders.put(identityProvider.getInternalId(), identityProvider);
} }
@ -887,7 +925,8 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) { public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config,
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(KeycloakModelUtils.generateId()); entity.setId(KeycloakModelUtils.generateId());
entity.setPriority(priority); entity.setPriority(priority);
@ -902,7 +941,8 @@ public class RealmAdapter implements RealmModel {
entity.setLastSync(lastSync); entity.setLastSync(lastSync);
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync); return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod,
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -911,8 +951,11 @@ public class RealmAdapter implements RealmModel {
while (it.hasNext()) { while (it.hasNext()) {
UserFederationProviderEntity entity = it.next(); UserFederationProviderEntity entity = it.next();
if (entity.getId().equals(provider.getId())) { if (entity.getId().equals(provider.getId())) {
session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), session.users().preRemove(
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); this,
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
} }
} }
@ -956,8 +999,9 @@ public class RealmAdapter implements RealmModel {
}); });
List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); .getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity
.getLastSync()));
} }
return result; return result;
@ -968,8 +1012,10 @@ public class RealmAdapter implements RealmModel {
List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>();
for (UserFederationProviderModel model : providers) { for (UserFederationProviderModel model : providers) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) entity.setId(model.getId()); if (model.getId() != null)
else entity.setId(KeycloakModelUtils.generateId()); entity.setId(model.getId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
@ -1043,7 +1089,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isIdentityFederationEnabled() { public boolean isIdentityFederationEnabled() {
//TODO: not sure if we will support identity federation storage for file // TODO: not sure if we will support identity federation storage for file
return getIdentityProviders() != null && !getIdentityProviders().isEmpty(); return getIdentityProviders() != null && !getIdentityProviders().isEmpty();
} }
@ -1059,8 +1105,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || !(o instanceof RealmModel)) return false; return true;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());

View file

@ -1,21 +1,5 @@
package org.keycloak.models.cache; package org.keycloak.models.cache;
import org.keycloak.Config;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimTypeModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -27,6 +11,20 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.Config;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.utils.KeycloakModelUtils;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -50,19 +48,22 @@ public class RealmAdapter implements RealmModel {
if (updated == null) { if (updated == null) {
cacheSession.registerRealmInvalidation(getId()); cacheSession.registerRealmInvalidation(getId());
updated = cacheSession.getDelegate().getRealm(getId()); updated = cacheSession.getDelegate().getRealm(getId());
if (updated == null) throw new IllegalStateException("Not found in database"); if (updated == null)
throw new IllegalStateException("Not found in database");
} }
} }
@Override @Override
public String getId() { public String getId() {
if (updated != null) return updated.getId(); if (updated != null)
return updated.getId();
return cached.getId(); return cached.getId();
} }
@Override @Override
public String getName() { public String getName() {
if (updated != null) return updated.getName(); if (updated != null)
return updated.getName();
return cached.getName(); return cached.getName();
} }
@ -74,7 +75,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
if (updated != null) return updated.isEnabled(); if (updated != null)
return updated.isEnabled();
return cached.isEnabled(); return cached.isEnabled();
} }
@ -86,7 +88,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public SslRequired getSslRequired() { public SslRequired getSslRequired() {
if (updated != null) return updated.getSslRequired(); if (updated != null)
return updated.getSslRequired();
return cached.getSslRequired(); return cached.getSslRequired();
} }
@ -98,7 +101,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isRegistrationAllowed() { public boolean isRegistrationAllowed() {
if (updated != null) return updated.isRegistrationAllowed(); if (updated != null)
return updated.isRegistrationAllowed();
return cached.isRegistrationAllowed(); return cached.isRegistrationAllowed();
} }
@ -108,9 +112,23 @@ public class RealmAdapter implements RealmModel {
updated.setRegistrationAllowed(registrationAllowed); updated.setRegistrationAllowed(registrationAllowed);
} }
@Override
public boolean isRegistrationEmailAsUsername() {
if (updated != null)
return updated.isRegistrationEmailAsUsername();
return cached.isRegistrationEmailAsUsername();
}
@Override
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
getDelegateForUpdate();
updated.setRegistrationEmailAsUsername(registrationEmailAsUsername);
}
@Override @Override
public boolean isPasswordCredentialGrantAllowed() { public boolean isPasswordCredentialGrantAllowed() {
if (updated != null) return updated.isPasswordCredentialGrantAllowed(); if (updated != null)
return updated.isPasswordCredentialGrantAllowed();
return cached.isPasswordCredentialGrantAllowed(); return cached.isPasswordCredentialGrantAllowed();
} }
@ -122,7 +140,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isRememberMe() { public boolean isRememberMe() {
if (updated != null) return updated.isRememberMe(); if (updated != null)
return updated.isRememberMe();
return cached.isRememberMe(); return cached.isRememberMe();
} }
@ -134,7 +153,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isBruteForceProtected() { public boolean isBruteForceProtected() {
if (updated != null) return updated.isBruteForceProtected(); if (updated != null)
return updated.isBruteForceProtected();
return cached.isBruteForceProtected(); return cached.isBruteForceProtected();
} }
@ -146,7 +166,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMaxFailureWaitSeconds() { public int getMaxFailureWaitSeconds() {
if (updated != null) return updated.getMaxFailureWaitSeconds(); if (updated != null)
return updated.getMaxFailureWaitSeconds();
return cached.getMaxFailureWaitSeconds(); return cached.getMaxFailureWaitSeconds();
} }
@ -158,7 +179,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getWaitIncrementSeconds() { public int getWaitIncrementSeconds() {
if (updated != null) return updated.getWaitIncrementSeconds(); if (updated != null)
return updated.getWaitIncrementSeconds();
return cached.getWaitIncrementSeconds(); return cached.getWaitIncrementSeconds();
} }
@ -170,7 +192,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMinimumQuickLoginWaitSeconds() { public int getMinimumQuickLoginWaitSeconds() {
if (updated != null) return updated.getMinimumQuickLoginWaitSeconds(); if (updated != null)
return updated.getMinimumQuickLoginWaitSeconds();
return cached.getMinimumQuickLoginWaitSeconds(); return cached.getMinimumQuickLoginWaitSeconds();
} }
@ -182,7 +205,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public long getQuickLoginCheckMilliSeconds() { public long getQuickLoginCheckMilliSeconds() {
if (updated != null) return updated.getQuickLoginCheckMilliSeconds(); if (updated != null)
return updated.getQuickLoginCheckMilliSeconds();
return cached.getQuickLoginCheckMilliSeconds(); return cached.getQuickLoginCheckMilliSeconds();
} }
@ -194,7 +218,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
if (updated != null) return updated.getMaxDeltaTimeSeconds(); if (updated != null)
return updated.getMaxDeltaTimeSeconds();
return cached.getMaxDeltaTimeSeconds(); return cached.getMaxDeltaTimeSeconds();
} }
@ -206,7 +231,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getFailureFactor() { public int getFailureFactor() {
if (updated != null) return updated.getFailureFactor(); if (updated != null)
return updated.getFailureFactor();
return cached.getFailureFactor(); return cached.getFailureFactor();
} }
@ -218,7 +244,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
if (updated != null) return updated.isVerifyEmail(); if (updated != null)
return updated.isVerifyEmail();
return cached.isVerifyEmail(); return cached.isVerifyEmail();
} }
@ -230,7 +257,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isResetPasswordAllowed() { public boolean isResetPasswordAllowed() {
if (updated != null) return updated.isResetPasswordAllowed(); if (updated != null)
return updated.isResetPasswordAllowed();
return cached.isResetPasswordAllowed(); return cached.isResetPasswordAllowed();
} }
@ -242,7 +270,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
if (updated != null) return updated.getSsoSessionIdleTimeout(); if (updated != null)
return updated.getSsoSessionIdleTimeout();
return cached.getSsoSessionIdleTimeout(); return cached.getSsoSessionIdleTimeout();
} }
@ -254,7 +283,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getSsoSessionMaxLifespan() { public int getSsoSessionMaxLifespan() {
if (updated != null) return updated.getSsoSessionMaxLifespan(); if (updated != null)
return updated.getSsoSessionMaxLifespan();
return cached.getSsoSessionMaxLifespan(); return cached.getSsoSessionMaxLifespan();
} }
@ -266,7 +296,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessTokenLifespan() { public int getAccessTokenLifespan() {
if (updated != null) return updated.getAccessTokenLifespan(); if (updated != null)
return updated.getAccessTokenLifespan();
return cached.getAccessTokenLifespan(); return cached.getAccessTokenLifespan();
} }
@ -278,7 +309,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespan() { public int getAccessCodeLifespan() {
if (updated != null) return updated.getAccessCodeLifespan(); if (updated != null)
return updated.getAccessCodeLifespan();
return cached.getAccessCodeLifespan(); return cached.getAccessCodeLifespan();
} }
@ -290,7 +322,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespanUserAction() { public int getAccessCodeLifespanUserAction() {
if (updated != null) return updated.getAccessCodeLifespanUserAction(); if (updated != null)
return updated.getAccessCodeLifespanUserAction();
return cached.getAccessCodeLifespanUserAction(); return cached.getAccessCodeLifespanUserAction();
} }
@ -302,7 +335,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
if (updated != null) return updated.getAccessCodeLifespanLogin(); if (updated != null)
return updated.getAccessCodeLifespanLogin();
return cached.getAccessCodeLifespanLogin(); return cached.getAccessCodeLifespanLogin();
} }
@ -314,7 +348,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getPublicKeyPem() { public String getPublicKeyPem() {
if (updated != null) return updated.getPublicKeyPem(); if (updated != null)
return updated.getPublicKeyPem();
return cached.getPublicKeyPem(); return cached.getPublicKeyPem();
} }
@ -326,7 +361,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
if (updated != null) return updated.getPrivateKeyPem(); if (updated != null)
return updated.getPrivateKeyPem();
return cached.getPrivateKeyPem(); return cached.getPrivateKeyPem();
} }
@ -338,7 +374,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) return publicKey; if (publicKey != null)
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -352,7 +389,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) return certificate; if (certificate != null)
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -366,7 +404,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getCertificatePem() { public String getCertificatePem() {
if (updated != null) return updated.getCertificatePem(); if (updated != null)
return updated.getCertificatePem();
return cached.getCertificatePem(); return cached.getCertificatePem();
} }
@ -379,7 +418,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) return privateKey; if (privateKey != null)
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -414,8 +454,10 @@ public class RealmAdapter implements RealmModel {
public List<RequiredCredentialModel> getRequiredCredentials() { public List<RequiredCredentialModel> getRequiredCredentials() {
List<RequiredCredentialModel> copy = new LinkedList<RequiredCredentialModel>(); List<RequiredCredentialModel> copy = new LinkedList<RequiredCredentialModel>();
if (updated != null) copy.addAll(updated.getRequiredCredentials()); if (updated != null)
else copy.addAll(cached.getRequiredCredentials()); copy.addAll(updated.getRequiredCredentials());
else
copy.addAll(cached.getRequiredCredentials());
return copy; return copy;
} }
@ -427,7 +469,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PasswordPolicy getPasswordPolicy() { public PasswordPolicy getPasswordPolicy() {
if (updated != null) return updated.getPasswordPolicy(); if (updated != null)
return updated.getPasswordPolicy();
return cached.getPasswordPolicy(); return cached.getPasswordPolicy();
} }
@ -439,13 +482,15 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
if (updated != null) return updated.getRoleById(id); if (updated != null)
return updated.getRoleById(id);
return cacheSession.getRoleById(id, this); return cacheSession.getRoleById(id, this);
} }
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
if (updated != null) return updated.getDefaultRoles(); if (updated != null)
return updated.getDefaultRoles();
return cached.getDefaultRoles(); return cached.getDefaultRoles();
} }
@ -463,7 +508,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
if (updated != null) return updated.findClient(clientId); if (updated != null)
return updated.findClient(clientId);
String appId = cached.getApplications().get(clientId); String appId = cached.getApplications().get(clientId);
if (appId != null) { if (appId != null) {
return cacheSession.getApplicationById(appId, this); return cacheSession.getApplicationById(appId, this);
@ -477,7 +523,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, ApplicationModel> getApplicationNameMap() { public Map<String, ApplicationModel> getApplicationNameMap() {
if (updated != null) return updated.getApplicationNameMap(); if (updated != null)
return updated.getApplicationNameMap();
Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>(); Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>();
for (String id : cached.getApplications().values()) { for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this); ApplicationModel model = cacheSession.getApplicationById(id, this);
@ -491,7 +538,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
if (updated != null) return updated.getApplications(); if (updated != null)
return updated.getApplications();
List<ApplicationModel> apps = new LinkedList<ApplicationModel>(); List<ApplicationModel> apps = new LinkedList<ApplicationModel>();
for (String id : cached.getApplications().values()) { for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this); ApplicationModel model = cacheSession.getApplicationById(id, this);
@ -529,15 +577,18 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
if (updated != null) return updated.getApplicationById(id); if (updated != null)
return updated.getApplicationById(id);
return cacheSession.getApplicationById(id, this); return cacheSession.getApplicationById(id, this);
} }
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
if (updated != null) return updated.getApplicationByName(name); if (updated != null)
return updated.getApplicationByName(name);
String id = cached.getApplications().get(name); String id = cached.getApplications().get(name);
if (id == null) return null; if (id == null)
return null;
return getApplicationById(id); return getApplicationById(id);
} }
@ -565,15 +616,18 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
if (updated != null) return updated.getOAuthClient(name); if (updated != null)
return updated.getOAuthClient(name);
String id = cached.getClients().get(name); String id = cached.getClients().get(name);
if (id == null) return null; if (id == null)
return null;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public OAuthClientModel getOAuthClientById(String id) { public OAuthClientModel getOAuthClientById(String id) {
if (updated != null) return updated.getOAuthClientById(id); if (updated != null)
return updated.getOAuthClientById(id);
return cacheSession.getOAuthClientById(id, this); return cacheSession.getOAuthClientById(id, this);
} }
@ -586,7 +640,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
if (updated != null) return updated.getOAuthClients(); if (updated != null)
return updated.getOAuthClients();
List<OAuthClientModel> clients = new LinkedList<OAuthClientModel>(); List<OAuthClientModel> clients = new LinkedList<OAuthClientModel>();
for (String id : cached.getClients().values()) { for (String id : cached.getClients().values()) {
OAuthClientModel model = cacheSession.getOAuthClientById(id, this); OAuthClientModel model = cacheSession.getOAuthClientById(id, this);
@ -600,7 +655,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, String> getBrowserSecurityHeaders() { public Map<String, String> getBrowserSecurityHeaders() {
if (updated != null) return updated.getBrowserSecurityHeaders(); if (updated != null)
return updated.getBrowserSecurityHeaders();
return cached.getBrowserSecurityHeaders(); return cached.getBrowserSecurityHeaders();
} }
@ -613,7 +669,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, String> getSmtpConfig() { public Map<String, String> getSmtpConfig() {
if (updated != null) return updated.getSmtpConfig(); if (updated != null)
return updated.getSmtpConfig();
return cached.getSmtpConfig(); return cached.getSmtpConfig();
} }
@ -623,10 +680,10 @@ public class RealmAdapter implements RealmModel {
updated.setSmtpConfig(smtpConfig); updated.setSmtpConfig(smtpConfig);
} }
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
if (updated != null) return updated.getIdentityProviders(); if (updated != null)
return updated.getIdentityProviders();
return cached.getIdentityProviders(); return cached.getIdentityProviders();
} }
@ -661,7 +718,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<UserFederationProviderModel> getUserFederationProviders() { public List<UserFederationProviderModel> getUserFederationProviders() {
if (updated != null) return updated.getUserFederationProviders(); if (updated != null)
return updated.getUserFederationProviders();
return cached.getUserFederationProviders(); return cached.getUserFederationProviders();
} }
@ -672,9 +730,11 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) { public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config,
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
getDelegateForUpdate(); getDelegateForUpdate();
return updated.addUserFederationProvider(providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync); return updated.addUserFederationProvider(providerName, config, priority, displayName, fullSyncPeriod,
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -693,7 +753,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getLoginTheme() { public String getLoginTheme() {
if (updated != null) return updated.getLoginTheme(); if (updated != null)
return updated.getLoginTheme();
return cached.getLoginTheme(); return cached.getLoginTheme();
} }
@ -705,7 +766,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getAccountTheme() { public String getAccountTheme() {
if (updated != null) return updated.getAccountTheme(); if (updated != null)
return updated.getAccountTheme();
return cached.getAccountTheme(); return cached.getAccountTheme();
} }
@ -717,7 +779,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getAdminTheme() { public String getAdminTheme() {
if (updated != null) return updated.getAdminTheme(); if (updated != null)
return updated.getAdminTheme();
return cached.getAdminTheme(); return cached.getAdminTheme();
} }
@ -729,7 +792,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getEmailTheme() { public String getEmailTheme() {
if (updated != null) return updated.getEmailTheme(); if (updated != null)
return updated.getEmailTheme();
return cached.getEmailTheme(); return cached.getEmailTheme();
} }
@ -741,7 +805,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getNotBefore() { public int getNotBefore() {
if (updated != null) return updated.getNotBefore(); if (updated != null)
return updated.getNotBefore();
return cached.getNotBefore(); return cached.getNotBefore();
} }
@ -760,7 +825,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isEventsEnabled() { public boolean isEventsEnabled() {
if (updated != null) return updated.isEventsEnabled(); if (updated != null)
return updated.isEventsEnabled();
return cached.isEventsEnabled(); return cached.isEventsEnabled();
} }
@ -772,7 +838,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public long getEventsExpiration() { public long getEventsExpiration() {
if (updated != null) return updated.getEventsExpiration(); if (updated != null)
return updated.getEventsExpiration();
return cached.getEventsExpiration(); return cached.getEventsExpiration();
} }
@ -784,7 +851,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<String> getEventsListeners() { public Set<String> getEventsListeners() {
if (updated != null) return updated.getEventsListeners(); if (updated != null)
return updated.getEventsListeners();
return cached.getEventsListeners(); return cached.getEventsListeners();
} }
@ -807,9 +875,11 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRole(String name) { public RoleModel getRole(String name) {
if (updated != null) return updated.getRole(name); if (updated != null)
return updated.getRole(name);
String id = cached.getRealmRoles().get(name); String id = cached.getRealmRoles().get(name);
if (id == null) return null; if (id == null)
return null;
return cacheSession.getRoleById(id, this); return cacheSession.getRoleById(id, this);
} }
@ -838,12 +908,14 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
if (updated != null) return updated.getRoles(); if (updated != null)
return updated.getRoles();
Set<RoleModel> roles = new HashSet<RoleModel>(); Set<RoleModel> roles = new HashSet<RoleModel>();
for (String id : cached.getRealmRoles().values()) { for (String id : cached.getRealmRoles().values()) {
RoleModel roleById = cacheSession.getRoleById(id, this); RoleModel roleById = cacheSession.getRoleById(id, this);
if (roleById == null) continue; if (roleById == null)
continue;
roles.add(roleById); roles.add(roleById);
} }
return roles; return roles;
@ -852,21 +924,24 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) return model; if (model != null)
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public boolean isIdentityFederationEnabled() { public boolean isIdentityFederationEnabled() {
if (updated != null) return updated.isIdentityFederationEnabled(); if (updated != null)
return updated.isIdentityFederationEnabled();
return cached.isIdentityFederationEnabled(); return cached.isIdentityFederationEnabled();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || !(o instanceof RealmModel)) return false; return true;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());

View file

@ -1,19 +1,5 @@
package org.keycloak.models.cache.entities; package org.keycloak.models.cache.entities;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimTypeModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.RealmCache;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -22,6 +8,18 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.RealmCache;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -33,12 +31,13 @@ public class CachedRealm {
private boolean enabled; private boolean enabled;
private SslRequired sslRequired; private SslRequired sslRequired;
private boolean registrationAllowed; private boolean registrationAllowed;
protected boolean registrationEmailAsUsername;
private boolean rememberMe; private boolean rememberMe;
private boolean verifyEmail; private boolean verifyEmail;
private boolean passwordCredentialGrantAllowed; private boolean passwordCredentialGrantAllowed;
private boolean resetPasswordAllowed; private boolean resetPasswordAllowed;
private boolean identityFederationEnabled; private boolean identityFederationEnabled;
//--- brute force settings // --- brute force settings
private boolean bruteForceProtected; private boolean bruteForceProtected;
private int maxFailureWaitSeconds; private int maxFailureWaitSeconds;
private int minimumQuickLoginWaitSeconds; private int minimumQuickLoginWaitSeconds;
@ -46,7 +45,7 @@ public class CachedRealm {
private long quickLoginCheckMilliSeconds; private long quickLoginCheckMilliSeconds;
private int maxDeltaTimeSeconds; private int maxDeltaTimeSeconds;
private int failureFactor; private int failureFactor;
//--- end brute force settings // --- end brute force settings
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@ -92,12 +91,13 @@ public class CachedRealm {
enabled = model.isEnabled(); enabled = model.isEnabled();
sslRequired = model.getSslRequired(); sslRequired = model.getSslRequired();
registrationAllowed = model.isRegistrationAllowed(); registrationAllowed = model.isRegistrationAllowed();
registrationEmailAsUsername = model.isRegistrationEmailAsUsername();
rememberMe = model.isRememberMe(); rememberMe = model.isRememberMe();
verifyEmail = model.isVerifyEmail(); verifyEmail = model.isVerifyEmail();
passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed(); passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed();
resetPasswordAllowed = model.isResetPasswordAllowed(); resetPasswordAllowed = model.isResetPasswordAllowed();
identityFederationEnabled = model.isIdentityFederationEnabled(); identityFederationEnabled = model.isIdentityFederationEnabled();
//--- brute force settings // --- brute force settings
bruteForceProtected = model.isBruteForceProtected(); bruteForceProtected = model.isBruteForceProtected();
maxFailureWaitSeconds = model.getMaxFailureWaitSeconds(); maxFailureWaitSeconds = model.getMaxFailureWaitSeconds();
minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds(); minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds();
@ -105,7 +105,7 @@ public class CachedRealm {
quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds(); quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds();
maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds(); maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds();
failureFactor = model.getFailureFactor(); failureFactor = model.getFailureFactor();
//--- end brute force settings // --- end brute force settings
ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout(); ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout();
ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan(); ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan();
@ -164,7 +164,6 @@ public class CachedRealm {
} }
public String getId() { public String getId() {
return id; return id;
} }
@ -205,6 +204,10 @@ public class CachedRealm {
return registrationAllowed; return registrationAllowed;
} }
public boolean isRegistrationEmailAsUsername() {
return registrationEmailAsUsername;
}
public boolean isPasswordCredentialGrantAllowed() { public boolean isPasswordCredentialGrantAllowed() {
return passwordCredentialGrantAllowed; return passwordCredentialGrantAllowed;
} }
@ -268,6 +271,7 @@ public class CachedRealm {
public int getAccessCodeLifespanUserAction() { public int getAccessCodeLifespanUserAction() {
return accessCodeLifespanUserAction; return accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }

View file

@ -1,5 +1,24 @@
package org.keycloak.models.jpa; package org.keycloak.models.jpa;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
@ -21,24 +40,6 @@ import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.UserFederationProviderEntity; import org.keycloak.models.jpa.entities.UserFederationProviderEntity;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -123,6 +124,17 @@ public class RealmAdapter implements RealmModel {
em.flush(); em.flush();
} }
@Override
public boolean isRegistrationEmailAsUsername() {
return realm.isRegistrationEmailAsUsername();
}
@Override
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
realm.setRegistrationEmailAsUsername(registrationEmailAsUsername);
em.flush();
}
@Override @Override
public boolean isRememberMe() { public boolean isRememberMe() {
return realm.isRememberMe(); return realm.isRememberMe();
@ -207,6 +219,7 @@ public class RealmAdapter implements RealmModel {
} }
return result; return result;
} }
@Override @Override
public boolean isBruteForceProtected() { public boolean isBruteForceProtected() {
return getAttribute("bruteForceProtected", false); return getAttribute("bruteForceProtected", false);
@ -386,7 +399,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) return certificate; if (certificate != null)
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -423,7 +437,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) return publicKey; if (publicKey != null)
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -437,7 +452,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) return privateKey; if (privateKey != null)
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -497,7 +513,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void updateRequiredCredentials(Set<String> creds) { public void updateRequiredCredentials(Set<String> creds) {
Collection<RequiredCredentialEntity> relationships = realm.getRequiredCredentials(); Collection<RequiredCredentialEntity> relationships = realm.getRequiredCredentials();
if (relationships == null) relationships = new ArrayList<RequiredCredentialEntity>(); if (relationships == null)
relationships = new ArrayList<RequiredCredentialEntity>();
Set<String> already = new HashSet<String>(); Set<String> already = new HashSet<String>();
List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>(); List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>();
@ -520,12 +537,12 @@ public class RealmAdapter implements RealmModel {
em.flush(); em.flush();
} }
@Override @Override
public List<RequiredCredentialModel> getRequiredCredentials() { public List<RequiredCredentialModel> getRequiredCredentials() {
List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>();
Collection<RequiredCredentialEntity> entities = realm.getRequiredCredentials(); Collection<RequiredCredentialEntity> entities = realm.getRequiredCredentials();
if (entities == null) return requiredCredentialModels; if (entities == null)
return requiredCredentialModels;
for (RequiredCredentialEntity entity : entities) { for (RequiredCredentialEntity entity : entities) {
RequiredCredentialModel model = new RequiredCredentialModel(); RequiredCredentialModel model = new RequiredCredentialModel();
model.setFormLabel(entity.getFormLabel()); model.setFormLabel(entity.getFormLabel());
@ -534,15 +551,15 @@ public class RealmAdapter implements RealmModel {
model.setInput(entity.isInput()); model.setInput(entity.isInput());
requiredCredentialModels.add(model); requiredCredentialModels.add(model);
} }
return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates. return requiredCredentialModels; // To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
Collection<RoleEntity> entities = realm.getDefaultRoles(); Collection<RoleEntity> entities = realm.getDefaultRoles();
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
if (entities == null) return roles; if (entities == null)
return roles;
for (RoleEntity entity : entities) { for (RoleEntity entity : entities) {
roles.add(entity.getName()); roles.add(entity.getName());
} }
@ -568,7 +585,8 @@ public class RealmAdapter implements RealmModel {
public static boolean contains(String str, String[] array) { public static boolean contains(String str, String[] array) {
for (String s : array) { for (String s : array) {
if (str.equals(s)) return true; if (str.equals(s))
return true;
} }
return false; return false;
} }
@ -600,14 +618,16 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) return model; if (model != null)
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) return model; if (model != null)
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@ -617,13 +637,14 @@ public class RealmAdapter implements RealmModel {
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
map.put(app.getName(), app); map.put(app.getName(), app);
} }
return map; //To change body of implemented methods use File | Settings | File Templates. return map; // To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
List<ApplicationModel> list = new ArrayList<ApplicationModel>(); List<ApplicationModel> list = new ArrayList<ApplicationModel>();
if (realm.getApplications() == null) return list; if (realm.getApplications() == null)
return list;
for (ApplicationEntity entity : realm.getApplications()) { for (ApplicationEntity entity : realm.getApplications()) {
list.add(new ApplicationAdapter(this, em, session, entity)); list.add(new ApplicationAdapter(this, em, session, entity));
} }
@ -663,9 +684,11 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeApplication(String id) { public boolean removeApplication(String id) {
if (id == null) return false; if (id == null)
return false;
ApplicationModel application = getApplicationById(id); ApplicationModel application = getApplicationById(id);
if (application == null) return false; if (application == null)
return false;
for (RoleModel role : application.getRoles()) { for (RoleModel role : application.getRoles()) {
application.removeRole(role); application.removeRole(role);
@ -739,21 +762,22 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeOAuthClient(String id) { public boolean removeOAuthClient(String id) {
OAuthClientModel oauth = getOAuthClientById(id); OAuthClientModel oauth = getOAuthClientById(id);
if (oauth == null) return false; if (oauth == null)
return false;
OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId()); OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId());
em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", client).executeUpdate(); em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", client).executeUpdate();
em.remove(client); em.remove(client);
return true; return true;
} }
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByName", OAuthClientEntity.class); TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByName", OAuthClientEntity.class);
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<OAuthClientEntity> entities = query.getResultList(); List<OAuthClientEntity> entities = query.getResultList();
if (entities.size() == 0) return null; if (entities.size() == 0)
return null;
return new OAuthClientAdapter(this, entities.get(0), em); return new OAuthClientAdapter(this, entities.get(0), em);
} }
@ -762,14 +786,14 @@ public class RealmAdapter implements RealmModel {
return session.realms().getOAuthClientById(id, this); return session.realms().getOAuthClientById(id, this);
} }
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByRealm", OAuthClientEntity.class); TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByRealm", OAuthClientEntity.class);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<OAuthClientEntity> entities = query.getResultList(); List<OAuthClientEntity> entities = query.getResultList();
List<OAuthClientModel> list = new ArrayList<OAuthClientModel>(); List<OAuthClientModel> list = new ArrayList<OAuthClientModel>();
for (OAuthClientEntity entity : entities) list.add(new OAuthClientAdapter(this, entity, em)); for (OAuthClientEntity entity : entities)
list.add(new OAuthClientAdapter(this, entity, em));
return list; return list;
} }
@ -823,15 +847,17 @@ public class RealmAdapter implements RealmModel {
}); });
List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); .getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity
.getLastSync()));
} }
return result; return result;
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) { public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config,
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
String id = KeycloakModelUtils.generateId(); String id = KeycloakModelUtils.generateId();
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(id); entity.setId(id);
@ -849,7 +875,8 @@ public class RealmAdapter implements RealmModel {
em.persist(entity); em.persist(entity);
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
em.flush(); em.flush();
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync); return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod,
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -865,6 +892,7 @@ public class RealmAdapter implements RealmModel {
} }
} }
} }
@Override @Override
public void updateUserFederationProvider(UserFederationProviderModel model) { public void updateUserFederationProvider(UserFederationProviderModel model) {
Iterator<UserFederationProviderEntity> it = realm.getUserFederationProviders().iterator(); Iterator<UserFederationProviderEntity> it = realm.getUserFederationProviders().iterator();
@ -912,9 +940,13 @@ public class RealmAdapter implements RealmModel {
} }
} }
if (found) continue; if (found)
session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), continue;
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); session.users().preRemove(
this,
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
em.remove(entity); em.remove(entity);
} }
@ -928,13 +960,16 @@ public class RealmAdapter implements RealmModel {
break; break;
} }
} }
if (!found) add.add(model); if (!found)
add.add(model);
} }
for (UserFederationProviderModel model : add) { for (UserFederationProviderModel model : add) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) entity.setId(model.getId()); if (model.getId() != null)
else entity.setId(KeycloakModelUtils.generateId()); entity.setId(model.getId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
@ -959,7 +994,8 @@ public class RealmAdapter implements RealmModel {
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<RoleEntity> roles = query.getResultList(); List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null; if (roles.size() == 0)
return null;
return new RoleAdapter(this, em, roles.get(0)); return new RoleAdapter(this, em, roles.get(0));
} }
@ -986,13 +1022,15 @@ public class RealmAdapter implements RealmModel {
if (role == null) { if (role == null) {
return false; return false;
} }
if (!role.getContainer().equals(this)) return false; if (!role.getContainer().equals(this))
return false;
session.users().preRemove(this, role); session.users().preRemove(this, role);
RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em); RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em);
realm.getRoles().remove(role); realm.getRoles().remove(role);
realm.getDefaultRoles().remove(role); realm.getDefaultRoles().remove(role);
em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", roleEntity).executeUpdate(); em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", roleEntity)
.executeUpdate();
em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", roleEntity).executeUpdate(); em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", roleEntity).executeUpdate();
em.remove(roleEntity); em.remove(roleEntity);
@ -1004,7 +1042,8 @@ public class RealmAdapter implements RealmModel {
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>(); Set<RoleModel> list = new HashSet<RoleModel>();
Collection<RoleEntity> roles = realm.getRoles(); Collection<RoleEntity> roles = realm.getRoles();
if (roles == null) return list; if (roles == null)
return list;
for (RoleEntity entity : roles) { for (RoleEntity entity : roles) {
list.add(new RoleAdapter(this, em, entity)); list.add(new RoleAdapter(this, em, entity));
} }
@ -1019,7 +1058,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
RoleModel role = getRoleById(id); RoleModel role = getRoleById(id);
if (role == null) return false; if (role == null)
return false;
return role.getContainer().removeRole(role); return role.getContainer().removeRole(role);
} }
@ -1040,8 +1080,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || !(o instanceof RealmModel)) return false; return true;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());
@ -1136,7 +1178,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void setMasterAdminApp(ApplicationModel app) { public void setMasterAdminApp(ApplicationModel app) {
ApplicationEntity appEntity = app!=null ? em.getReference(ApplicationEntity.class, app.getId()) : null; ApplicationEntity appEntity = app != null ? em.getReference(ApplicationEntity.class, app.getId()) : null;
realm.setMasterAdminApp(appEntity); realm.setMasterAdminApp(appEntity);
em.flush(); em.flush();
} }
@ -1145,7 +1187,7 @@ public class RealmAdapter implements RealmModel {
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>(); List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>();
for (IdentityProviderEntity entity: realm.getIdentityProviders()) { for (IdentityProviderEntity entity : realm.getIdentityProviders()) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setProviderId(entity.getProviderId()); identityProviderModel.setProviderId(entity.getProviderId());

View file

@ -1,5 +1,13 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
@ -15,124 +23,117 @@ import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Table(name="REALM") @Table(name = "REALM")
@Entity @Entity
@NamedQueries({ @NamedQueries({ @NamedQuery(name = "getAllRealms", query = "select realm from RealmEntity realm"),
@NamedQuery(name="getAllRealms", query="select realm from RealmEntity realm"), @NamedQuery(name = "getRealmByName", query = "select realm from RealmEntity realm where realm.name = :name"), })
@NamedQuery(name="getRealmByName", query="select realm from RealmEntity realm where realm.name = :name"),
})
public class RealmEntity { public class RealmEntity {
@Id @Id
@Column(name="ID", length = 36) @Column(name = "ID", length = 36)
protected String id; protected String id;
@Column(name="NAME", unique = true) @Column(name = "NAME", unique = true)
protected String name; protected String name;
@Column(name="ENABLED") @Column(name = "ENABLED")
protected boolean enabled; protected boolean enabled;
@Column(name="SSL_REQUIRED") @Column(name = "SSL_REQUIRED")
protected String sslRequired; protected String sslRequired;
@Column(name="REGISTRATION_ALLOWED") @Column(name = "REGISTRATION_ALLOWED")
protected boolean registrationAllowed; protected boolean registrationAllowed;
@Column(name="PASSWORD_CRED_GRANT_ALLOWED") @Column(name = "REGISTRATION_EMAIL_AS_USERNAME")
protected boolean registrationEmailAsUsername;
@Column(name = "PASSWORD_CRED_GRANT_ALLOWED")
protected boolean passwordCredentialGrantAllowed; protected boolean passwordCredentialGrantAllowed;
@Column(name="VERIFY_EMAIL") @Column(name = "VERIFY_EMAIL")
protected boolean verifyEmail; protected boolean verifyEmail;
@Column(name="RESET_PASSWORD_ALLOWED") @Column(name = "RESET_PASSWORD_ALLOWED")
protected boolean resetPasswordAllowed; protected boolean resetPasswordAllowed;
@Column(name="REMEMBER_ME") @Column(name = "REMEMBER_ME")
protected boolean rememberMe; protected boolean rememberMe;
@Column(name="PASSWORD_POLICY") @Column(name = "PASSWORD_POLICY")
protected String passwordPolicy; protected String passwordPolicy;
@Column(name="SSO_IDLE_TIMEOUT") @Column(name = "SSO_IDLE_TIMEOUT")
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
@Column(name="SSO_MAX_LIFESPAN") @Column(name = "SSO_MAX_LIFESPAN")
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@Column(name="ACCESS_TOKEN_LIFESPAN") @Column(name = "ACCESS_TOKEN_LIFESPAN")
protected int accessTokenLifespan; protected int accessTokenLifespan;
@Column(name="ACCESS_CODE_LIFESPAN") @Column(name = "ACCESS_CODE_LIFESPAN")
protected int accessCodeLifespan; protected int accessCodeLifespan;
@Column(name="USER_ACTION_LIFESPAN") @Column(name = "USER_ACTION_LIFESPAN")
protected int accessCodeLifespanUserAction; protected int accessCodeLifespanUserAction;
@Column(name="LOGIN_LIFESPAN") @Column(name = "LOGIN_LIFESPAN")
protected int accessCodeLifespanLogin; protected int accessCodeLifespanLogin;
@Column(name="NOT_BEFORE") @Column(name = "NOT_BEFORE")
protected int notBefore; protected int notBefore;
@Column(name="PUBLIC_KEY", length = 2048) @Column(name = "PUBLIC_KEY", length = 2048)
protected String publicKeyPem; protected String publicKeyPem;
@Column(name="PRIVATE_KEY", length = 2048) @Column(name = "PRIVATE_KEY", length = 2048)
protected String privateKeyPem; protected String privateKeyPem;
@Column(name="CERTIFICATE", length = 2048) @Column(name = "CERTIFICATE", length = 2048)
protected String certificatePem; protected String certificatePem;
@Column(name="CODE_SECRET", length = 255) @Column(name = "CODE_SECRET", length = 255)
protected String codeSecret; protected String codeSecret;
@Column(name="LOGIN_THEME") @Column(name = "LOGIN_THEME")
protected String loginTheme; protected String loginTheme;
@Column(name="ACCOUNT_THEME") @Column(name = "ACCOUNT_THEME")
protected String accountTheme; protected String accountTheme;
@Column(name="ADMIN_THEME") @Column(name = "ADMIN_THEME")
protected String adminTheme; protected String adminTheme;
@Column(name="EMAIL_THEME") @Column(name = "EMAIL_THEME")
protected String emailTheme; protected String emailTheme;
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>(); Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>();
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>(); Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name="FED_PROVIDERS") @JoinTable(name = "FED_PROVIDERS")
List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name="REALM_APPLICATION", joinColumns={ @JoinColumn(name="APPLICATION_ID") }, inverseJoinColumns={ @JoinColumn(name="REALM_ID") }) @JoinTable(name = "REALM_APPLICATION", joinColumns = { @JoinColumn(name = "APPLICATION_ID") }, inverseJoinColumns = { @JoinColumn(name = "REALM_ID") })
Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>(); Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
Collection<RoleEntity> roles = new ArrayList<RoleEntity>(); Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@ElementCollection @ElementCollection
@MapKeyColumn(name="NAME") @MapKeyColumn(name = "NAME")
@Column(name="VALUE") @Column(name = "VALUE")
@CollectionTable(name="REALM_SMTP_CONFIG", joinColumns={ @JoinColumn(name="REALM_ID") }) @CollectionTable(name = "REALM_SMTP_CONFIG", joinColumns = { @JoinColumn(name = "REALM_ID") })
protected Map<String, String> smtpConfig = new HashMap<String, String>(); protected Map<String, String> smtpConfig = new HashMap<String, String>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name="REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name="REALM_ID")}, inverseJoinColumns = { @JoinColumn(name="ROLE_ID")}) @JoinTable(name = "REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name = "REALM_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>(); protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
@Column(name="EVENTS_ENABLED") @Column(name = "EVENTS_ENABLED")
protected boolean eventsEnabled; protected boolean eventsEnabled;
@Column(name="EVENTS_EXPIRATION") @Column(name = "EVENTS_EXPIRATION")
protected long eventsExpiration; protected long eventsExpiration;
@ElementCollection @ElementCollection
@Column(name="VALUE") @Column(name = "VALUE")
@CollectionTable(name="REALM_EVENTS_LISTENERS", joinColumns={ @JoinColumn(name="REALM_ID") }) @CollectionTable(name = "REALM_EVENTS_LISTENERS", joinColumns = { @JoinColumn(name = "REALM_ID") })
protected Set<String> eventsListeners = new HashSet<String>(); protected Set<String> eventsListeners = new HashSet<String>();
@OneToOne @OneToOne
@JoinColumn(name="MASTER_ADMIN_APP") @JoinColumn(name = "MASTER_ADMIN_APP")
protected ApplicationEntity masterAdminApp; protected ApplicationEntity masterAdminApp;
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>(); protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
public String getId() { public String getId() {
@ -183,6 +184,14 @@ public class RealmEntity {
this.registrationAllowed = registrationAllowed; this.registrationAllowed = registrationAllowed;
} }
public boolean isRegistrationEmailAsUsername() {
return registrationEmailAsUsername;
}
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
this.registrationEmailAsUsername = registrationEmailAsUsername;
}
public boolean isRememberMe() { public boolean isRememberMe() {
return rememberMe; return rememberMe;
} }
@ -246,6 +255,7 @@ public class RealmEntity {
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }
@ -443,4 +453,3 @@ public class RealmEntity {
} }
} }

View file

@ -1,7 +1,21 @@
package org.keycloak.models.mongo.keycloak.adapters; package org.keycloak.models.mongo.keycloak.adapters;
import com.mongodb.DBObject; import java.security.Key;
import com.mongodb.QueryBuilder; import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
@ -24,21 +38,8 @@ import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import java.security.Key; import com.mongodb.DBObject;
import java.security.PrivateKey; import com.mongodb.QueryBuilder;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
@ -56,7 +57,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
private volatile transient PasswordPolicy passwordPolicy; private volatile transient PasswordPolicy passwordPolicy;
private volatile transient KeycloakSession session; private volatile transient KeycloakSession session;
public RealmAdapter(KeycloakSession session, MongoRealmEntity realmEntity, MongoStoreInvocationContext invocationContext) { public RealmAdapter(KeycloakSession session, MongoRealmEntity realmEntity,
MongoStoreInvocationContext invocationContext) {
super(invocationContext); super(invocationContext);
this.realm = realmEntity; this.realm = realmEntity;
this.session = session; this.session = session;
@ -123,6 +125,15 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
public boolean isRegistrationEmailAsUsername() {
return realm.isRegistrationEmailAsUsername();
}
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
realm.setRegistrationEmailAsUsername(registrationEmailAsUsername);
updateRealm();
}
@Override @Override
public boolean isRememberMe() { public boolean isRememberMe() {
return realm.isRememberMe(); return realm.isRememberMe();
@ -189,7 +200,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
return realm.getMaxDeltaTimeSeconds(); return realm.getMaxDeltaTimeSeconds();
@ -212,7 +222,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
return realm.isVerifyEmail(); return realm.isVerifyEmail();
@ -261,7 +270,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
return realm.getSsoSessionIdleTimeout(); return realm.getSsoSessionIdleTimeout();
@ -342,7 +350,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) return certificate; if (certificate != null)
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -366,7 +375,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
} }
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
return realm.getPrivateKeyPem(); return realm.getPrivateKeyPem();
@ -381,7 +389,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) return publicKey; if (publicKey != null)
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -395,7 +404,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) return privateKey; if (privateKey != null)
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -472,10 +482,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public RoleAdapter getRole(String name) { public RoleAdapter getRole(String name) {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("name").is(name).and("realmId").is(getId()).get();
.and("name").is(name)
.and("realmId").is(getId())
.get();
MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext); MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext);
if (role == null) { if (role == null) {
return null; return null;
@ -509,21 +516,21 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
RoleModel role = getRoleById(id); RoleModel role = getRoleById(id);
if (role == null) return false; if (role == null)
return false;
session.users().preRemove(this, role); session.users().preRemove(this, role);
return getMongoStore().removeEntity(MongoRoleEntity.class, id, invocationContext); return getMongoStore().removeEntity(MongoRoleEntity.class, id, invocationContext);
} }
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("realmId").is(getId()).get();
.and("realmId").is(getId())
.get();
List<MongoRoleEntity> roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); List<MongoRoleEntity> roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext);
Set<RoleModel> result = new HashSet<RoleModel>(); Set<RoleModel> result = new HashSet<RoleModel>();
if (roles == null) return result; if (roles == null)
return result;
for (MongoRoleEntity role : roles) { for (MongoRoleEntity role : roles) {
result.add(new RoleAdapter(session, this, role, this, invocationContext)); result.add(new RoleAdapter(session, this, role, this, invocationContext));
} }
@ -570,19 +577,19 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) return model; if (model != null)
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) return model; if (model != null)
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
return model.getApplicationById(id, this); return model.getApplicationById(id, this);
@ -590,11 +597,9 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("realmId").is(getId()).and("name").is(name).get();
.and("realmId").is(getId()) MongoApplicationEntity appEntity = getMongoStore().loadSingleEntity(MongoApplicationEntity.class, query,
.and("name").is(name) invocationContext);
.get();
MongoApplicationEntity appEntity = getMongoStore().loadSingleEntity(MongoApplicationEntity.class, query, invocationContext);
return appEntity == null ? null : new ApplicationAdapter(session, this, appEntity, invocationContext); return appEntity == null ? null : new ApplicationAdapter(session, this, appEntity, invocationContext);
} }
@ -609,10 +614,9 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("realmId").is(getId()).get();
.and("realmId").is(getId()) List<MongoApplicationEntity> appDatas = getMongoStore().loadEntities(MongoApplicationEntity.class, query,
.get(); invocationContext);
List<MongoApplicationEntity> appDatas = getMongoStore().loadEntities(MongoApplicationEntity.class, query, invocationContext);
List<ApplicationModel> result = new ArrayList<ApplicationModel>(); List<ApplicationModel> result = new ArrayList<ApplicationModel>();
for (MongoApplicationEntity appData : appDatas) { for (MongoApplicationEntity appData : appDatas) {
@ -690,11 +694,9 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("realmId").is(getId()).and("name").is(name).get();
.and("realmId").is(getId()) MongoOAuthClientEntity oauthClient = getMongoStore().loadSingleEntity(MongoOAuthClientEntity.class, query,
.and("name").is(name) invocationContext);
.get();
MongoOAuthClientEntity oauthClient = getMongoStore().loadSingleEntity(MongoOAuthClientEntity.class, query, invocationContext);
return oauthClient == null ? null : new OAuthClientAdapter(session, this, oauthClient, invocationContext); return oauthClient == null ? null : new OAuthClientAdapter(session, this, oauthClient, invocationContext);
} }
@ -705,10 +707,9 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder().and("realmId").is(getId()).get();
.and("realmId").is(getId()) List<MongoOAuthClientEntity> results = getMongoStore().loadEntities(MongoOAuthClientEntity.class, query,
.get(); invocationContext);
List<MongoOAuthClientEntity> results = getMongoStore().loadEntities(MongoOAuthClientEntity.class, query, invocationContext);
List<OAuthClientModel> list = new ArrayList<OAuthClientModel>(); List<OAuthClientModel> list = new ArrayList<OAuthClientModel>();
for (MongoOAuthClientEntity data : results) { for (MongoOAuthClientEntity data : results) {
list.add(new OAuthClientAdapter(session, this, data, invocationContext)); list.add(new OAuthClientAdapter(session, this, data, invocationContext));
@ -722,7 +723,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
addRequiredCredential(credentialModel, realm.getRequiredCredentials()); addRequiredCredential(credentialModel, realm.getRequiredCredentials());
} }
protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) { protected void addRequiredCredential(RequiredCredentialModel credentialModel,
List<RequiredCredentialEntity> persistentCollection) {
RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); RequiredCredentialEntity credEntity = new RequiredCredentialEntity();
credEntity.setType(credentialModel.getType()); credEntity.setType(credentialModel.getType());
credEntity.setFormLabel(credentialModel.getFormLabel()); credEntity.setFormLabel(credentialModel.getFormLabel());
@ -766,7 +768,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
return convertRequiredCredentialEntities(realm.getRequiredCredentials()); return convertRequiredCredentialEntities(realm.getRequiredCredentials());
} }
protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) { protected List<RequiredCredentialModel> convertRequiredCredentialEntities(
Collection<RequiredCredentialEntity> credEntities) {
List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>();
for (RequiredCredentialEntity entity : credEntities) { for (RequiredCredentialEntity entity : credEntities) {
@ -815,12 +818,11 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>(); List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>();
for (IdentityProviderEntity entity: realm.getIdentityProviders()) { for (IdentityProviderEntity entity : realm.getIdentityProviders()) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setProviderId(entity.getProviderId()); identityProviderModel.setProviderId(entity.getProviderId());
@ -898,7 +900,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) { public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config,
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(KeycloakModelUtils.generateId()); entity.setId(KeycloakModelUtils.generateId());
entity.setPriority(priority); entity.setPriority(priority);
@ -914,7 +917,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
updateRealm(); updateRealm();
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync); return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod,
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -923,8 +927,11 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
while (it.hasNext()) { while (it.hasNext()) {
UserFederationProviderEntity entity = it.next(); UserFederationProviderEntity entity = it.next();
if (entity.getId().equals(provider.getId())) { if (entity.getId().equals(provider.getId())) {
session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), session.users().preRemove(
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); this,
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
} }
} }
@ -970,8 +977,9 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
}); });
List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); .getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity
.getLastSync()));
} }
return result; return result;
@ -982,8 +990,10 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>();
for (UserFederationProviderModel model : providers) { for (UserFederationProviderModel model : providers) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) entity.setId(model.getId()); if (model.getId() != null)
else entity.setId(KeycloakModelUtils.generateId()); entity.setId(model.getId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
@ -1041,7 +1051,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ApplicationModel getMasterAdminApp() { public ApplicationModel getMasterAdminApp() {
MongoApplicationEntity appData = getMongoStore().loadEntity(MongoApplicationEntity.class, realm.getAdminAppId(), invocationContext); MongoApplicationEntity appData = getMongoStore().loadEntity(MongoApplicationEntity.class, realm.getAdminAppId(),
invocationContext);
return appData != null ? new ApplicationAdapter(session, this, appData, invocationContext) : null; return appData != null ? new ApplicationAdapter(session, this, appData, invocationContext) : null;
} }
@ -1064,8 +1075,10 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || !(o instanceof RealmModel)) return false; return true;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());
@ -1076,5 +1089,4 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
return getId().hashCode(); return getId().hashCode();
} }
} }

View file

@ -56,6 +56,7 @@ public class ApplianceBootstrap {
realm.setAccessCodeLifespanUserAction(300); realm.setAccessCodeLifespanUserAction(300);
realm.setSslRequired(SslRequired.EXTERNAL); realm.setSslRequired(SslRequired.EXTERNAL);
realm.setRegistrationAllowed(false); realm.setRegistrationAllowed(false);
realm.setRegistrationEmailAsUsername(false);
KeycloakModelUtils.generateRealmKeys(realm); KeycloakModelUtils.generateRealmKeys(realm);
UserModel adminUser = session.users().addUser(realm, "admin"); UserModel adminUser = session.users().addUser(realm, "admin");

View file

@ -17,6 +17,26 @@
*/ */
package org.keycloak.services.resources; package org.keycloak.services.resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.ClientConnection; import org.keycloak.ClientConnection;
@ -50,32 +70,14 @@ import org.keycloak.services.resources.flows.Flows;
import org.keycloak.services.resources.flows.Urls; import org.keycloak.services.resources.flows.Urls;
import org.keycloak.social.SocialIdentityProvider; import org.keycloak.social.SocialIdentityProvider;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT; import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT;
import static org.keycloak.models.ClientSessionModel.Action.AUTHENTICATE; import static org.keycloak.models.ClientSessionModel.Action.AUTHENTICATE;
import static org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_APP; 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
*/ */
@ -108,7 +110,8 @@ public class IdentityBrokerService {
} }
public void init() { public void init() {
this.event = new EventsManager(this.realmModel, this.session, this.clientConnection).createEventBuilder().event(EventType.IDENTITY_PROVIDER_LOGIN); this.event = new EventsManager(this.realmModel, this.session, this.clientConnection).createEventBuilder().event(
EventType.IDENTITY_PROVIDER_LOGIN);
} }
@GET @GET
@ -123,7 +126,8 @@ public class IdentityBrokerService {
try { try {
ClientSessionCode clientSessionCode = parseClientSessionCode(code, providerId); ClientSessionCode clientSessionCode = parseClientSessionCode(code, providerId);
IdentityProvider identityProvider = getIdentityProvider(providerId); IdentityProvider identityProvider = getIdentityProvider(providerId);
AuthenticationResponse authenticationResponse = identityProvider.handleRequest(createAuthenticationRequest(providerId, clientSessionCode)); AuthenticationResponse authenticationResponse = identityProvider.handleRequest(createAuthenticationRequest(
providerId, clientSessionCode));
Response response = authenticationResponse.getResponse(); Response response = authenticationResponse.getResponse();
@ -137,7 +141,8 @@ public class IdentityBrokerService {
} catch (IdentityBrokerException e) { } catch (IdentityBrokerException e) {
return redirectToErrorPage("Could not send authentication request to identity provider [" + providerId + "].", e); return redirectToErrorPage("Could not send authentication request to identity provider [" + providerId + "].", e);
} catch (Exception e) { } catch (Exception e) {
return redirectToErrorPage("Unexpected error when handling authentication request to identity provider [" + providerId + "].", e); return redirectToErrorPage("Unexpected error when handling authentication request to identity provider ["
+ providerId + "].", e);
} }
return redirectToErrorPage("Could not proceed with authentication request to identity provider."); return redirectToErrorPage("Could not proceed with authentication request to identity provider.");
@ -172,7 +177,8 @@ public class IdentityBrokerService {
try { try {
AppAuthManager authManager = new AppAuthManager(); AppAuthManager authManager = new AppAuthManager();
AuthResult authResult = authManager.authenticateBearerToken(this.session, this.realmModel, this.uriInfo, this.clientConnection, this.request.getHttpHeaders()); AuthResult authResult = authManager.authenticateBearerToken(this.session, this.realmModel, this.uriInfo,
this.clientConnection, this.request.getHttpHeaders());
if (authResult != null) { if (authResult != null) {
String audience = authResult.getToken().getAudience(); String audience = authResult.getToken().getAudience();
@ -187,27 +193,27 @@ public class IdentityBrokerService {
} }
if (!clientModel.isAllowedRetrieveTokenFromIdentityProvider(providerId)) { if (!clientModel.isAllowedRetrieveTokenFromIdentityProvider(providerId)) {
return corsResponse(badRequest("Client [" + audience + "] not authorized to retrieve tokens from identity provider [" + providerId + "]."), clientModel); return corsResponse(badRequest("Client [" + audience
+ "] not authorized to retrieve tokens from identity provider [" + providerId + "]."), clientModel);
} }
if (OAuthClientModel.class.isInstance(clientModel) && !forceRetrieval) { if (OAuthClientModel.class.isInstance(clientModel) && !forceRetrieval) {
return corsResponse(Flows.forms(this.session, this.realmModel, clientModel, this.uriInfo) return corsResponse(Flows.forms(this.session, this.realmModel, clientModel, this.uriInfo)
.setClientSessionCode(authManager.extractAuthorizationHeaderToken(this.request.getHttpHeaders())) .setClientSessionCode(authManager.extractAuthorizationHeaderToken(this.request.getHttpHeaders()))
.setAccessRequest("Your information from " + providerId + " identity provider.") .setAccessRequest("Your information from " + providerId + " identity provider.").setClient(clientModel)
.setClient(clientModel) .setUriInfo(this.uriInfo).setActionUri(this.uriInfo.getRequestUri()).createOAuthGrant(), clientModel);
.setUriInfo(this.uriInfo)
.setActionUri(this.uriInfo.getRequestUri())
.createOAuthGrant(), clientModel);
} }
IdentityProvider identityProvider = getIdentityProvider(providerId); IdentityProvider identityProvider = getIdentityProvider(providerId);
IdentityProviderModel identityProviderConfig = getIdentityProviderConfig(providerId); IdentityProviderModel identityProviderConfig = getIdentityProviderConfig(providerId);
if (identityProviderConfig.isStoreToken()) { if (identityProviderConfig.isStoreToken()) {
FederatedIdentityModel identity = this.session.users().getFederatedIdentity(authResult.getUser(), providerId, this.realmModel); FederatedIdentityModel identity = this.session.users().getFederatedIdentity(authResult.getUser(), providerId,
this.realmModel);
if (identity == null) { if (identity == null) {
return corsResponse(badRequest("User [" + authResult.getUser().getId() + "] is not associated with identity provider [" + providerId + "]."), clientModel); return corsResponse(badRequest("User [" + authResult.getUser().getId()
+ "] is not associated with identity provider [" + providerId + "]."), clientModel);
} }
this.event.success(); this.event.success();
@ -215,14 +221,16 @@ public class IdentityBrokerService {
return corsResponse(identityProvider.retrieveToken(identity), clientModel); return corsResponse(identityProvider.retrieveToken(identity), clientModel);
} }
return corsResponse(badRequest("Identity Provider [" + providerId + "] does not support this operation."), clientModel); return corsResponse(badRequest("Identity Provider [" + providerId + "] does not support this operation."),
clientModel);
} }
return badRequest("Invalid token."); return badRequest("Invalid token.");
} catch (IdentityBrokerException e) { } catch (IdentityBrokerException e) {
return redirectToErrorPage("Could not obtain token fron identity provider [" + providerId + "].", e); return redirectToErrorPage("Could not obtain token fron identity provider [" + providerId + "].", e);
} catch (Exception e) { } catch (Exception e) {
return redirectToErrorPage("Unexpected error when retrieving token from identity provider [" + providerId + "].", e); return redirectToErrorPage("Unexpected error when retrieving token from identity provider [" + providerId + "].",
e);
} }
} }
@ -259,7 +267,8 @@ public class IdentityBrokerService {
} }
ClientSessionCode clientSessionCode = parseClientSessionCode(relayState, providerId); ClientSessionCode clientSessionCode = parseClientSessionCode(relayState, providerId);
AuthenticationResponse authenticationResponse = identityProvider.handleResponse(createAuthenticationRequest(providerId, clientSessionCode)); AuthenticationResponse authenticationResponse = identityProvider.handleResponse(createAuthenticationRequest(
providerId, clientSessionCode));
Response response = authenticationResponse.getResponse(); Response response = authenticationResponse.getResponse();
if (response != null) { if (response != null) {
@ -287,10 +296,12 @@ public class IdentityBrokerService {
return performLocalAuthentication(identity, clientSessionCode); return performLocalAuthentication(identity, clientSessionCode);
} catch (IdentityBrokerException e) { } catch (IdentityBrokerException e) {
rollback(); rollback();
return redirectToErrorPage("Authentication failed. Could not authenticate with identity provider [" + providerId + "].", e); return redirectToErrorPage("Authentication failed. Could not authenticate with identity provider [" + providerId
+ "].", e);
} catch (Exception e) { } catch (Exception e) {
rollback(); rollback();
return redirectToErrorPage("Unexpected error when handling response from identity provider [" + providerId + "].", e); return redirectToErrorPage(
"Unexpected error when handling response from identity provider [" + providerId + "].", e);
} finally { } finally {
if (this.session.getTransaction().isActive()) { if (this.session.getTransaction().isActive()) {
this.session.getTransaction().commit(); this.session.getTransaction().commit();
@ -305,8 +316,7 @@ public class IdentityBrokerService {
FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, updatedIdentity.getId(), FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, updatedIdentity.getId(),
updatedIdentity.getUsername(), updatedIdentity.getToken()); updatedIdentity.getUsername(), updatedIdentity.getToken());
this.event.event(EventType.IDENTITY_PROVIDER_LOGIN) this.event.event(EventType.IDENTITY_PROVIDER_LOGIN).detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.IDENTITY_PROVIDER_IDENTITY, updatedIdentity.getUsername()); .detail(Details.IDENTITY_PROVIDER_IDENTITY, updatedIdentity.getUsername());
UserModel federatedUser = this.session.users().getUserByFederatedIdentity(federatedIdentityModel, this.realmModel); UserModel federatedUser = this.session.users().getUserByFederatedIdentity(federatedIdentityModel, this.realmModel);
@ -333,8 +343,8 @@ public class IdentityBrokerService {
updateFederatedIdentity(updatedIdentity, federatedUser); updateFederatedIdentity(updatedIdentity, federatedUser);
UserSessionModel userSession = this.session.sessions() UserSessionModel userSession = this.session.sessions().createUserSession(this.realmModel, federatedUser,
.createUserSession(this.realmModel, federatedUser, federatedUser.getUsername(), this.clientConnection.getRemoteAddr(), "broker", false); federatedUser.getUsername(), this.clientConnection.getRemoteAddr(), "broker", false);
this.event.user(federatedUser); this.event.user(federatedUser);
this.event.session(userSession); this.event.session(userSession);
@ -345,21 +355,24 @@ public class IdentityBrokerService {
LOGGER.debugf("Performing local authentication for user [%s].", federatedUser); LOGGER.debugf("Performing local authentication for user [%s].", federatedUser);
} }
return AuthenticationManager.nextActionAfterAuthentication(this.session, userSession, clientSession, this.clientConnection, this.request, return AuthenticationManager.nextActionAfterAuthentication(this.session, userSession, clientSession,
this.uriInfo, event); this.clientConnection, this.request, this.uriInfo, event);
} }
private Response performAccountLinking(ClientSessionModel clientSession, String providerId, FederatedIdentityModel federatedIdentityModel, UserModel federatedUser) { private Response performAccountLinking(ClientSessionModel clientSession, String providerId,
FederatedIdentityModel federatedIdentityModel, UserModel federatedUser) {
this.event.event(EventType.IDENTITY_PROVIDER_ACCCOUNT_LINKING); this.event.event(EventType.IDENTITY_PROVIDER_ACCCOUNT_LINKING);
if (federatedUser != null) { if (federatedUser != null) {
return redirectToErrorPage("The identity returned by the identity provider [" + providerId + "] is already linked to other user."); return redirectToErrorPage("The identity returned by the identity provider [" + providerId
+ "] is already linked to other user.");
} }
UserModel authenticatedUser = clientSession.getUserSession().getUser(); UserModel authenticatedUser = clientSession.getUserSession().getUser();
if (isDebugEnabled()) { if (isDebugEnabled()) {
LOGGER.debugf("Linking account [%s] from identity provider [%s] to user [%s].", federatedIdentityModel, providerId, authenticatedUser); LOGGER.debugf("Linking account [%s] from identity provider [%s] to user [%s].", federatedIdentityModel,
providerId, authenticatedUser);
} }
if (!authenticatedUser.isEnabled()) { if (!authenticatedUser.isEnabled()) {
@ -367,7 +380,8 @@ public class IdentityBrokerService {
return redirectToErrorPage("User is disabled."); return redirectToErrorPage("User is disabled.");
} }
if (!authenticatedUser.hasRole(this.realmModel.getApplicationByName(ACCOUNT_MANAGEMENT_APP).getRole(MANAGE_ACCOUNT))) { if (!authenticatedUser
.hasRole(this.realmModel.getApplicationByName(ACCOUNT_MANAGEMENT_APP).getRole(MANAGE_ACCOUNT))) {
fireErrorEvent(Errors.NOT_ALLOWED); fireErrorEvent(Errors.NOT_ALLOWED);
return redirectToErrorPage("Insufficient permissions to link identities."); return redirectToErrorPage("Insufficient permissions to link identities.");
} }
@ -380,14 +394,16 @@ public class IdentityBrokerService {
} }
private void updateFederatedIdentity(FederatedIdentity updatedIdentity, UserModel federatedUser) { private void updateFederatedIdentity(FederatedIdentity updatedIdentity, UserModel federatedUser) {
FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(federatedUser, updatedIdentity.getIdentityProviderId(), this.realmModel); FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(federatedUser,
updatedIdentity.getIdentityProviderId(), this.realmModel);
federatedIdentityModel.setToken(updatedIdentity.getToken()); federatedIdentityModel.setToken(updatedIdentity.getToken());
this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, federatedIdentityModel); this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, federatedIdentityModel);
if (isDebugEnabled()) { if (isDebugEnabled()) {
LOGGER.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, updatedIdentity.getIdentityProviderId()); LOGGER.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser,
updatedIdentity.getIdentityProviderId());
} }
} }
@ -431,11 +447,13 @@ public class IdentityBrokerService {
relayState = clientSessionCode.getCode(); relayState = clientSessionCode.getCode();
} }
return new AuthenticationRequest(this.session, this.realmModel, clientSession, this.request, this.uriInfo, relayState, getRedirectUri(providerId)); return new AuthenticationRequest(this.session, this.realmModel, clientSession, this.request, this.uriInfo,
relayState, getRedirectUri(providerId));
} }
private String getRedirectUri(String providerId) { private String getRedirectUri(String providerId) {
return Urls.identityProviderAuthnResponse(this.uriInfo.getBaseUri(), providerId, this.realmModel.getName()).toString(); return Urls.identityProviderAuthnResponse(this.uriInfo.getBaseUri(), providerId, this.realmModel.getName())
.toString();
} }
private Response redirectToErrorPage(String message) { private Response redirectToErrorPage(String message) {
@ -460,9 +478,7 @@ public class IdentityBrokerService {
fireErrorEvent(message); fireErrorEvent(message);
return Flows.forms(this.session, this.realmModel, clientCode.getClientSession().getClient(), this.uriInfo) return Flows.forms(this.session, this.realmModel, clientCode.getClientSession().getClient(), this.uriInfo)
.setClientSessionCode(clientCode.getCode()) .setClientSessionCode(clientCode.getCode()).setError(message).createLogin();
.setError(message)
.createLogin();
} }
private Response badRequest(String message) { private Response badRequest(String message) {
@ -519,13 +535,14 @@ public class IdentityBrokerService {
} }
if (!clientModel.hasIdentityProvider(providerId)) { if (!clientModel.hasIdentityProvider(providerId)) {
throw new IdentityBrokerException("Client [" + clientModel.getClientId() + "] not authorized to authenticate with identity provider [" + providerId + "]."); throw new IdentityBrokerException("Client [" + clientModel.getClientId()
+ "] not authorized to authenticate with identity provider [" + providerId + "].");
} }
} }
private UserModel createUser(FederatedIdentity updatedIdentity) { private UserModel createUser(FederatedIdentity updatedIdentity) {
FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(updatedIdentity.getIdentityProviderId(), updatedIdentity.getId(), FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(updatedIdentity.getIdentityProviderId(),
updatedIdentity.getUsername(), updatedIdentity.getToken()); updatedIdentity.getId(), updatedIdentity.getUsername(), updatedIdentity.getToken());
// Check if no user already exists with this username or email // Check if no user already exists with this username or email
UserModel existingUser = null; UserModel existingUser = null;
@ -538,7 +555,18 @@ public class IdentityBrokerService {
throw new IdentityBrokerException("federatedIdentityEmailExists"); throw new IdentityBrokerException("federatedIdentityEmailExists");
} }
existingUser = this.session.users().getUserByUsername(updatedIdentity.getUsername(), this.realmModel); String username = updatedIdentity.getUsername();
if (this.realmModel.isRegistrationEmailAsUsername()) {
username = updatedIdentity.getEmail();
if (username == null) {
fireErrorEvent(Errors.FEDERATED_IDENTITY_REGISTRATION_EMAIL_MISSING);
throw new IdentityBrokerException("federatedIdentityRegistrationEmailMissing");
// TODO KEYCLOAK-1053 (ask user to enter email address) should be implemented instead of plain exception as
// better solution for this case
}
}
existingUser = this.session.users().getUserByUsername(username, this.realmModel);
if (existingUser != null) { if (existingUser != null) {
fireErrorEvent(Errors.FEDERATED_IDENTITY_USERNAME_EXISTS); fireErrorEvent(Errors.FEDERATED_IDENTITY_USERNAME_EXISTS);
@ -549,7 +577,7 @@ public class IdentityBrokerService {
LOGGER.debugf("Creating account from identity [%s].", federatedIdentityModel); LOGGER.debugf("Creating account from identity [%s].", federatedIdentityModel);
} }
UserModel federatedUser = this.session.users().addUser(this.realmModel, updatedIdentity.getUsername()); UserModel federatedUser = this.session.users().addUser(this.realmModel, username);
if (isDebugEnabled()) { if (isDebugEnabled()) {
LOGGER.debugf("Account [%s] created.", federatedUser); LOGGER.debugf("Account [%s] created.", federatedUser);
@ -564,8 +592,7 @@ public class IdentityBrokerService {
this.event.clone().user(federatedUser).event(EventType.REGISTER) this.event.clone().user(federatedUser).event(EventType.REGISTER)
.detail(Details.IDENTITY_PROVIDER, federatedIdentityModel.getIdentityProvider()) .detail(Details.IDENTITY_PROVIDER, federatedIdentityModel.getIdentityProvider())
.detail(Details.IDENTITY_PROVIDER_IDENTITY, updatedIdentity.getUsername()) .detail(Details.IDENTITY_PROVIDER_IDENTITY, updatedIdentity.getUsername()).removeDetail("auth_method")
.removeDetail("auth_method")
.success(); .success();
return federatedUser; return federatedUser;

View file

@ -21,6 +21,25 @@
*/ */
package org.keycloak.services.resources; package org.keycloak.services.resources;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.ClientConnection; import org.keycloak.ClientConnection;
@ -56,24 +75,6 @@ import org.keycloak.services.resources.flows.Urls;
import org.keycloak.services.util.CookieHelper; import org.keycloak.services.util.CookieHelper;
import org.keycloak.services.validation.Validation; import org.keycloak.services.validation.Validation;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/** /**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/ */
@ -150,7 +151,6 @@ public class LoginActionsService {
} }
} }
private class Checks { private class Checks {
ClientSessionCode clientCode; ClientSessionCode clientCode;
Response response; Response response;
@ -160,19 +160,22 @@ 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, "Invalid code, please login again through your application."); response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"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, ClientSessionModel.Action alternativeRequiredAction) { boolean check(String code, ClientSessionModel.Action requiredAction,
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, "Invalid code, please login again through your application."); response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Invalid code, please login again through your application.");
return false; return false;
} else { } else {
return true; return true;
@ -193,7 +196,8 @@ 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, "Unknown code, please login again through your application."); response = Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Unknown code, please login again through your application.");
return false; return false;
} }
return true; return true;
@ -224,8 +228,8 @@ public class LoginActionsService {
clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE); clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE);
} }
LoginFormsProvider forms = Flows.forms(session, realm, clientSession.getClient(), uriInfo) LoginFormsProvider forms = Flows.forms(session, realm, clientSession.getClient(), uriInfo).setClientSessionCode(
.setClientSessionCode(clientSessionCode.getCode()); clientSessionCode.getCode());
return forms.createLogin(); return forms.createLogin();
} }
@ -253,12 +257,10 @@ public class LoginActionsService {
ClientSessionCode clientSessionCode = checks.clientCode; ClientSessionCode clientSessionCode = checks.clientCode;
ClientSessionModel clientSession = clientSessionCode.getClientSession(); ClientSessionModel clientSession = clientSessionCode.getClientSession();
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()) .setClientSessionCode(clientSessionCode.getCode()).createRegistration();
.createRegistration();
} }
/** /**
@ -271,8 +273,7 @@ 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, public Response processLogin(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
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);
@ -286,7 +287,8 @@ 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, "Unknown code, please login again through your application."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Unknown code, please login again through your application.");
} }
ClientSessionModel clientSession = clientCode.getClientSession(); ClientSessionModel clientSession = clientCode.getClientSession();
@ -296,8 +298,7 @@ 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()) .setClientSessionCode(clientCode.getCode()).createLogin();
.createLogin();
} }
String username = formData.getFirst(AuthenticationManager.FORM_USERNAME); String username = formData.getFirst(AuthenticationManager.FORM_USERNAME);
@ -305,17 +306,13 @@ 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()) event.client(clientSession.getClient().getClientId()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) .detail(Details.RESPONSE_TYPE, "code").detail(Details.AUTH_METHOD, "form").detail(Details.USERNAME, username);
.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");
} }
ClientModel client = clientSession.getClient(); ClientModel client = clientSession.getClient();
if (client == null) { if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND); event.error(Errors.CLIENT_NOT_FOUND);
@ -329,12 +326,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) protocol.setRealm(realm).setUriInfo(uriInfo);
.setUriInfo(uriInfo);
return protocol.cancelLogin(clientSession); return protocol.cancelLogin(clientSession);
} }
AuthenticationManager.AuthenticationStatus status = authManager.authenticateForm(session, clientConnection, realm, formData); AuthenticationManager.AuthenticationStatus status = authManager.authenticateForm(session, clientConnection, realm,
formData);
if (remember) { if (remember) {
authManager.createRememberMeCookie(realm, username, uriInfo, clientConnection); authManager.createRememberMeCookie(realm, username, uriInfo, clientConnection);
@ -350,45 +347,37 @@ 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, clientConnection.getRemoteAddr(), "form", remember); UserSessionModel userSession = session.sessions().createUserSession(realm, user, username,
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, uriInfo, event); return authManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request,
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) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.ACCOUNT_TEMPORARILY_DISABLED)
.setError(Messages.ACCOUNT_TEMPORARILY_DISABLED) .setFormData(formData).setClientSessionCode(clientCode.getCode()).createLogin();
.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) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.ACCOUNT_DISABLED)
.setError(Messages.ACCOUNT_DISABLED) .setClientSessionCode(clientCode.getCode()).setFormData(formData).createLogin();
.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(realm.getPrivateKey()); String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), user.getId())).rsa256(
realm.getPrivateKey());
formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken); formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);
return Flows.forms(this.session, realm, client, uriInfo) return Flows.forms(this.session, realm, client, uriInfo).setFormData(formData)
.setFormData(formData) .setClientSessionCode(clientCode.getCode()).createLoginTotp();
.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) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER).setFormData(formData)
.setFormData(formData) .setClientSessionCode(clientCode.getCode()).createLogin();
.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) return Flows.forms(this.session, realm, client, uriInfo).setError(Messages.INVALID_USER).setFormData(formData)
.setFormData(formData) .setClientSessionCode(clientCode.getCode()).createLogin();
.setClientSessionCode(clientCode.getCode())
.createLogin();
} }
} }
@ -402,8 +391,7 @@ 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, public Response processRegister(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
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);
@ -421,21 +409,24 @@ 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, "Unknown code, please login again through your application."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"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, "Invalid code, please login again through your application."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Invalid code, please login again through your application.");
} }
String username = formData.getFirst("username"); String username = formData.getFirst("username");
String email = formData.getFirst("email"); String email = formData.getFirst("email");
if (realm.isRegistrationEmailAsUsername()) {
username = email;
formData.putSingle(AuthenticationManager.FORM_USERNAME, username);
}
ClientSessionModel clientSession = clientCode.getClientSession(); ClientSessionModel clientSession = clientCode.getClientSession();
event.client(clientSession.getClient()) event.client(clientSession.getClient()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) .detail(Details.RESPONSE_TYPE, "code").detail(Details.USERNAME, username).detail(Details.EMAIL, email)
.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()) {
@ -453,45 +444,35 @@ public class LoginActionsService {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled.");
} }
List<String> requiredCredentialTypes = new LinkedList<String>(); List<String> requiredCredentialTypes = new LinkedList<String>();
for (RequiredCredentialModel m : realm.getRequiredCredentials()) { for (RequiredCredentialModel m : realm.getRequiredCredentials()) {
requiredCredentialTypes.add(m.getType()); requiredCredentialTypes.add(m.getType());
} }
// Validate here, so user is not created if password doesn't validate to passwordPolicy of current realm // Validate here, so user is not created if password doesn't validate to passwordPolicy of current realm
String error = Validation.validateRegistrationForm(formData, requiredCredentialTypes); String error = Validation.validateRegistrationForm(realm, formData, requiredCredentialTypes);
if (error == null) { if (error == null) {
error = Validation.validatePassword(formData, realm.getPasswordPolicy()); error = Validation.validatePassword(formData, realm.getPasswordPolicy());
} }
if (error != null) { if (error != null) {
event.error(Errors.INVALID_REGISTRATION); event.error(Errors.INVALID_REGISTRATION);
return Flows.forms(session, realm, client, uriInfo) return Flows.forms(session, realm, client, uriInfo).setError(error).setFormData(formData)
.setError(error) .setClientSessionCode(clientCode.getCode()).createRegistration();
.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) return Flows.forms(session, realm, client, uriInfo).setError(Messages.USERNAME_EXISTS).setFormData(formData)
.setError(Messages.USERNAME_EXISTS) .setClientSessionCode(clientCode.getCode()).createRegistration();
.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) return Flows.forms(session, realm, client, uriInfo).setError(Messages.EMAIL_EXISTS).setFormData(formData)
.setError(Messages.EMAIL_EXISTS) .setClientSessionCode(clientCode.getCode()).createRegistration();
.setFormData(formData)
.setClientSessionCode(clientCode.getCode())
.createRegistration();
} }
UserModel user = session.users().addUser(realm, username); UserModel user = session.users().addUser(realm, username);
@ -519,10 +500,8 @@ 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) return Flows.forms(session, realm, client, uriInfo).setError(passwordUpdateError)
.setError(passwordUpdateError) .setClientSessionCode(clientCode.getCode()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
.setClientSessionCode(clientCode.getCode())
.createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
} }
} }
@ -546,7 +525,6 @@ public class LoginActionsService {
public Response processConsent(final MultivaluedMap<String, String> formData) { public Response processConsent(final MultivaluedMap<String, String> formData) {
event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code"); event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code");
if (!checkSsl()) { if (!checkSsl()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required"); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required");
} }
@ -563,10 +541,8 @@ public class LoginActionsService {
String redirect = clientSession.getRedirectUri(); String redirect = clientSession.getRedirectUri();
event.client(clientSession.getClient()) event.client(clientSession.getClient()).user(clientSession.getUserSession().getUser())
.user(clientSession.getUserSession().getUser()) .detail(Details.RESPONSE_TYPE, "code").detail(Details.REDIRECT_URI, redirect);
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.REDIRECT_URI, redirect);
UserSessionModel userSession = clientSession.getUserSession(); UserSessionModel userSession = clientSession.getUserSession();
if (userSession != null) { if (userSession != null) {
@ -585,8 +561,7 @@ 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) protocol.setRealm(realm).setUriInfo(uriInfo);
.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);
@ -594,17 +569,14 @@ public class LoginActionsService {
event.success(); event.success();
return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, clientConnection); return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo,
clientConnection);
} }
@Path("profile") @Path("profile")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateProfile(@QueryParam("code") String code, public Response updateProfile(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
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)) {
@ -620,8 +592,7 @@ 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()) .setClientSessionCode(accessCode.getCode()).createResponse(RequiredAction.UPDATE_PROFILE);
.createResponse(RequiredAction.UPDATE_PROFILE);
} }
user.setFirstName(formData.getFirst("firstName")); user.setFirstName(formData.getFirst("firstName"));
@ -638,8 +609,7 @@ 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()) .setClientSessionCode(accessCode.getCode()).createResponse(RequiredAction.UPDATE_PROFILE);
.createResponse(RequiredAction.UPDATE_PROFILE);
} }
user.setEmail(email); user.setEmail(email);
@ -650,7 +620,8 @@ 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).detail(Details.UPDATED_EMAIL, email).success(); event.clone().event(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, oldEmail)
.detail(Details.UPDATED_EMAIL, email).success();
} }
return redirectOauth(user, accessCode, clientSession, userSession); return redirectOauth(user, accessCode, clientSession, userSession);
@ -659,8 +630,7 @@ 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, public Response updateTotp(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
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)) {
@ -678,12 +648,10 @@ 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) return loginForms.setError(Messages.MISSING_TOTP).setClientSessionCode(accessCode.getCode())
.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) return loginForms.setError(Messages.INVALID_TOTP).setClientSessionCode(accessCode.getCode())
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.CONFIGURE_TOTP); .createResponse(RequiredAction.CONFIGURE_TOTP);
} }
@ -704,8 +672,7 @@ public class LoginActionsService {
@Path("password") @Path("password")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updatePassword(@QueryParam("code") String code, public Response updatePassword(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
final MultivaluedMap<String, String> formData) {
event.event(EventType.UPDATE_PASSWORD); event.event(EventType.UPDATE_PASSWORD);
Checks checks = new Checks(); Checks checks = new Checks();
if (!checks.check(code, ClientSessionModel.Action.UPDATE_PASSWORD, ClientSessionModel.Action.RECOVER_PASSWORD)) { if (!checks.check(code, ClientSessionModel.Action.UPDATE_PASSWORD, ClientSessionModel.Action.RECOVER_PASSWORD)) {
@ -723,20 +690,17 @@ 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) return loginForms.setError(Messages.MISSING_PASSWORD).setClientSessionCode(accessCode.getCode())
.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) return loginForms.setError(Messages.NOTMATCH_PASSWORD).setClientSessionCode(accessCode.getCode())
.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()) return loginForms.setError(ape.getMessage()).setClientSessionCode(accessCode.getCode())
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} }
@ -747,7 +711,8 @@ 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").createInfoPage(); return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("passwordUpdated")
.createInfoPage();
} }
} }
@ -756,7 +721,6 @@ public class LoginActionsService {
return redirectOauth(user, accessCode, clientSession, userSession); return redirectOauth(user, accessCode, clientSession, userSession);
} }
@Path("email-verification") @Path("email-verification")
@GET @GET
public Response emailVerification(@QueryParam("code") String code, @QueryParam("key") String key) { public Response emailVerification(@QueryParam("code") String code, @QueryParam("key") String key) {
@ -779,7 +743,8 @@ 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").createInfoPage(); return Flows.forms(session, realm, clientSession.getClient(), uriInfo).setSuccess("emailVerified")
.createInfoPage();
} }
event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN); event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN);
@ -797,10 +762,8 @@ public class LoginActionsService {
createActionCookie(realm, uriInfo, clientConnection, userSession.getId()); createActionCookie(realm, uriInfo, clientConnection, userSession.getId());
return Flows.forms(session, realm, null, uriInfo) return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(accessCode.getCode())
.setClientSessionCode(accessCode.getCode()) .setUser(userSession.getUser()).createResponse(RequiredAction.VERIFY_EMAIL);
.setUser(userSession.getUser())
.createResponse(RequiredAction.VERIFY_EMAIL);
} }
} }
@ -814,21 +777,17 @@ public class LoginActionsService {
return checks.response; return checks.response;
} }
ClientSessionCode accessCode = checks.clientCode; ClientSessionCode accessCode = checks.clientCode;
return Flows.forms(session, realm, null, uriInfo) return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(accessCode.getCode())
.setClientSessionCode(accessCode.getCode())
.createResponse(RequiredAction.UPDATE_PASSWORD); .createResponse(RequiredAction.UPDATE_PASSWORD);
} else { } else {
return Flows.forms(session, realm, null, uriInfo) return Flows.forms(session, realm, null, uriInfo).setClientSessionCode(code).createPasswordReset();
.setClientSessionCode(code)
.createPasswordReset();
} }
} }
@Path("password-reset") @Path("password-reset")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendPasswordReset(@QueryParam("code") String code, public Response sendPasswordReset(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) {
final MultivaluedMap<String, String> formData) {
event.event(EventType.SEND_RESET_PASSWORD); event.event(EventType.SEND_RESET_PASSWORD);
if (!checkSsl()) { if (!checkSsl()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required"); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required");
@ -840,7 +799,8 @@ 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, "Unknown code, please login again through your application."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Unknown code, please login again through your application.");
} }
ClientSessionModel clientSession = accessCode.getClientSession(); ClientSessionModel clientSession = accessCode.getClientSession();
@ -848,19 +808,14 @@ public class LoginActionsService {
ClientModel client = clientSession.getClient(); ClientModel client = clientSession.getClient();
if (client == null) { if (client == null) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown login requester.");
"Unknown login requester.");
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled.");
"Login requester not enabled.");
} }
event.client(client.getClientId()) event.client(client.getClientId()).detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri()) .detail(Details.RESPONSE_TYPE, "code").detail(Details.AUTH_METHOD, "form").detail(Details.USERNAME, username);
.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("@")) {
@ -869,15 +824,15 @@ public class LoginActionsService {
if (user == null) { if (user == null) {
event.error(Errors.USER_NOT_FOUND); event.error(Errors.USER_NOT_FOUND);
} else if(!user.isEnabled()) { } else if (!user.isEnabled()) {
event.user(user).error(Errors.USER_DISABLED); event.user(user).error(Errors.USER_DISABLED);
} } else if (user.getEmail() == null || user.getEmail().trim().length() == 0) {
else if(user.getEmail() == null || user.getEmail().trim().length() == 0) {
event.user(user).error(Errors.INVALID_EMAIL); event.user(user).error(Errors.INVALID_EMAIL);
} else{ } else {
event.user(user); event.user(user);
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false); UserSessionModel userSession = session.sessions().createUserSession(realm, user, username,
clientConnection.getRemoteAddr(), "form", false);
event.session(userSession); event.session(userSession);
TokenManager.attachClientSession(userSession, clientSession); TokenManager.attachClientSession(userSession, clientSession);
@ -897,37 +852,39 @@ 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()) .setClientSessionCode(accessCode.getCode()).createErrorPage();
.createErrorPage();
} }
createActionCookie(realm, uriInfo, clientConnection, userSession.getId()); createActionCookie(realm, uriInfo, clientConnection, userSession.getId());
} }
return Flows.forms(session, realm, client, uriInfo).setSuccess("emailSent").setClientSessionCode(accessCode.getCode()).createPasswordReset(); return Flows.forms(session, realm, client, uriInfo).setSuccess("emailSent")
.setClientSessionCode(accessCode.getCode()).createPasswordReset();
} }
private String getActionCookie() { private String getActionCookie() {
Cookie cookie = headers.getCookies().get(ACTION_COOKIE); Cookie cookie = headers.getCookies().get(ACTION_COOKIE);
AuthenticationManager.expireCookie(realm, ACTION_COOKIE, AuthenticationManager.getRealmCookiePath(realm, uriInfo), realm.getSslRequired().isRequired(clientConnection), clientConnection); AuthenticationManager.expireCookie(realm, ACTION_COOKIE, AuthenticationManager.getRealmCookiePath(realm, uriInfo),
realm.getSslRequired().isRequired(clientConnection), clientConnection);
return cookie != null ? cookie.getValue() : null; return cookie != null ? cookie.getValue() : null;
} }
public static void createActionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection clientConnection, String sessionId) { public static void createActionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection clientConnection,
CookieHelper.addCookie(ACTION_COOKIE, sessionId, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null, null, -1, realm.getSslRequired().isRequired(clientConnection), true); String sessionId) {
CookieHelper.addCookie(ACTION_COOKIE, sessionId, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null,
null, -1, realm.getSslRequired().isRequired(clientConnection), true);
} }
private Response redirectOauth(UserModel user, ClientSessionCode accessCode, ClientSessionModel clientSession, UserSessionModel userSession) { private Response redirectOauth(UserModel user, ClientSessionCode accessCode, ClientSessionModel clientSession,
return AuthenticationManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, uriInfo, event); UserSessionModel userSession) {
return AuthenticationManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection,
request, uriInfo, event);
} }
private void initEvent(ClientSessionModel clientSession) { private void initEvent(ClientSessionModel clientSession) {
event.event(EventType.LOGIN).client(clientSession.getClient()) event.event(EventType.LOGIN).client(clientSession.getClient()).user(clientSession.getUserSession().getUser())
.user(clientSession.getUserSession().getUser()) .session(clientSession.getUserSession().getId()).detail(Details.CODE_ID, clientSession.getId())
.session(clientSession.getUserSession().getId()) .detail(Details.REDIRECT_URI, clientSession.getRedirectUri()).detail(Details.RESPONSE_TYPE, "code");
.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

@ -1,19 +1,23 @@
package org.keycloak.services.validation; package org.keycloak.services.validation;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.messages.Messages;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.ws.rs.core.MultivaluedMap;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.CredentialRepresentation;
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.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*"); private static final Pattern EMAIL_PATTERN = Pattern
.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*");
public static String validateRegistrationForm(MultivaluedMap<String, String> formData, List<String> requiredCredentialTypes) { public static String validateRegistrationForm(RealmModel realm, MultivaluedMap<String, String> formData,
List<String> requiredCredentialTypes) {
if (isEmpty(formData.getFirst("firstName"))) { if (isEmpty(formData.getFirst("firstName"))) {
return Messages.MISSING_FIRST_NAME; return Messages.MISSING_FIRST_NAME;
} }
@ -30,7 +34,7 @@ public class Validation {
return Messages.INVALID_EMAIL; return Messages.INVALID_EMAIL;
} }
if (isEmpty(formData.getFirst("username"))) { if (!realm.isRegistrationEmailAsUsername() && isEmpty(formData.getFirst("username"))) {
return Messages.MISSING_USERNAME; return Messages.MISSING_USERNAME;
} }
@ -79,5 +83,4 @@ public class Validation {
return EMAIL_PATTERN.matcher(email).matches(); return EMAIL_PATTERN.matcher(email).matches();
} }
} }

View file

@ -21,6 +21,21 @@
*/ */
package org.keycloak.testsuite.admin; package org.keycloak.testsuite.admin;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.junit.Assert; import org.junit.Assert;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test; import org.junit.Test;
@ -41,20 +56,6 @@ import org.keycloak.services.resources.admin.AdminRoot;
import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testutils.KeycloakServer; import org.keycloak.testutils.KeycloakServer;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** /**
* Tests Undertow Adapter * Tests Undertow Adapter
* *
@ -78,8 +79,10 @@ 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", false); UserSessionModel userSession = session.sessions().createUserSession(adminRealm, admin, "admin", null, "form",
AccessToken token = tm.createClientAccessToken(session, tm.getAccess(null, adminConsole, admin), adminRealm, adminConsole, admin, userSession, null); false);
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);
@ -101,7 +104,6 @@ public class AdminAPITest {
String realmName = rep.getRealm(); String realmName = rep.getRealm();
WebTarget realmTarget = adminRealms.path(realmName); WebTarget realmTarget = adminRealms.path(realmName);
// create with just name, enabled, and id, just like admin console // create with just name, enabled, and id, just like admin console
RealmRepresentation newRep = new RealmRepresentation(); RealmRepresentation newRep = new RealmRepresentation();
newRep.setRealm(rep.getRealm()); newRep.setRealm(rep.getRealm());
@ -125,7 +127,8 @@ public class AdminAPITest {
WebTarget applicationsTarget = realmTarget.path("applications"); WebTarget applicationsTarget = realmTarget.path("applications");
for (ApplicationRepresentation appRep : rep.getApplications()) { for (ApplicationRepresentation appRep : rep.getApplications()) {
ApplicationRepresentation newApp = new ApplicationRepresentation(); ApplicationRepresentation newApp = new ApplicationRepresentation();
if (appRep.getId() != null) newApp.setId(appRep.getId()); if (appRep.getId() != null)
newApp.setId(appRep.getId());
newApp.setName(appRep.getName()); newApp.setName(appRep.getName());
if (appRep.getSecret() != null) { if (appRep.getSecret() != null) {
newApp.setSecret(appRep.getSecret()); newApp.setSecret(appRep.getSecret());
@ -135,15 +138,16 @@ public class AdminAPITest {
appCreateResponse.close(); appCreateResponse.close();
WebTarget appTarget = applicationsTarget.path(appRep.getName()); WebTarget appTarget = applicationsTarget.path(appRep.getName());
CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class); CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class);
if (appRep.getSecret() != null) Assert.assertEquals(appRep.getSecret(), cred.getValue()); if (appRep.getSecret() != null)
CredentialRepresentation newCred = appTarget.path("client-secret").request().post(null, CredentialRepresentation.class); Assert.assertEquals(appRep.getSecret(), cred.getValue());
CredentialRepresentation newCred = appTarget.path("client-secret").request()
.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));
Assert.assertEquals(204, appUpdateResponse.getStatus()); Assert.assertEquals(204, appUpdateResponse.getStatus());
appUpdateResponse.close(); appUpdateResponse.close();
ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class); ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class);
checkAppUpdate(appRep, storedApp); checkAppUpdate(appRep, storedApp);
@ -162,14 +166,22 @@ public class AdminAPITest {
} }
protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) { protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) {
if (appRep.getName() != null) Assert.assertEquals(appRep.getName(), storedApp.getName()); if (appRep.getName() != null)
if (appRep.isEnabled() != null) Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled()); Assert.assertEquals(appRep.getName(), storedApp.getName());
if (appRep.isBearerOnly() != null) Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly()); if (appRep.isEnabled() != null)
if (appRep.isPublicClient() != null) Assert.assertEquals(appRep.isPublicClient(), storedApp.isPublicClient()); Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled());
if (appRep.isFullScopeAllowed() != null) Assert.assertEquals(appRep.isFullScopeAllowed(), storedApp.isFullScopeAllowed()); if (appRep.isBearerOnly() != null)
if (appRep.getAdminUrl() != null) Assert.assertEquals(appRep.getAdminUrl(), storedApp.getAdminUrl()); Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly());
if (appRep.getBaseUrl() != null) Assert.assertEquals(appRep.getBaseUrl(), storedApp.getBaseUrl()); if (appRep.isPublicClient() != null)
if (appRep.isSurrogateAuthRequired() != null) Assert.assertEquals(appRep.isSurrogateAuthRequired(), storedApp.isSurrogateAuthRequired()); Assert.assertEquals(appRep.isPublicClient(), storedApp.isPublicClient());
if (appRep.isFullScopeAllowed() != null)
Assert.assertEquals(appRep.isFullScopeAllowed(), storedApp.isFullScopeAllowed());
if (appRep.getAdminUrl() != null)
Assert.assertEquals(appRep.getAdminUrl(), storedApp.getAdminUrl());
if (appRep.getBaseUrl() != null)
Assert.assertEquals(appRep.getBaseUrl(), storedApp.getBaseUrl());
if (appRep.isSurrogateAuthRequired() != null)
Assert.assertEquals(appRep.isSurrogateAuthRequired(), storedApp.isSurrogateAuthRequired());
if (appRep.getNotBefore() != null) { if (appRep.getNotBefore() != null) {
Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore()); Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore());
@ -223,39 +235,65 @@ public class AdminAPITest {
if (rep.getRealm() != null) { if (rep.getRealm() != null) {
Assert.assertEquals(rep.getRealm(), storedRealm.getRealm()); Assert.assertEquals(rep.getRealm(), storedRealm.getRealm());
} }
if (rep.isEnabled() != null) Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled()); if (rep.isEnabled() != null)
if (rep.isBruteForceProtected() != null) Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected()); Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled());
if (rep.getMaxFailureWaitSeconds() != null) Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds()); if (rep.isBruteForceProtected() != null)
if (rep.getMinimumQuickLoginWaitSeconds() != null) Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds()); Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected());
if (rep.getWaitIncrementSeconds() != null) Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds()); if (rep.getMaxFailureWaitSeconds() != null)
if (rep.getQuickLoginCheckMilliSeconds() != null) Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds()); Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds()); if (rep.getMinimumQuickLoginWaitSeconds() != null)
if (rep.getFailureFactor() != null) Assert.assertEquals(rep.getFailureFactor(), storedRealm.getFailureFactor()); Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
if (rep.isPasswordCredentialGrantAllowed() != null) Assert.assertEquals(rep.isPasswordCredentialGrantAllowed(), storedRealm.isPasswordCredentialGrantAllowed()); if (rep.getWaitIncrementSeconds() != null)
if (rep.isRegistrationAllowed() != null) Assert.assertEquals(rep.isRegistrationAllowed(), storedRealm.isRegistrationAllowed()); Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
if (rep.isRememberMe() != null) Assert.assertEquals(rep.isRememberMe(), storedRealm.isRememberMe()); if (rep.getQuickLoginCheckMilliSeconds() != null)
if (rep.isVerifyEmail() != null) Assert.assertEquals(rep.isVerifyEmail(), storedRealm.isVerifyEmail()); Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
if (rep.isResetPasswordAllowed() != null) Assert.assertEquals(rep.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed()); if (rep.getMaxDeltaTimeSeconds() != null)
if (rep.getSslRequired() != null) Assert.assertEquals(rep.getSslRequired(), storedRealm.getSslRequired()); Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
if (rep.getAccessCodeLifespan() != null) Assert.assertEquals(rep.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan()); if (rep.getFailureFactor() != null)
Assert.assertEquals(rep.getFailureFactor(), storedRealm.getFailureFactor());
if (rep.isPasswordCredentialGrantAllowed() != null)
Assert.assertEquals(rep.isPasswordCredentialGrantAllowed(), storedRealm.isPasswordCredentialGrantAllowed());
if (rep.isRegistrationAllowed() != null)
Assert.assertEquals(rep.isRegistrationAllowed(), storedRealm.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
Assert.assertEquals(rep.isRegistrationEmailAsUsername(), storedRealm.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null)
Assert.assertEquals(rep.isRememberMe(), storedRealm.isRememberMe());
if (rep.isVerifyEmail() != null)
Assert.assertEquals(rep.isVerifyEmail(), storedRealm.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null)
Assert.assertEquals(rep.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed());
if (rep.getSslRequired() != null)
Assert.assertEquals(rep.getSslRequired(), storedRealm.getSslRequired());
if (rep.getAccessCodeLifespan() != null)
Assert.assertEquals(rep.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null) if (rep.getAccessCodeLifespanUserAction() != null)
Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction()); Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
if (rep.getNotBefore() != null) Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore()); if (rep.getNotBefore() != null)
if (rep.getAccessTokenLifespan() != null) Assert.assertEquals(rep.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan()); Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore());
if (rep.getSsoSessionIdleTimeout() != null) Assert.assertEquals(rep.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout()); if (rep.getAccessTokenLifespan() != null)
if (rep.getSsoSessionMaxLifespan() != null) Assert.assertEquals(rep.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan()); Assert.assertEquals(rep.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan());
if (rep.getSsoSessionIdleTimeout() != null)
Assert.assertEquals(rep.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout());
if (rep.getSsoSessionMaxLifespan() != null)
Assert.assertEquals(rep.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan());
if (rep.getRequiredCredentials() != null) { if (rep.getRequiredCredentials() != null) {
Assert.assertNotNull(storedRealm.getRequiredCredentials()); Assert.assertNotNull(storedRealm.getRequiredCredentials());
for (String cred : rep.getRequiredCredentials()) { for (String cred : rep.getRequiredCredentials()) {
Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred)); Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred));
} }
} }
if (rep.getLoginTheme() != null) Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme()); if (rep.getLoginTheme() != null)
if (rep.getAccountTheme() != null) Assert.assertEquals(rep.getAccountTheme(), storedRealm.getAccountTheme()); Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme());
if (rep.getAdminTheme() != null) Assert.assertEquals(rep.getAdminTheme(), storedRealm.getAdminTheme()); if (rep.getAccountTheme() != null)
if (rep.getEmailTheme() != null) Assert.assertEquals(rep.getEmailTheme(), storedRealm.getEmailTheme()); Assert.assertEquals(rep.getAccountTheme(), storedRealm.getAccountTheme());
if (rep.getAdminTheme() != null)
Assert.assertEquals(rep.getAdminTheme(), storedRealm.getAdminTheme());
if (rep.getEmailTheme() != null)
Assert.assertEquals(rep.getEmailTheme(), storedRealm.getEmailTheme());
if (rep.getPasswordPolicy() != null) Assert.assertEquals(rep.getPasswordPolicy(), storedRealm.getPasswordPolicy()); if (rep.getPasswordPolicy() != null)
Assert.assertEquals(rep.getPasswordPolicy(), storedRealm.getPasswordPolicy());
if (rep.getDefaultRoles() != null) { if (rep.getDefaultRoles() != null) {
Assert.assertNotNull(storedRealm.getDefaultRoles()); Assert.assertNotNull(storedRealm.getDefaultRoles());

View file

@ -1,5 +1,7 @@
package org.keycloak.testsuite.model; package org.keycloak.testsuite.model;
import java.util.HashMap;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
@ -9,14 +11,13 @@ import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
import java.util.HashMap;
public class ModelTest extends AbstractModelTest { public class ModelTest extends AbstractModelTest {
@Test @Test
public void importExportRealm() { public void importExportRealm() {
RealmModel realm = realmManager.createRealm("original"); RealmModel realm = realmManager.createRealm("original");
realm.setRegistrationAllowed(true); realm.setRegistrationAllowed(true);
realm.setRegistrationEmailAsUsername(true);
realm.setResetPasswordAllowed(true); realm.setResetPasswordAllowed(true);
realm.setSslRequired(SslRequired.EXTERNAL); realm.setSslRequired(SslRequired.EXTERNAL);
realm.setVerifyEmail(true); realm.setVerifyEmail(true);
@ -27,16 +28,16 @@ public class ModelTest extends AbstractModelTest {
KeycloakModelUtils.generateRealmKeys(realm); KeycloakModelUtils.generateRealmKeys(realm);
realm.addDefaultRole("default-role"); realm.addDefaultRole("default-role");
HashMap<String, String> smtp = new HashMap<String,String>(); HashMap<String, String> smtp = new HashMap<String, String>();
smtp.put("from", "auto@keycloak"); smtp.put("from", "auto@keycloak");
smtp.put("hostname", "localhost"); smtp.put("hostname", "localhost");
realm.setSmtpConfig(smtp); realm.setSmtpConfig(smtp);
HashMap<String, String> social = new HashMap<String,String>(); HashMap<String, String> social = new HashMap<String, String>();
social.put("google.key", "1234"); social.put("google.key", "1234");
social.put("google.secret", "5678"); social.put("google.secret", "5678");
//FIXME: KEYCLOAK-883 // FIXME: KEYCLOAK-883
// realm.setSocialConfig(social); // realm.setSocialConfig(social);
RealmModel persisted = realmManager.getRealm(realm.getId()); RealmModel persisted = realmManager.getRealm(realm.getId());
assertEquals(realm, persisted); assertEquals(realm, persisted);
@ -47,6 +48,7 @@ public class ModelTest extends AbstractModelTest {
public static void assertEquals(RealmModel expected, RealmModel actual) { public static void assertEquals(RealmModel expected, RealmModel actual) {
Assert.assertEquals(expected.isRegistrationAllowed(), actual.isRegistrationAllowed()); Assert.assertEquals(expected.isRegistrationAllowed(), actual.isRegistrationAllowed());
Assert.assertEquals(expected.isRegistrationEmailAsUsername(), actual.isRegistrationEmailAsUsername());
Assert.assertEquals(expected.isResetPasswordAllowed(), actual.isResetPasswordAllowed()); Assert.assertEquals(expected.isResetPasswordAllowed(), actual.isResetPasswordAllowed());
Assert.assertEquals(expected.getSslRequired(), actual.getSslRequired()); Assert.assertEquals(expected.getSslRequired(), actual.getSslRequired());
Assert.assertEquals(expected.isVerifyEmail(), actual.isVerifyEmail()); Assert.assertEquals(expected.isVerifyEmail(), actual.isVerifyEmail());
@ -60,8 +62,8 @@ public class ModelTest extends AbstractModelTest {
Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles()); Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles());
Assert.assertEquals(expected.getSmtpConfig(), actual.getSmtpConfig()); Assert.assertEquals(expected.getSmtpConfig(), actual.getSmtpConfig());
//FIXME: KEYCLOAK-883 // FIXME: KEYCLOAK-883
// Assert.assertEquals(expected.getSocialConfig(), actual.getSocialConfig()); // Assert.assertEquals(expected.getSocialConfig(), actual.getSocialConfig());
} }
private RealmModel importExport(RealmModel src, String copyName) { private RealmModel importExport(RealmModel src, String copyName) {

View file

@ -3,6 +3,7 @@
"enabled": true, "enabled": true,
"sslRequired": "external", "sslRequired": "external",
"registrationAllowed": true, "registrationAllowed": true,
"registrationEmailAsUsername": true,
"resetPasswordAllowed": true, "resetPasswordAllowed": true,
"privateKey": "MIICXAIBAAKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQABAoGAfmO8gVhyBxdqlxmIuglbz8bcjQbhXJLR2EoS8ngTXmN1bo2L90M0mUKSdc7qF10LgETBzqL8jYlQIbt+e6TH8fcEpKCjUlyq0Mf/vVbfZSNaVycY13nTzo27iPyWQHK5NLuJzn1xvxxrUeXI6A2WFpGEBLbHjwpx5WQG9A+2scECQQDvdn9NE75HPTVPxBqsEd2z10TKkl9CZxu10Qby3iQQmWLEJ9LNmy3acvKrE3gMiYNWb6xHPKiIqOR1as7L24aTAkEAtyvQOlCvr5kAjVqrEKXalj0Tzewjweuxc0pskvArTI2Oo070h65GpoIKLc9jf+UA69cRtquwP93aZKtW06U8dQJAF2Y44ks/mK5+eyDqik3koCI08qaC8HYq2wVl7G2QkJ6sbAaILtcvD92ToOvyGyeE0flvmDZxMYlvaZnaQ0lcSQJBAKZU6umJi3/xeEbkJqMfeLclD27XGEFoPeNrmdx0q10Azp4NfJAY+Z8KRyQCR2BEG+oNitBOZ+YXF9KCpH3cdmECQHEigJhYg+ykOvr1aiZUMFT72HU0jnmQe2FVekuG+LJUt2Tm7GtMjTFoGpf0JwrVuZN39fOYAlo+nTixgeW7X8Y=", "privateKey": "MIICXAIBAAKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQABAoGAfmO8gVhyBxdqlxmIuglbz8bcjQbhXJLR2EoS8ngTXmN1bo2L90M0mUKSdc7qF10LgETBzqL8jYlQIbt+e6TH8fcEpKCjUlyq0Mf/vVbfZSNaVycY13nTzo27iPyWQHK5NLuJzn1xvxxrUeXI6A2WFpGEBLbHjwpx5WQG9A+2scECQQDvdn9NE75HPTVPxBqsEd2z10TKkl9CZxu10Qby3iQQmWLEJ9LNmy3acvKrE3gMiYNWb6xHPKiIqOR1as7L24aTAkEAtyvQOlCvr5kAjVqrEKXalj0Tzewjweuxc0pskvArTI2Oo070h65GpoIKLc9jf+UA69cRtquwP93aZKtW06U8dQJAF2Y44ks/mK5+eyDqik3koCI08qaC8HYq2wVl7G2QkJ6sbAaILtcvD92ToOvyGyeE0flvmDZxMYlvaZnaQ0lcSQJBAKZU6umJi3/xeEbkJqMfeLclD27XGEFoPeNrmdx0q10Azp4NfJAY+Z8KRyQCR2BEG+oNitBOZ+YXF9KCpH3cdmECQHEigJhYg+ykOvr1aiZUMFT72HU0jnmQe2FVekuG+LJUt2Tm7GtMjTFoGpf0JwrVuZN39fOYAlo+nTixgeW7X8Y=",
"publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB", "publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",