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

@ -11,497 +11,510 @@ import java.util.Set;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
public class RealmRepresentation { public class RealmRepresentation {
protected String id; protected String id;
protected String realm; protected String realm;
protected Integer notBefore; protected Integer notBefore;
protected Integer accessTokenLifespan; protected Integer accessTokenLifespan;
protected Integer ssoSessionIdleTimeout; protected Integer ssoSessionIdleTimeout;
protected Integer ssoSessionMaxLifespan; protected Integer ssoSessionMaxLifespan;
protected Integer accessCodeLifespan; protected Integer accessCodeLifespan;
protected Integer accessCodeLifespanUserAction; protected Integer accessCodeLifespanUserAction;
protected Integer accessCodeLifespanLogin; protected Integer accessCodeLifespanLogin;
protected Boolean enabled; protected Boolean enabled;
protected String sslRequired; protected String sslRequired;
protected Boolean passwordCredentialGrantAllowed; protected Boolean passwordCredentialGrantAllowed;
protected Boolean registrationAllowed; protected Boolean registrationAllowed;
protected Boolean rememberMe; protected Boolean registrationEmailAsUsername;
protected Boolean verifyEmail; protected Boolean rememberMe;
protected Boolean resetPasswordAllowed; protected Boolean verifyEmail;
protected Boolean resetPasswordAllowed;
protected Boolean userCacheEnabled;
protected Boolean realmCacheEnabled; protected Boolean userCacheEnabled;
protected Boolean realmCacheEnabled;
//--- brute force settings
protected Boolean bruteForceProtected; // --- brute force settings
protected Integer maxFailureWaitSeconds; protected Boolean bruteForceProtected;
protected Integer minimumQuickLoginWaitSeconds; protected Integer maxFailureWaitSeconds;
protected Integer waitIncrementSeconds; protected Integer minimumQuickLoginWaitSeconds;
protected Long quickLoginCheckMilliSeconds; protected Integer waitIncrementSeconds;
protected Integer maxDeltaTimeSeconds; protected Long quickLoginCheckMilliSeconds;
protected Integer failureFactor; protected Integer maxDeltaTimeSeconds;
//--- end brute force settings protected Integer failureFactor;
// --- end brute force settings
protected String privateKey;
protected String publicKey; protected String privateKey;
protected String certificate; protected String publicKey;
protected String codeSecret; protected String certificate;
protected RolesRepresentation roles; protected String codeSecret;
protected List<String> defaultRoles; protected RolesRepresentation roles;
protected Set<String> requiredCredentials; protected List<String> defaultRoles;
protected String passwordPolicy; protected Set<String> requiredCredentials;
protected List<UserRepresentation> users; protected String passwordPolicy;
protected List<ScopeMappingRepresentation> scopeMappings; protected List<UserRepresentation> users;
protected Map<String, List<ScopeMappingRepresentation>> applicationScopeMappings; protected List<ScopeMappingRepresentation> scopeMappings;
protected List<ApplicationRepresentation> applications; protected Map<String, List<ScopeMappingRepresentation>> applicationScopeMappings;
protected List<OAuthClientRepresentation> oauthClients; protected List<ApplicationRepresentation> applications;
protected Map<String, String> browserSecurityHeaders; protected List<OAuthClientRepresentation> oauthClients;
protected Map<String, String> smtpServer; protected Map<String, String> browserSecurityHeaders;
protected List<UserFederationProviderRepresentation> userFederationProviders; protected Map<String, String> smtpServer;
protected String loginTheme; protected List<UserFederationProviderRepresentation> userFederationProviders;
protected String accountTheme; protected String loginTheme;
protected String adminTheme; protected String accountTheme;
protected String emailTheme; protected String adminTheme;
protected Boolean eventsEnabled; protected String emailTheme;
protected Long eventsExpiration; protected Boolean eventsEnabled;
protected List<String> eventsListeners; protected Long eventsExpiration;
private List<IdentityProviderRepresentation> identityProviders; protected List<String> eventsListeners;
private List<ProtocolMapperRepresentation> protocolMappers; private List<IdentityProviderRepresentation> identityProviders;
private Boolean identityFederationEnabled; private List<ProtocolMapperRepresentation> protocolMappers;
private Boolean identityFederationEnabled;
public String getId() {
return id; public String getId() {
} return id;
}
public void setId(String id) {
this.id = id; public void setId(String id) {
} this.id = id;
}
public String getRealm() {
return realm; public String getRealm() {
} return realm;
}
public void setRealm(String realm) {
this.realm = realm; public void setRealm(String realm) {
} this.realm = realm;
}
public List<UserRepresentation> getUsers() {
return users; public List<UserRepresentation> getUsers() {
} return users;
}
public List<ApplicationRepresentation> getApplications() {
return applications; public List<ApplicationRepresentation> getApplications() {
} return applications;
}
public ApplicationRepresentation resource(String name) {
ApplicationRepresentation resource = new ApplicationRepresentation(); public ApplicationRepresentation resource(String name) {
if (applications == null) applications = new ArrayList<ApplicationRepresentation>(); ApplicationRepresentation resource = new ApplicationRepresentation();
applications.add(resource); if (applications == null)
resource.setName(name); applications = new ArrayList<ApplicationRepresentation>();
return resource; applications.add(resource);
} resource.setName(name);
return resource;
public void setUsers(List<UserRepresentation> users) { }
this.users = users;
} public void setUsers(List<UserRepresentation> users) {
this.users = users;
public UserRepresentation user(String username) { }
UserRepresentation user = new UserRepresentation();
user.setUsername(username); public UserRepresentation user(String username) {
if (users == null) users = new ArrayList<UserRepresentation>(); UserRepresentation user = new UserRepresentation();
users.add(user); user.setUsername(username);
return user; if (users == null)
} users = new ArrayList<UserRepresentation>();
users.add(user);
public void setApplications(List<ApplicationRepresentation> applications) { return user;
this.applications = applications; }
}
public void setApplications(List<ApplicationRepresentation> applications) {
public Boolean isEnabled() { this.applications = applications;
return enabled; }
}
public Boolean isEnabled() {
public void setEnabled(Boolean enabled) { return enabled;
this.enabled = enabled; }
}
public void setEnabled(Boolean enabled) {
public String getSslRequired() { this.enabled = enabled;
return sslRequired; }
}
public String getSslRequired() {
public void setSslRequired(String sslRequired) { return sslRequired;
this.sslRequired = sslRequired; }
}
public void setSslRequired(String sslRequired) {
public Integer getAccessTokenLifespan() { this.sslRequired = sslRequired;
return accessTokenLifespan; }
}
public Integer getAccessTokenLifespan() {
public void setAccessTokenLifespan(Integer accessTokenLifespan) { return accessTokenLifespan;
this.accessTokenLifespan = accessTokenLifespan; }
}
public void setAccessTokenLifespan(Integer accessTokenLifespan) {
public Integer getSsoSessionIdleTimeout() { this.accessTokenLifespan = accessTokenLifespan;
return ssoSessionIdleTimeout; }
}
public Integer getSsoSessionIdleTimeout() {
public void setSsoSessionIdleTimeout(Integer ssoSessionIdleTimeout) { return ssoSessionIdleTimeout;
this.ssoSessionIdleTimeout = ssoSessionIdleTimeout; }
}
public void setSsoSessionIdleTimeout(Integer ssoSessionIdleTimeout) {
public Integer getSsoSessionMaxLifespan() { this.ssoSessionIdleTimeout = ssoSessionIdleTimeout;
return ssoSessionMaxLifespan; }
}
public Integer getSsoSessionMaxLifespan() {
public void setSsoSessionMaxLifespan(Integer ssoSessionMaxLifespan) { return ssoSessionMaxLifespan;
this.ssoSessionMaxLifespan = ssoSessionMaxLifespan; }
}
public void setSsoSessionMaxLifespan(Integer ssoSessionMaxLifespan) {
public List<ScopeMappingRepresentation> getScopeMappings() { this.ssoSessionMaxLifespan = ssoSessionMaxLifespan;
return scopeMappings; }
}
public List<ScopeMappingRepresentation> getScopeMappings() {
public ScopeMappingRepresentation scopeMapping(String username) { return scopeMappings;
ScopeMappingRepresentation mapping = new ScopeMappingRepresentation(); }
mapping.setClient(username);
if (scopeMappings == null) scopeMappings = new ArrayList<ScopeMappingRepresentation>(); public ScopeMappingRepresentation scopeMapping(String username) {
scopeMappings.add(mapping); ScopeMappingRepresentation mapping = new ScopeMappingRepresentation();
return mapping; mapping.setClient(username);
} if (scopeMappings == null)
scopeMappings = new ArrayList<ScopeMappingRepresentation>();
public Set<String> getRequiredCredentials() { scopeMappings.add(mapping);
return requiredCredentials; return mapping;
} }
public void setRequiredCredentials(Set<String> requiredCredentials) { public Set<String> getRequiredCredentials() {
this.requiredCredentials = requiredCredentials; return requiredCredentials;
} }
public String getPasswordPolicy() { public void setRequiredCredentials(Set<String> requiredCredentials) {
return passwordPolicy; this.requiredCredentials = requiredCredentials;
} }
public void setPasswordPolicy(String passwordPolicy) { public String getPasswordPolicy() {
this.passwordPolicy = passwordPolicy; return passwordPolicy;
} }
public Integer getAccessCodeLifespan() { public void setPasswordPolicy(String passwordPolicy) {
return accessCodeLifespan; this.passwordPolicy = passwordPolicy;
} }
public void setAccessCodeLifespan(Integer accessCodeLifespan) { public Integer getAccessCodeLifespan() {
this.accessCodeLifespan = accessCodeLifespan; return accessCodeLifespan;
} }
public Integer getAccessCodeLifespanUserAction() { public void setAccessCodeLifespan(Integer accessCodeLifespan) {
return accessCodeLifespanUserAction; this.accessCodeLifespan = accessCodeLifespan;
} }
public void setAccessCodeLifespanUserAction(Integer accessCodeLifespanUserAction) { public Integer getAccessCodeLifespanUserAction() {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; return accessCodeLifespanUserAction;
} }
public Integer getAccessCodeLifespanLogin() { public void setAccessCodeLifespanUserAction(Integer accessCodeLifespanUserAction) {
return accessCodeLifespanLogin; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public void setAccessCodeLifespanLogin(Integer accessCodeLifespanLogin) { public Integer getAccessCodeLifespanLogin() {
this.accessCodeLifespanLogin = accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }
public List<String> getDefaultRoles() { public void setAccessCodeLifespanLogin(Integer accessCodeLifespanLogin) {
return defaultRoles; this.accessCodeLifespanLogin = accessCodeLifespanLogin;
} }
public List<String> getDefaultRoles() {
return defaultRoles;
}
public void setDefaultRoles(List<String> defaultRoles) {
this.defaultRoles = defaultRoles;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getCertificate() {
return certificate;
}
public void setCertificate(String certificate) {
this.certificate = certificate;
}
public String getCodeSecret() {
return codeSecret;
}
public void setCodeSecret(String codeSecret) {
this.codeSecret = codeSecret;
}
public Boolean isPasswordCredentialGrantAllowed() {
return passwordCredentialGrantAllowed;
}
public void setPasswordCredentialGrantAllowed(Boolean passwordCredentialGrantAllowed) {
this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed;
}
public Boolean isRegistrationAllowed() {
return registrationAllowed;
}
public void setRegistrationAllowed(Boolean registrationAllowed) {
this.registrationAllowed = registrationAllowed;
}
public void setDefaultRoles(List<String> defaultRoles) { public Boolean isRegistrationEmailAsUsername() {
this.defaultRoles = defaultRoles; return registrationEmailAsUsername;
} }
public String getPrivateKey() { public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
return privateKey; this.registrationEmailAsUsername = registrationEmailAsUsername;
} }
public void setPrivateKey(String privateKey) { public Boolean isRememberMe() {
this.privateKey = privateKey; return rememberMe;
} }
public String getPublicKey() { public void setRememberMe(Boolean rememberMe) {
return publicKey; this.rememberMe = rememberMe;
} }
public void setPublicKey(String publicKey) { public Boolean isRealmCacheEnabled() {
this.publicKey = publicKey; return realmCacheEnabled;
} }
public String getCertificate() { public void setRealmCacheEnabled(Boolean realmCacheEnabled) {
return certificate; this.realmCacheEnabled = realmCacheEnabled;
} }
public void setCertificate(String certificate) { public Boolean isUserCacheEnabled() {
this.certificate = certificate; return userCacheEnabled;
} }
public String getCodeSecret() { public void setUserCacheEnabled(Boolean userCacheEnabled) {
return codeSecret; this.userCacheEnabled = userCacheEnabled;
} }
public void setCodeSecret(String codeSecret) { public Boolean isVerifyEmail() {
this.codeSecret = codeSecret; return verifyEmail;
} }
public Boolean isPasswordCredentialGrantAllowed() { public void setVerifyEmail(Boolean verifyEmail) {
return passwordCredentialGrantAllowed; this.verifyEmail = verifyEmail;
} }
public void setPasswordCredentialGrantAllowed(Boolean passwordCredentialGrantAllowed) { public Boolean isResetPasswordAllowed() {
this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed; return resetPasswordAllowed;
} }
public Boolean isRegistrationAllowed() { public void setResetPasswordAllowed(Boolean resetPassword) {
return registrationAllowed; this.resetPasswordAllowed = resetPassword;
} }
public void setRegistrationAllowed(Boolean registrationAllowed) { public Map<String, String> getBrowserSecurityHeaders() {
this.registrationAllowed = registrationAllowed; return browserSecurityHeaders;
} }
public Boolean isRememberMe() { public void setBrowserSecurityHeaders(Map<String, String> browserSecurityHeaders) {
return rememberMe; this.browserSecurityHeaders = browserSecurityHeaders;
} }
public void setRememberMe(Boolean rememberMe) { public Map<String, String> getSmtpServer() {
this.rememberMe = rememberMe; return smtpServer;
} }
public Boolean isRealmCacheEnabled() { public void setSmtpServer(Map<String, String> smtpServer) {
return realmCacheEnabled; this.smtpServer = smtpServer;
} }
public void setRealmCacheEnabled(Boolean realmCacheEnabled) { public List<OAuthClientRepresentation> getOauthClients() {
this.realmCacheEnabled = realmCacheEnabled; return oauthClients;
} }
public Boolean isUserCacheEnabled() { public void setOauthClients(List<OAuthClientRepresentation> oauthClients) {
return userCacheEnabled; this.oauthClients = oauthClients;
} }
public void setUserCacheEnabled(Boolean userCacheEnabled) { public Map<String, List<ScopeMappingRepresentation>> getApplicationScopeMappings() {
this.userCacheEnabled = userCacheEnabled; return applicationScopeMappings;
} }
public Boolean isVerifyEmail() { public void setApplicationScopeMappings(Map<String, List<ScopeMappingRepresentation>> applicationScopeMappings) {
return verifyEmail; this.applicationScopeMappings = applicationScopeMappings;
} }
public void setVerifyEmail(Boolean verifyEmail) { public RolesRepresentation getRoles() {
this.verifyEmail = verifyEmail; return roles;
} }
public Boolean isResetPasswordAllowed() { public void setRoles(RolesRepresentation roles) {
return resetPasswordAllowed; this.roles = roles;
} }
public void setResetPasswordAllowed(Boolean resetPassword) { public String getLoginTheme() {
this.resetPasswordAllowed = resetPassword; return loginTheme;
} }
public Map<String, String> getBrowserSecurityHeaders() { public void setLoginTheme(String loginTheme) {
return browserSecurityHeaders; this.loginTheme = loginTheme;
} }
public void setBrowserSecurityHeaders(Map<String, String> browserSecurityHeaders) { public String getAccountTheme() {
this.browserSecurityHeaders = browserSecurityHeaders; return accountTheme;
} }
public Map<String, String> getSmtpServer() { public void setAccountTheme(String accountTheme) {
return smtpServer; this.accountTheme = accountTheme;
} }
public void setSmtpServer(Map<String, String> smtpServer) { public String getAdminTheme() {
this.smtpServer = smtpServer; return adminTheme;
} }
public List<OAuthClientRepresentation> getOauthClients() { public void setAdminTheme(String adminTheme) {
return oauthClients; this.adminTheme = adminTheme;
} }
public void setOauthClients(List<OAuthClientRepresentation> oauthClients) { public String getEmailTheme() {
this.oauthClients = oauthClients; return emailTheme;
} }
public Map<String, List<ScopeMappingRepresentation>> getApplicationScopeMappings() { public void setEmailTheme(String emailTheme) {
return applicationScopeMappings; this.emailTheme = emailTheme;
} }
public void setApplicationScopeMappings(Map<String, List<ScopeMappingRepresentation>> applicationScopeMappings) { public Integer getNotBefore() {
this.applicationScopeMappings = applicationScopeMappings; return notBefore;
} }
public RolesRepresentation getRoles() { public void setNotBefore(Integer notBefore) {
return roles; this.notBefore = notBefore;
} }
public void setRoles(RolesRepresentation roles) { public Boolean isBruteForceProtected() {
this.roles = roles; return bruteForceProtected;
} }
public String getLoginTheme() { public void setBruteForceProtected(Boolean bruteForceProtected) {
return loginTheme; this.bruteForceProtected = bruteForceProtected;
} }
public void setLoginTheme(String loginTheme) { public Integer getMaxFailureWaitSeconds() {
this.loginTheme = loginTheme; return maxFailureWaitSeconds;
} }
public String getAccountTheme() { public void setMaxFailureWaitSeconds(Integer maxFailureWaitSeconds) {
return accountTheme; this.maxFailureWaitSeconds = maxFailureWaitSeconds;
} }
public void setAccountTheme(String accountTheme) { public Integer getMinimumQuickLoginWaitSeconds() {
this.accountTheme = accountTheme; return minimumQuickLoginWaitSeconds;
} }
public String getAdminTheme() { public void setMinimumQuickLoginWaitSeconds(Integer minimumQuickLoginWaitSeconds) {
return adminTheme; this.minimumQuickLoginWaitSeconds = minimumQuickLoginWaitSeconds;
} }
public void setAdminTheme(String adminTheme) { public Integer getWaitIncrementSeconds() {
this.adminTheme = adminTheme; return waitIncrementSeconds;
} }
public String getEmailTheme() { public void setWaitIncrementSeconds(Integer waitIncrementSeconds) {
return emailTheme; this.waitIncrementSeconds = waitIncrementSeconds;
} }
public void setEmailTheme(String emailTheme) { public Long getQuickLoginCheckMilliSeconds() {
this.emailTheme = emailTheme; return quickLoginCheckMilliSeconds;
} }
public Integer getNotBefore() { public void setQuickLoginCheckMilliSeconds(Long quickLoginCheckMilliSeconds) {
return notBefore; this.quickLoginCheckMilliSeconds = quickLoginCheckMilliSeconds;
} }
public void setNotBefore(Integer notBefore) { public Integer getMaxDeltaTimeSeconds() {
this.notBefore = notBefore; return maxDeltaTimeSeconds;
} }
public Boolean isBruteForceProtected() { public void setMaxDeltaTimeSeconds(Integer maxDeltaTimeSeconds) {
return bruteForceProtected; this.maxDeltaTimeSeconds = maxDeltaTimeSeconds;
} }
public void setBruteForceProtected(Boolean bruteForceProtected) { public Integer getFailureFactor() {
this.bruteForceProtected = bruteForceProtected; return failureFactor;
} }
public Integer getMaxFailureWaitSeconds() { public void setFailureFactor(Integer failureFactor) {
return maxFailureWaitSeconds; this.failureFactor = failureFactor;
} }
public void setMaxFailureWaitSeconds(Integer maxFailureWaitSeconds) { public Boolean isEventsEnabled() {
this.maxFailureWaitSeconds = maxFailureWaitSeconds; return eventsEnabled;
} }
public Integer getMinimumQuickLoginWaitSeconds() { public void setEventsEnabled(boolean eventsEnabled) {
return minimumQuickLoginWaitSeconds; this.eventsEnabled = eventsEnabled;
} }
public void setMinimumQuickLoginWaitSeconds(Integer minimumQuickLoginWaitSeconds) { public Long getEventsExpiration() {
this.minimumQuickLoginWaitSeconds = minimumQuickLoginWaitSeconds; return eventsExpiration;
} }
public Integer getWaitIncrementSeconds() { public void setEventsExpiration(long eventsExpiration) {
return waitIncrementSeconds; this.eventsExpiration = eventsExpiration;
} }
public void setWaitIncrementSeconds(Integer waitIncrementSeconds) { public List<String> getEventsListeners() {
this.waitIncrementSeconds = waitIncrementSeconds; return eventsListeners;
} }
public Long getQuickLoginCheckMilliSeconds() { public void setEventsListeners(List<String> eventsListeners) {
return quickLoginCheckMilliSeconds; this.eventsListeners = eventsListeners;
} }
public void setQuickLoginCheckMilliSeconds(Long quickLoginCheckMilliSeconds) { public List<UserFederationProviderRepresentation> getUserFederationProviders() {
this.quickLoginCheckMilliSeconds = quickLoginCheckMilliSeconds; return userFederationProviders;
} }
public Integer getMaxDeltaTimeSeconds() { public void setUserFederationProviders(List<UserFederationProviderRepresentation> userFederationProviders) {
return maxDeltaTimeSeconds; this.userFederationProviders = userFederationProviders;
} }
public void setMaxDeltaTimeSeconds(Integer maxDeltaTimeSeconds) { public List<IdentityProviderRepresentation> getIdentityProviders() {
this.maxDeltaTimeSeconds = maxDeltaTimeSeconds; if (this.identityProviders == null) {
} this.identityProviders = new ArrayList<IdentityProviderRepresentation>();
}
return identityProviders;
}
public Integer getFailureFactor() { public void setIdentityProviders(List<IdentityProviderRepresentation> identityProviders) {
return failureFactor; this.identityProviders = identityProviders;
} }
public void setFailureFactor(Integer failureFactor) { public void addIdentityProvider(IdentityProviderRepresentation identityProviderRepresentation) {
this.failureFactor = failureFactor; getIdentityProviders().add(identityProviderRepresentation);
} }
public Boolean isEventsEnabled() { public boolean isIdentityFederationEnabled() {
return eventsEnabled; return !getIdentityProviders().isEmpty();
} }
public void setEventsEnabled(boolean eventsEnabled) { public List<ProtocolMapperRepresentation> getProtocolMappers() {
this.eventsEnabled = eventsEnabled; return protocolMappers;
} }
public Long getEventsExpiration() { public void addProtocolMapper(ProtocolMapperRepresentation rep) {
return eventsExpiration; if (protocolMappers == null)
} protocolMappers = new LinkedList<ProtocolMapperRepresentation>();
protocolMappers.add(rep);
public void setEventsExpiration(long eventsExpiration) { }
this.eventsExpiration = eventsExpiration;
} public void setProtocolMappers(List<ProtocolMapperRepresentation> protocolMappers) {
this.protocolMappers = protocolMappers;
public List<String> getEventsListeners() { }
return eventsListeners;
}
public void setEventsListeners(List<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public List<UserFederationProviderRepresentation> getUserFederationProviders() {
return userFederationProviders;
}
public void setUserFederationProviders(List<UserFederationProviderRepresentation> userFederationProviders) {
this.userFederationProviders = userFederationProviders;
}
public List<IdentityProviderRepresentation> getIdentityProviders() {
if (this.identityProviders == null) {
this.identityProviders = new ArrayList<IdentityProviderRepresentation>();
}
return identityProviders;
}
public void setIdentityProviders(List<IdentityProviderRepresentation> identityProviders) {
this.identityProviders = identityProviders;
}
public void addIdentityProvider(IdentityProviderRepresentation identityProviderRepresentation) {
getIdentityProviders().add(identityProviderRepresentation);
}
public boolean isIdentityFederationEnabled() {
return !getIdentityProviders().isEmpty();
}
public List<ProtocolMapperRepresentation> getProtocolMappers() {
return protocolMappers;
}
public void addProtocolMapper(ProtocolMapperRepresentation rep) {
if (protocolMappers == null) protocolMappers = new LinkedList<ProtocolMapperRepresentation>();
protocolMappers.add(rep);
}
public void setProtocolMappers(List<ProtocolMapperRepresentation> protocolMappers) {
this.protocolMappers = protocolMappers;
}
} }

View file

@ -5,42 +5,43 @@ package org.keycloak.events;
*/ */
public interface Errors { public interface Errors {
String REALM_DISABLED = "realm_disabled"; String REALM_DISABLED = "realm_disabled";
String CLIENT_NOT_FOUND = "client_not_found"; String CLIENT_NOT_FOUND = "client_not_found";
String CLIENT_DISABLED = "client_disabled"; String CLIENT_DISABLED = "client_disabled";
String INVALID_CLIENT_CREDENTIALS = "invalid_client_credentials"; String INVALID_CLIENT_CREDENTIALS = "invalid_client_credentials";
String INVALID_CLIENT = "invalid_client"; String INVALID_CLIENT = "invalid_client";
String USER_NOT_FOUND = "user_not_found"; String USER_NOT_FOUND = "user_not_found";
String USER_DISABLED = "user_disabled"; String USER_DISABLED = "user_disabled";
String USER_TEMPORARILY_DISABLED = "user_temporarily_disabled"; String USER_TEMPORARILY_DISABLED = "user_temporarily_disabled";
String INVALID_USER_CREDENTIALS = "invalid_user_credentials"; String INVALID_USER_CREDENTIALS = "invalid_user_credentials";
String USERNAME_MISSING = "username_missing"; String USERNAME_MISSING = "username_missing";
String USERNAME_IN_USE = "username_in_use"; String USERNAME_IN_USE = "username_in_use";
String EMAIL_IN_USE = "email_in_use"; String EMAIL_IN_USE = "email_in_use";
String INVALID_REDIRECT_URI = "invalid_redirect_uri"; String INVALID_REDIRECT_URI = "invalid_redirect_uri";
String INVALID_CODE = "invalid_code"; String INVALID_CODE = "invalid_code";
String INVALID_TOKEN = "invalid_token"; String INVALID_TOKEN = "invalid_token";
String INVALID_SIGNATURE = "invalid_signature"; String INVALID_SIGNATURE = "invalid_signature";
String INVALID_REGISTRATION = "invalid_registration"; String INVALID_REGISTRATION = "invalid_registration";
String INVALID_FORM = "invalid_form"; String INVALID_FORM = "invalid_form";
String EXPIRED_CODE = "expired_code"; String EXPIRED_CODE = "expired_code";
String REGISTRATION_DISABLED = "registration_disabled"; String REGISTRATION_DISABLED = "registration_disabled";
String REJECTED_BY_USER = "rejected_by_user"; String REJECTED_BY_USER = "rejected_by_user";
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_USERNAME_EXISTS = "federated_identity_username_exists"; String FEDERATED_IDENTITY_REGISTRATION_EMAIL_MISSING = "federated_identity_registration_email_missing";
String SSL_REQUIRED = "ssl_required"; String FEDERATED_IDENTITY_USERNAME_EXISTS = "federated_identity_username_exists";
String SSL_REQUIRED = "ssl_required";
String USER_SESSION_NOT_FOUND = "user_session_not_found"; String USER_SESSION_NOT_FOUND = "user_session_not_found";
String EMAIL_SEND_FAILED = "email_send_failed"; String EMAIL_SEND_FAILED = "email_send_failed";
String INVALID_EMAIL = "invalid_email"; String INVALID_EMAIL = "invalid_email";
} }

View file

@ -12,7 +12,14 @@
<div class="col-sm-4"> <div class="col-sm-4">
<input ng-model="realm.registrationAllowed" name="registrationAllowed" id="registrationAllowed" onoffswitch /> <input ng-model="realm.registrationAllowed" name="registrationAllowed" id="registrationAllowed" onoffswitch />
</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 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>
<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>

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

@ -30,39 +30,43 @@ import org.keycloak.representations.idm.CredentialRepresentation;
*/ */
public class RealmBean { public class RealmBean {
private RealmModel realm; private RealmModel realm;
public RealmBean(RealmModel realmModel) { public RealmBean(RealmModel realmModel) {
realm = realmModel; realm = realmModel;
} }
public String getName() { public String getName() {
return realm.getName(); return realm.getName();
} }
public boolean isIdentityFederationEnabled() { public boolean isIdentityFederationEnabled() {
return realm.isIdentityFederationEnabled(); return realm.isIdentityFederationEnabled();
} }
public boolean isRegistrationAllowed() { public boolean isRegistrationAllowed() {
return realm.isRegistrationAllowed(); return realm.isRegistrationAllowed();
} }
public boolean isResetPasswordAllowed() { public boolean isRegistrationEmailAsUsername() {
return realm.isResetPasswordAllowed(); return realm.isRegistrationEmailAsUsername();
} }
public boolean isRememberMe() { public boolean isResetPasswordAllowed() {
return realm.isRememberMe(); return realm.isResetPasswordAllowed();
} }
public boolean isPassword() { public boolean isRememberMe() {
for (RequiredCredentialModel r : realm.getRequiredCredentials()) { return realm.isRememberMe();
if (r.getType().equals(CredentialRepresentation.PASSWORD)) { }
return true;
} public boolean isPassword() {
} for (RequiredCredentialModel r : realm.getRequiredCredentials()) {
return false; if (r.getType().equals(CredentialRepresentation.PASSWORD)) {
} return true;
}
}
return false;
}
} }

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,233 +8,272 @@ 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 $
*/ */
public interface RealmModel extends RoleContainerModel { public interface RealmModel extends RoleContainerModel {
interface RealmCreationEvent extends ProviderEvent { interface RealmCreationEvent extends ProviderEvent {
RealmModel getCreatedRealm(); RealmModel getCreatedRealm();
} }
interface ClientCreationEvent extends ProviderEvent {
ClientModel getCreatedClient();
}
interface ApplicationCreationEvent extends ClientCreationEvent {
ApplicationModel getCreatedApplication();
}
interface OAuthClientCreationEvent extends ClientCreationEvent {
OAuthClientModel getCreatedOAuthClient();
}
String getId(); interface ClientCreationEvent extends ProviderEvent {
ClientModel getCreatedClient();
}
String getName(); interface ApplicationCreationEvent extends ClientCreationEvent {
ApplicationModel getCreatedApplication();
}
void setName(String name); interface OAuthClientCreationEvent extends ClientCreationEvent {
OAuthClientModel getCreatedOAuthClient();
}
boolean isEnabled(); String getId();
void setEnabled(boolean enabled); String getName();
SslRequired getSslRequired(); void setName(String name);
void setSslRequired(SslRequired sslRequired); boolean isEnabled();
boolean isRegistrationAllowed(); void setEnabled(boolean enabled);
void setRegistrationAllowed(boolean registrationAllowed); SslRequired getSslRequired();
boolean isPasswordCredentialGrantAllowed(); void setSslRequired(SslRequired sslRequired);
void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed); boolean isRegistrationAllowed();
boolean isRememberMe(); void setRegistrationAllowed(boolean registrationAllowed);
void setRememberMe(boolean rememberMe); public boolean isRegistrationEmailAsUsername();
//--- brute force settings public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername);
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
boolean isPasswordCredentialGrantAllowed();
boolean isVerifyEmail(); void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed);
void setVerifyEmail(boolean verifyEmail); boolean isRememberMe();
boolean isResetPasswordAllowed(); void setRememberMe(boolean rememberMe);
void setResetPasswordAllowed(boolean resetPasswordAllowed); // --- brute force settings
boolean isBruteForceProtected();
int getSsoSessionIdleTimeout(); void setBruteForceProtected(boolean value);
void setSsoSessionIdleTimeout(int seconds);
int getSsoSessionMaxLifespan(); int getMaxFailureWaitSeconds();
void setSsoSessionMaxLifespan(int seconds);
int getAccessTokenLifespan(); void setMaxFailureWaitSeconds(int val);
void setAccessTokenLifespan(int seconds); int getWaitIncrementSeconds();
int getAccessCodeLifespan(); void setWaitIncrementSeconds(int val);
void setAccessCodeLifespan(int seconds); int getMinimumQuickLoginWaitSeconds();
int getAccessCodeLifespanUserAction(); void setMinimumQuickLoginWaitSeconds(int val);
void setAccessCodeLifespanUserAction(int seconds); long getQuickLoginCheckMilliSeconds();
int getAccessCodeLifespanLogin(); void setQuickLoginCheckMilliSeconds(long val);
void setAccessCodeLifespanLogin(int seconds); int getMaxDeltaTimeSeconds();
String getPublicKeyPem(); void setMaxDeltaTimeSeconds(int val);
void setPublicKeyPem(String publicKeyPem); int getFailureFactor();
String getPrivateKeyPem(); void setFailureFactor(int failureFactor);
void setPrivateKeyPem(String privateKeyPem); // --- end brute force settings
PublicKey getPublicKey(); boolean isVerifyEmail();
void setPublicKey(PublicKey publicKey); void setVerifyEmail(boolean verifyEmail);
String getCodeSecret(); boolean isResetPasswordAllowed();
Key getCodeSecretKey(); void setResetPasswordAllowed(boolean resetPasswordAllowed);
void setCodeSecret(String codeSecret); int getSsoSessionIdleTimeout();
X509Certificate getCertificate(); void setSsoSessionIdleTimeout(int seconds);
void setCertificate(X509Certificate certificate);
String getCertificatePem();
void setCertificatePem(String certificate);
PrivateKey getPrivateKey(); int getSsoSessionMaxLifespan();
void setPrivateKey(PrivateKey privateKey); void setSsoSessionMaxLifespan(int seconds);
List<RequiredCredentialModel> getRequiredCredentials(); int getAccessTokenLifespan();
void addRequiredCredential(String cred); void setAccessTokenLifespan(int seconds);
PasswordPolicy getPasswordPolicy(); int getAccessCodeLifespan();
void setPasswordPolicy(PasswordPolicy policy); void setAccessCodeLifespan(int seconds);
RoleModel getRoleById(String id); int getAccessCodeLifespanUserAction();
List<String> getDefaultRoles(); void setAccessCodeLifespanUserAction(int seconds);
void addDefaultRole(String name); int getAccessCodeLifespanLogin();
void updateDefaultRoles(String[] defaultRoles); void setAccessCodeLifespanLogin(int seconds);
ClientModel findClient(String clientId); String getPublicKeyPem();
Map<String, ApplicationModel> getApplicationNameMap(); void setPublicKeyPem(String publicKeyPem);
List<ApplicationModel> getApplications(); String getPrivateKeyPem();
ApplicationModel addApplication(String name); void setPrivateKeyPem(String privateKeyPem);
ApplicationModel addApplication(String id, String name); PublicKey getPublicKey();
boolean removeApplication(String id); void setPublicKey(PublicKey publicKey);
ApplicationModel getApplicationById(String id); String getCodeSecret();
ApplicationModel getApplicationByName(String name);
void updateRequiredCredentials(Set<String> creds); Key getCodeSecretKey();
OAuthClientModel addOAuthClient(String name); void setCodeSecret(String codeSecret);
OAuthClientModel addOAuthClient(String id, String name); X509Certificate getCertificate();
OAuthClientModel getOAuthClient(String name); void setCertificate(X509Certificate certificate);
OAuthClientModel getOAuthClientById(String id);
boolean removeOAuthClient(String id);
List<OAuthClientModel> getOAuthClients(); String getCertificatePem();
Map<String, String> getBrowserSecurityHeaders(); void setCertificatePem(String certificate);
void setBrowserSecurityHeaders(Map<String, String> headers);
Map<String, String> getSmtpConfig(); PrivateKey getPrivateKey();
void setSmtpConfig(Map<String, String> smtpConfig); void setPrivateKey(PrivateKey privateKey);
List<IdentityProviderModel> getIdentityProviders(); List<RequiredCredentialModel> getRequiredCredentials();
IdentityProviderModel getIdentityProviderById(String identityProviderId);
void addIdentityProvider(IdentityProviderModel identityProvider);
void removeIdentityProviderById(String providerId);
void updateIdentityProvider(IdentityProviderModel identityProvider);
List<UserFederationProviderModel> getUserFederationProviders(); void addRequiredCredential(String cred);
UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync); PasswordPolicy getPasswordPolicy();
void updateUserFederationProvider(UserFederationProviderModel provider);
void removeUserFederationProvider(UserFederationProviderModel provider);
void setUserFederationProviders(List<UserFederationProviderModel> providers);
String getLoginTheme(); void setPasswordPolicy(PasswordPolicy policy);
void setLoginTheme(String name); RoleModel getRoleById(String id);
String getAccountTheme(); List<String> getDefaultRoles();
void setAccountTheme(String name); void addDefaultRole(String name);
String getAdminTheme(); void updateDefaultRoles(String[] defaultRoles);
void setAdminTheme(String name); ClientModel findClient(String clientId);
String getEmailTheme(); Map<String, ApplicationModel> getApplicationNameMap();
void setEmailTheme(String name); List<ApplicationModel> getApplications();
ApplicationModel addApplication(String name);
/** ApplicationModel addApplication(String id, String name);
* Time in seconds since epoc
*
* @return
*/
int getNotBefore();
void setNotBefore(int notBefore); boolean removeApplication(String id);
boolean removeRoleById(String id); ApplicationModel getApplicationById(String id);
boolean isEventsEnabled(); ApplicationModel getApplicationByName(String name);
void setEventsEnabled(boolean enabled); void updateRequiredCredentials(Set<String> creds);
long getEventsExpiration(); OAuthClientModel addOAuthClient(String name);
void setEventsExpiration(long expiration); OAuthClientModel addOAuthClient(String id, String name);
Set<String> getEventsListeners(); OAuthClientModel getOAuthClient(String name);
void setEventsListeners(Set<String> listeners); OAuthClientModel getOAuthClientById(String id);
ApplicationModel getMasterAdminApp(); boolean removeOAuthClient(String id);
void setMasterAdminApp(ApplicationModel app); List<OAuthClientModel> getOAuthClients();
ClientModel findClientById(String id); Map<String, String> getBrowserSecurityHeaders();
boolean isIdentityFederationEnabled(); void setBrowserSecurityHeaders(Map<String, String> headers);
Map<String, String> getSmtpConfig();
void setSmtpConfig(Map<String, String> smtpConfig);
List<IdentityProviderModel> getIdentityProviders();
IdentityProviderModel getIdentityProviderById(String identityProviderId);
void addIdentityProvider(IdentityProviderModel identityProvider);
void removeIdentityProviderById(String providerId);
void updateIdentityProvider(IdentityProviderModel identityProvider);
List<UserFederationProviderModel> getUserFederationProviders();
UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority,
String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync);
void updateUserFederationProvider(UserFederationProviderModel provider);
void removeUserFederationProvider(UserFederationProviderModel provider);
void setUserFederationProviders(List<UserFederationProviderModel> providers);
String getLoginTheme();
void setLoginTheme(String name);
String getAccountTheme();
void setAccountTheme(String name);
String getAdminTheme();
void setAdminTheme(String name);
String getEmailTheme();
void setEmailTheme(String name);
/**
* Time in seconds since epoc
*
* @return
*/
int getNotBefore();
void setNotBefore(int notBefore);
boolean removeRoleById(String id);
boolean isEventsEnabled();
void setEventsEnabled(boolean enabled);
long getEventsExpiration();
void setEventsExpiration(long expiration);
Set<String> getEventsListeners();
void setEventsListeners(Set<String> listeners);
ApplicationModel getMasterAdminApp();
void setMasterAdminApp(ApplicationModel app);
ClientModel findClientById(String id);
boolean isIdentityFederationEnabled();
} }

View file

@ -10,394 +10,402 @@ import java.util.Map;
*/ */
public class RealmEntity extends AbstractIdentifiableEntity { public class RealmEntity extends AbstractIdentifiableEntity {
private String name; private String name;
private boolean enabled; private boolean enabled;
private String sslRequired; private String sslRequired;
private boolean registrationAllowed; private boolean registrationAllowed;
private boolean rememberMe; protected boolean registrationEmailAsUsername;
private boolean verifyEmail; private boolean rememberMe;
private boolean passwordCredentialGrantAllowed; private boolean verifyEmail;
private boolean resetPasswordAllowed; private boolean passwordCredentialGrantAllowed;
private String passwordPolicy; private boolean resetPasswordAllowed;
//--- brute force settings private String passwordPolicy;
private boolean bruteForceProtected; // --- brute force settings
private int maxFailureWaitSeconds; private boolean bruteForceProtected;
private int minimumQuickLoginWaitSeconds; private int maxFailureWaitSeconds;
private int waitIncrementSeconds; private int minimumQuickLoginWaitSeconds;
private long quickLoginCheckMilliSeconds; private int waitIncrementSeconds;
private int maxDeltaTimeSeconds; private long quickLoginCheckMilliSeconds;
private int failureFactor; private int maxDeltaTimeSeconds;
//--- end brute force settings private int failureFactor;
// --- end brute force settings
private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionIdleTimeout;
private int accessTokenLifespan; private int ssoSessionMaxLifespan;
private int accessCodeLifespan; private int accessTokenLifespan;
private int accessCodeLifespanUserAction; private int accessCodeLifespan;
private int accessCodeLifespanLogin; private int accessCodeLifespanUserAction;
private int notBefore; private int accessCodeLifespanLogin;
private int notBefore;
private String publicKeyPem;
private String privateKeyPem; private String publicKeyPem;
private String certificatePem; private String privateKeyPem;
private String codeSecret; private String certificatePem;
private String codeSecret;
private String loginTheme;
private String accountTheme; private String loginTheme;
private String adminTheme; private String accountTheme;
private String emailTheme; private String adminTheme;
private String emailTheme;
// We are using names of defaultRoles (not ids)
private List<String> defaultRoles = new ArrayList<String>(); // We are using names of defaultRoles (not ids)
private List<String> defaultRoles = new ArrayList<String>();
private List<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
private List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>(); private List<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
private List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>(); private List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>();
private List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
private Map<String, String> browserSecurityHeaders = new HashMap<String, String>();
private Map<String, String> smtpConfig = new HashMap<String, String>(); private Map<String, String> browserSecurityHeaders = new HashMap<String, String>();
private Map<String, String> socialConfig = new HashMap<String, String>(); private Map<String, String> smtpConfig = new HashMap<String, String>();
private Map<String, String> socialConfig = new HashMap<String, String>();
private boolean eventsEnabled;
private long eventsExpiration; private boolean eventsEnabled;
private List<String> eventsListeners = new ArrayList<String>(); private long eventsExpiration;
private List<String> eventsListeners = new ArrayList<String>();
private String adminAppId;
private String adminAppId;
public String getName() {
return name; public String getName() {
} return name;
}
public void setName(String name) {
this.name = name; public void setName(String name) {
} this.name = name;
}
public boolean isEnabled() {
return enabled; public boolean isEnabled() {
} return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled; public void setEnabled(boolean enabled) {
} this.enabled = enabled;
}
public String getSslRequired() {
return sslRequired; public String getSslRequired() {
} return sslRequired;
}
public void setSslRequired(String sslRequired) {
this.sslRequired = sslRequired; public void setSslRequired(String sslRequired) {
} this.sslRequired = sslRequired;
}
public boolean isPasswordCredentialGrantAllowed() {
return passwordCredentialGrantAllowed; public boolean isPasswordCredentialGrantAllowed() {
} return passwordCredentialGrantAllowed;
}
public void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed) {
this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed; public void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed) {
} this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed;
}
public boolean isRegistrationAllowed() {
return registrationAllowed; public boolean isRegistrationAllowed() {
} return registrationAllowed;
}
public void setRegistrationAllowed(boolean registrationAllowed) {
this.registrationAllowed = registrationAllowed; public void setRegistrationAllowed(boolean registrationAllowed) {
} this.registrationAllowed = registrationAllowed;
}
public boolean isRememberMe() {
return rememberMe; public boolean isRegistrationEmailAsUsername() {
} return registrationEmailAsUsername;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe; public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
} this.registrationEmailAsUsername = registrationEmailAsUsername;
}
public boolean isVerifyEmail() {
return verifyEmail; public boolean isRememberMe() {
} return rememberMe;
}
public void setVerifyEmail(boolean verifyEmail) {
this.verifyEmail = verifyEmail; public void setRememberMe(boolean rememberMe) {
} this.rememberMe = rememberMe;
}
public boolean isResetPasswordAllowed() {
return resetPasswordAllowed; public boolean isVerifyEmail() {
} return verifyEmail;
}
public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
this.resetPasswordAllowed = resetPasswordAllowed; public void setVerifyEmail(boolean verifyEmail) {
} this.verifyEmail = verifyEmail;
}
public String getPasswordPolicy() { public boolean isResetPasswordAllowed() {
return passwordPolicy; return resetPasswordAllowed;
} }
public void setPasswordPolicy(String passwordPolicy) {
this.passwordPolicy = passwordPolicy;
}
public boolean isBruteForceProtected() { public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
return bruteForceProtected; this.resetPasswordAllowed = resetPasswordAllowed;
} }
public void setBruteForceProtected(boolean bruteForceProtected) { public String getPasswordPolicy() {
this.bruteForceProtected = bruteForceProtected; return passwordPolicy;
} }
public int getMaxFailureWaitSeconds() { public void setPasswordPolicy(String passwordPolicy) {
return maxFailureWaitSeconds; this.passwordPolicy = passwordPolicy;
} }
public void setMaxFailureWaitSeconds(int maxFailureWaitSeconds) { public boolean isBruteForceProtected() {
this.maxFailureWaitSeconds = maxFailureWaitSeconds; return bruteForceProtected;
} }
public int getMinimumQuickLoginWaitSeconds() { public void setBruteForceProtected(boolean bruteForceProtected) {
return minimumQuickLoginWaitSeconds; this.bruteForceProtected = bruteForceProtected;
} }
public void setMinimumQuickLoginWaitSeconds(int minimumQuickLoginWaitSeconds) { public int getMaxFailureWaitSeconds() {
this.minimumQuickLoginWaitSeconds = minimumQuickLoginWaitSeconds; return maxFailureWaitSeconds;
} }
public int getWaitIncrementSeconds() { public void setMaxFailureWaitSeconds(int maxFailureWaitSeconds) {
return waitIncrementSeconds; this.maxFailureWaitSeconds = maxFailureWaitSeconds;
} }
public void setWaitIncrementSeconds(int waitIncrementSeconds) { public int getMinimumQuickLoginWaitSeconds() {
this.waitIncrementSeconds = waitIncrementSeconds; return minimumQuickLoginWaitSeconds;
} }
public long getQuickLoginCheckMilliSeconds() { public void setMinimumQuickLoginWaitSeconds(int minimumQuickLoginWaitSeconds) {
return quickLoginCheckMilliSeconds; this.minimumQuickLoginWaitSeconds = minimumQuickLoginWaitSeconds;
} }
public void setQuickLoginCheckMilliSeconds(long quickLoginCheckMilliSeconds) { public int getWaitIncrementSeconds() {
this.quickLoginCheckMilliSeconds = quickLoginCheckMilliSeconds; return waitIncrementSeconds;
} }
public int getMaxDeltaTimeSeconds() { public void setWaitIncrementSeconds(int waitIncrementSeconds) {
return maxDeltaTimeSeconds; this.waitIncrementSeconds = waitIncrementSeconds;
} }
public void setMaxDeltaTimeSeconds(int maxDeltaTimeSeconds) { public long getQuickLoginCheckMilliSeconds() {
this.maxDeltaTimeSeconds = maxDeltaTimeSeconds; return quickLoginCheckMilliSeconds;
} }
public int getFailureFactor() { public void setQuickLoginCheckMilliSeconds(long quickLoginCheckMilliSeconds) {
return failureFactor; this.quickLoginCheckMilliSeconds = quickLoginCheckMilliSeconds;
} }
public void setFailureFactor(int failureFactor) { public int getMaxDeltaTimeSeconds() {
this.failureFactor = failureFactor; return maxDeltaTimeSeconds;
} }
public int getSsoSessionIdleTimeout() { public void setMaxDeltaTimeSeconds(int maxDeltaTimeSeconds) {
return ssoSessionIdleTimeout; this.maxDeltaTimeSeconds = maxDeltaTimeSeconds;
} }
public void setSsoSessionIdleTimeout(int ssoSessionIdleTimeout) { public int getFailureFactor() {
this.ssoSessionIdleTimeout = ssoSessionIdleTimeout; return failureFactor;
} }
public int getSsoSessionMaxLifespan() { public void setFailureFactor(int failureFactor) {
return ssoSessionMaxLifespan; this.failureFactor = failureFactor;
} }
public void setSsoSessionMaxLifespan(int ssoSessionMaxLifespan) { public int getSsoSessionIdleTimeout() {
this.ssoSessionMaxLifespan = ssoSessionMaxLifespan; return ssoSessionIdleTimeout;
} }
public int getAccessTokenLifespan() { public void setSsoSessionIdleTimeout(int ssoSessionIdleTimeout) {
return accessTokenLifespan; this.ssoSessionIdleTimeout = ssoSessionIdleTimeout;
} }
public void setAccessTokenLifespan(int accessTokenLifespan) { public int getSsoSessionMaxLifespan() {
this.accessTokenLifespan = accessTokenLifespan; return ssoSessionMaxLifespan;
} }
public int getAccessCodeLifespan() { public void setSsoSessionMaxLifespan(int ssoSessionMaxLifespan) {
return accessCodeLifespan; this.ssoSessionMaxLifespan = ssoSessionMaxLifespan;
} }
public void setAccessCodeLifespan(int accessCodeLifespan) { public int getAccessTokenLifespan() {
this.accessCodeLifespan = accessCodeLifespan; return accessTokenLifespan;
} }
public int getAccessCodeLifespanUserAction() { public void setAccessTokenLifespan(int accessTokenLifespan) {
return accessCodeLifespanUserAction; this.accessTokenLifespan = accessTokenLifespan;
} }
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { public int getAccessCodeLifespan() {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; return accessCodeLifespan;
} }
public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin;
}
public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) { public void setAccessCodeLifespan(int accessCodeLifespan) {
this.accessCodeLifespanLogin = accessCodeLifespanLogin; this.accessCodeLifespan = accessCodeLifespan;
} }
public int getNotBefore() { public int getAccessCodeLifespanUserAction() {
return notBefore; return accessCodeLifespanUserAction;
} }
public void setNotBefore(int notBefore) { public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.notBefore = notBefore; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public String getPublicKeyPem() { public int getAccessCodeLifespanLogin() {
return publicKeyPem; return accessCodeLifespanLogin;
} }
public void setPublicKeyPem(String publicKeyPem) { public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) {
this.publicKeyPem = publicKeyPem; this.accessCodeLifespanLogin = accessCodeLifespanLogin;
} }
public String getPrivateKeyPem() { public int getNotBefore() {
return privateKeyPem; return notBefore;
} }
public void setPrivateKeyPem(String privateKeyPem) { public void setNotBefore(int notBefore) {
this.privateKeyPem = privateKeyPem; this.notBefore = notBefore;
} }
public String getCodeSecret() { public String getPublicKeyPem() {
return codeSecret; return publicKeyPem;
} }
public void setCodeSecret(String codeSecret) { public void setPublicKeyPem(String publicKeyPem) {
this.codeSecret = codeSecret; this.publicKeyPem = publicKeyPem;
} }
public String getLoginTheme() { public String getPrivateKeyPem() {
return loginTheme; return privateKeyPem;
} }
public void setLoginTheme(String loginTheme) { public void setPrivateKeyPem(String privateKeyPem) {
this.loginTheme = loginTheme; this.privateKeyPem = privateKeyPem;
} }
public String getAccountTheme() { public String getCodeSecret() {
return accountTheme; return codeSecret;
} }
public void setAccountTheme(String accountTheme) { public void setCodeSecret(String codeSecret) {
this.accountTheme = accountTheme; this.codeSecret = codeSecret;
} }
public String getAdminTheme() { public String getLoginTheme() {
return adminTheme; return loginTheme;
} }
public void setAdminTheme(String adminTheme) { public void setLoginTheme(String loginTheme) {
this.adminTheme = adminTheme; this.loginTheme = loginTheme;
} }
public String getEmailTheme() { public String getAccountTheme() {
return emailTheme; return accountTheme;
} }
public void setEmailTheme(String emailTheme) {
this.emailTheme = emailTheme;
}
public List<String> getDefaultRoles() {
return defaultRoles;
}
public void setDefaultRoles(List<String> defaultRoles) {
this.defaultRoles = defaultRoles;
}
public List<RequiredCredentialEntity> getRequiredCredentials() {
return requiredCredentials;
}
public void setRequiredCredentials(List<RequiredCredentialEntity> requiredCredentials) {
this.requiredCredentials = requiredCredentials;
}
public Map<String, String> getBrowserSecurityHeaders() {
return browserSecurityHeaders;
}
public void setBrowserSecurityHeaders(Map<String, String> browserSecurityHeaders) {
this.browserSecurityHeaders = browserSecurityHeaders;
}
public Map<String, String> getSmtpConfig() {
return smtpConfig;
}
public void setSmtpConfig(Map<String, String> smtpConfig) {
this.smtpConfig = smtpConfig;
}
public Map<String, String> getSocialConfig() { public void setAccountTheme(String accountTheme) {
return socialConfig; this.accountTheme = accountTheme;
} }
public void setSocialConfig(Map<String, String> socialConfig) { public String getAdminTheme() {
this.socialConfig = socialConfig; return adminTheme;
} }
public boolean isEventsEnabled() { public void setAdminTheme(String adminTheme) {
return eventsEnabled; this.adminTheme = adminTheme;
} }
public void setEventsEnabled(boolean eventsEnabled) { public String getEmailTheme() {
this.eventsEnabled = eventsEnabled; return emailTheme;
} }
public long getEventsExpiration() { public void setEmailTheme(String emailTheme) {
return eventsExpiration; this.emailTheme = emailTheme;
} }
public void setEventsExpiration(long eventsExpiration) { public List<String> getDefaultRoles() {
this.eventsExpiration = eventsExpiration; return defaultRoles;
} }
public List<String> getEventsListeners() { public void setDefaultRoles(List<String> defaultRoles) {
return eventsListeners; this.defaultRoles = defaultRoles;
} }
public void setEventsListeners(List<String> eventsListeners) { public List<RequiredCredentialEntity> getRequiredCredentials() {
this.eventsListeners = eventsListeners; return requiredCredentials;
} }
public String getAdminAppId() { public void setRequiredCredentials(List<RequiredCredentialEntity> requiredCredentials) {
return adminAppId; this.requiredCredentials = requiredCredentials;
} }
public void setAdminAppId(String adminAppId) { public Map<String, String> getBrowserSecurityHeaders() {
this.adminAppId = adminAppId; return browserSecurityHeaders;
} }
public List<UserFederationProviderEntity> getUserFederationProviders() { public void setBrowserSecurityHeaders(Map<String, String> browserSecurityHeaders) {
return userFederationProviders; this.browserSecurityHeaders = browserSecurityHeaders;
} }
public void setUserFederationProviders(List<UserFederationProviderEntity> userFederationProviders) { public Map<String, String> getSmtpConfig() {
this.userFederationProviders = userFederationProviders; return smtpConfig;
} }
public List<IdentityProviderEntity> getIdentityProviders() { public void setSmtpConfig(Map<String, String> smtpConfig) {
return identityProviders; this.smtpConfig = smtpConfig;
} }
public void setIdentityProviders(List<IdentityProviderEntity> identityProviders) { public Map<String, String> getSocialConfig() {
this.identityProviders = identityProviders; return socialConfig;
} }
public String getCertificatePem() { public void setSocialConfig(Map<String, String> socialConfig) {
return certificatePem; this.socialConfig = socialConfig;
} }
public void setCertificatePem(String certificatePem) { public boolean isEventsEnabled() {
this.certificatePem = certificatePem; return eventsEnabled;
} }
public void setEventsEnabled(boolean eventsEnabled) {
this.eventsEnabled = eventsEnabled;
}
public long getEventsExpiration() {
return eventsExpiration;
}
public void setEventsExpiration(long eventsExpiration) {
this.eventsExpiration = eventsExpiration;
}
public List<String> getEventsListeners() {
return eventsListeners;
}
public void setEventsListeners(List<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public String getAdminAppId() {
return adminAppId;
}
public void setAdminAppId(String adminAppId) {
this.adminAppId = adminAppId;
}
public List<UserFederationProviderEntity> getUserFederationProviders() {
return userFederationProviders;
}
public void setUserFederationProviders(List<UserFederationProviderEntity> userFederationProviders) {
this.userFederationProviders = userFederationProviders;
}
public List<IdentityProviderEntity> getIdentityProviders() {
return identityProviders;
}
public void setIdentityProviders(List<IdentityProviderEntity> identityProviders) {
this.identityProviders = identityProviders;
}
public String getCertificatePem() {
return certificatePem;
}
public void setCertificatePem(String 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,337 +39,331 @@ 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 $
*/ */
public class ModelToRepresentation { public class ModelToRepresentation {
public static UserRepresentation toRepresentation(UserModel user) { public static UserRepresentation toRepresentation(UserModel user) {
UserRepresentation rep = new UserRepresentation(); UserRepresentation rep = new UserRepresentation();
rep.setId(user.getId()); rep.setId(user.getId());
rep.setUsername(user.getUsername()); rep.setUsername(user.getUsername());
rep.setLastName(user.getLastName()); rep.setLastName(user.getLastName());
rep.setFirstName(user.getFirstName()); rep.setFirstName(user.getFirstName());
rep.setEmail(user.getEmail()); rep.setEmail(user.getEmail());
rep.setEnabled(user.isEnabled()); rep.setEnabled(user.isEnabled());
rep.setEmailVerified(user.isEmailVerified()); rep.setEmailVerified(user.isEmailVerified());
rep.setTotp(user.isTotp()); rep.setTotp(user.isTotp());
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());
} }
rep.setRequiredActions(reqActions); rep.setRequiredActions(reqActions);
if (user.getAttributes() != null && !user.getAttributes().isEmpty()) { if (user.getAttributes() != null && !user.getAttributes().isEmpty()) {
Map<String, String> attrs = new HashMap<String, String>(); Map<String, String> attrs = new HashMap<String, String>();
attrs.putAll(user.getAttributes()); attrs.putAll(user.getAttributes());
rep.setAttributes(attrs); rep.setAttributes(attrs);
} }
return rep; return rep;
} }
public static RoleRepresentation toRepresentation(RoleModel role) { public static RoleRepresentation toRepresentation(RoleModel role) {
RoleRepresentation rep = new RoleRepresentation(); RoleRepresentation rep = new RoleRepresentation();
rep.setId(role.getId()); rep.setId(role.getId());
rep.setName(role.getName()); rep.setName(role.getName());
rep.setDescription(role.getDescription()); rep.setDescription(role.getDescription());
rep.setComposite(role.isComposite()); rep.setComposite(role.isComposite());
return rep; return rep;
} }
public static RealmRepresentation toRepresentation(RealmModel realm, boolean internal) { public static RealmRepresentation toRepresentation(RealmModel realm, boolean internal) {
RealmRepresentation rep = new RealmRepresentation(); RealmRepresentation rep = new RealmRepresentation();
rep.setId(realm.getId()); rep.setId(realm.getId());
rep.setRealm(realm.getName()); rep.setRealm(realm.getName());
rep.setEnabled(realm.isEnabled()); rep.setEnabled(realm.isEnabled());
rep.setNotBefore(realm.getNotBefore()); rep.setNotBefore(realm.getNotBefore());
rep.setSslRequired(realm.getSslRequired().name().toLowerCase()); rep.setSslRequired(realm.getSslRequired().name().toLowerCase());
rep.setPublicKey(realm.getPublicKeyPem()); rep.setPublicKey(realm.getPublicKeyPem());
if (internal) { if (internal) {
rep.setPrivateKey(realm.getPrivateKeyPem()); rep.setPrivateKey(realm.getPrivateKeyPem());
String privateKeyPem = realm.getPrivateKeyPem(); String privateKeyPem = realm.getPrivateKeyPem();
if (realm.getCertificatePem() == null && privateKeyPem != null) { if (realm.getCertificatePem() == null && privateKeyPem != null) {
KeycloakModelUtils.generateRealmCertificate(realm); KeycloakModelUtils.generateRealmCertificate(realm);
} }
rep.setCodeSecret(realm.getCodeSecret()); rep.setCodeSecret(realm.getCodeSecret());
} }
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.setRememberMe(realm.isRememberMe()); rep.setRegistrationEmailAsUsername(realm.isRegistrationEmailAsUsername());
rep.setBruteForceProtected(realm.isBruteForceProtected()); rep.setRememberMe(realm.isRememberMe());
rep.setMaxFailureWaitSeconds(realm.getMaxFailureWaitSeconds()); rep.setBruteForceProtected(realm.isBruteForceProtected());
rep.setMinimumQuickLoginWaitSeconds(realm.getMinimumQuickLoginWaitSeconds()); rep.setMaxFailureWaitSeconds(realm.getMaxFailureWaitSeconds());
rep.setWaitIncrementSeconds(realm.getWaitIncrementSeconds()); rep.setMinimumQuickLoginWaitSeconds(realm.getMinimumQuickLoginWaitSeconds());
rep.setQuickLoginCheckMilliSeconds(realm.getQuickLoginCheckMilliSeconds()); rep.setWaitIncrementSeconds(realm.getWaitIncrementSeconds());
rep.setMaxDeltaTimeSeconds(realm.getMaxDeltaTimeSeconds()); rep.setQuickLoginCheckMilliSeconds(realm.getQuickLoginCheckMilliSeconds());
rep.setFailureFactor(realm.getFailureFactor()); rep.setMaxDeltaTimeSeconds(realm.getMaxDeltaTimeSeconds());
rep.setVerifyEmail(realm.isVerifyEmail()); rep.setFailureFactor(realm.getFailureFactor());
rep.setResetPasswordAllowed(realm.isResetPasswordAllowed()); rep.setVerifyEmail(realm.isVerifyEmail());
rep.setAccessTokenLifespan(realm.getAccessTokenLifespan()); rep.setResetPasswordAllowed(realm.isResetPasswordAllowed());
rep.setSsoSessionIdleTimeout(realm.getSsoSessionIdleTimeout()); rep.setAccessTokenLifespan(realm.getAccessTokenLifespan());
rep.setSsoSessionMaxLifespan(realm.getSsoSessionMaxLifespan()); rep.setSsoSessionIdleTimeout(realm.getSsoSessionIdleTimeout());
rep.setAccessCodeLifespan(realm.getAccessCodeLifespan()); rep.setSsoSessionMaxLifespan(realm.getSsoSessionMaxLifespan());
rep.setAccessCodeLifespanUserAction(realm.getAccessCodeLifespanUserAction()); rep.setAccessCodeLifespan(realm.getAccessCodeLifespan());
rep.setAccessCodeLifespanLogin(realm.getAccessCodeLifespanLogin()); rep.setAccessCodeLifespanUserAction(realm.getAccessCodeLifespanUserAction());
rep.setSmtpServer(realm.getSmtpConfig()); rep.setAccessCodeLifespanLogin(realm.getAccessCodeLifespanLogin());
rep.setBrowserSecurityHeaders(realm.getBrowserSecurityHeaders()); rep.setSmtpServer(realm.getSmtpConfig());
rep.setAccountTheme(realm.getAccountTheme()); rep.setBrowserSecurityHeaders(realm.getBrowserSecurityHeaders());
rep.setLoginTheme(realm.getLoginTheme()); rep.setAccountTheme(realm.getAccountTheme());
rep.setAdminTheme(realm.getAdminTheme()); rep.setLoginTheme(realm.getLoginTheme());
rep.setEmailTheme(realm.getEmailTheme()); rep.setAdminTheme(realm.getAdminTheme());
if (realm.getPasswordPolicy() != null) { rep.setEmailTheme(realm.getEmailTheme());
rep.setPasswordPolicy(realm.getPasswordPolicy().toString()); if (realm.getPasswordPolicy() != null) {
} rep.setPasswordPolicy(realm.getPasswordPolicy().toString());
}
List<String> defaultRoles = realm.getDefaultRoles(); List<String> defaultRoles = realm.getDefaultRoles();
if (!defaultRoles.isEmpty()) { if (!defaultRoles.isEmpty()) {
List<String> roleStrings = new ArrayList<String>(); List<String> roleStrings = new ArrayList<String>();
roleStrings.addAll(defaultRoles); roleStrings.addAll(defaultRoles);
rep.setDefaultRoles(roleStrings); rep.setDefaultRoles(roleStrings);
} }
List<RequiredCredentialModel> requiredCredentialModels = realm.getRequiredCredentials(); List<RequiredCredentialModel> requiredCredentialModels = realm.getRequiredCredentials();
if (requiredCredentialModels.size() > 0) { if (requiredCredentialModels.size() > 0) {
rep.setRequiredCredentials(new HashSet<String>()); rep.setRequiredCredentials(new HashSet<String>());
for (RequiredCredentialModel cred : requiredCredentialModels) { for (RequiredCredentialModel cred : requiredCredentialModels) {
rep.getRequiredCredentials().add(cred.getType()); rep.getRequiredCredentials().add(cred.getType());
} }
} }
List<UserFederationProviderModel> fedProviderModels = realm.getUserFederationProviders(); List<UserFederationProviderModel> fedProviderModels = realm.getUserFederationProviders();
if (fedProviderModels.size() > 0) { if (fedProviderModels.size() > 0) {
List<UserFederationProviderRepresentation> fedProviderReps = new ArrayList<UserFederationProviderRepresentation>(); List<UserFederationProviderRepresentation> fedProviderReps = new ArrayList<UserFederationProviderRepresentation>();
for (UserFederationProviderModel model : fedProviderModels) { for (UserFederationProviderModel model : fedProviderModels) {
UserFederationProviderRepresentation fedProvRep = toRepresentation(model); UserFederationProviderRepresentation fedProvRep = toRepresentation(model);
fedProviderReps.add(fedProvRep); fedProviderReps.add(fedProvRep);
} }
rep.setUserFederationProviders(fedProviderReps); rep.setUserFederationProviders(fedProviderReps);
} }
for (IdentityProviderModel provider : realm.getIdentityProviders()) { for (IdentityProviderModel provider : realm.getIdentityProviders()) {
rep.addIdentityProvider(toRepresentation(provider)); rep.addIdentityProvider(toRepresentation(provider));
} }
return rep; return rep;
} }
public static RealmEventsConfigRepresentation toEventsConfigReprensetation(RealmModel realm) { public static RealmEventsConfigRepresentation toEventsConfigReprensetation(RealmModel realm) {
RealmEventsConfigRepresentation rep = new RealmEventsConfigRepresentation(); RealmEventsConfigRepresentation rep = new RealmEventsConfigRepresentation();
rep.setEventsEnabled(realm.isEventsEnabled()); rep.setEventsEnabled(realm.isEventsEnabled());
if (realm.getEventsExpiration() != 0) { if (realm.getEventsExpiration() != 0) {
rep.setEventsExpiration(realm.getEventsExpiration()); rep.setEventsExpiration(realm.getEventsExpiration());
} }
if (realm.getEventsListeners() != null) { if (realm.getEventsListeners() != null) {
rep.setEventsListeners(new LinkedList<String>(realm.getEventsListeners())); rep.setEventsListeners(new LinkedList<String>(realm.getEventsListeners()));
} }
return rep; return rep;
} }
public static CredentialRepresentation toRepresentation(UserCredentialModel cred) { public static CredentialRepresentation toRepresentation(UserCredentialModel cred) {
CredentialRepresentation rep = new CredentialRepresentation(); CredentialRepresentation rep = new CredentialRepresentation();
rep.setType(CredentialRepresentation.SECRET); rep.setType(CredentialRepresentation.SECRET);
rep.setValue(cred.getValue()); rep.setValue(cred.getValue());
return rep; return rep;
} }
public static ClaimRepresentation toRepresentation(ClientModel model) { public static ClaimRepresentation toRepresentation(ClientModel model) {
ClaimRepresentation rep = new ClaimRepresentation(); ClaimRepresentation rep = new ClaimRepresentation();
rep.setAddress(ClaimMask.hasAddress(model.getAllowedClaimsMask())); rep.setAddress(ClaimMask.hasAddress(model.getAllowedClaimsMask()));
rep.setEmail(ClaimMask.hasEmail(model.getAllowedClaimsMask())); rep.setEmail(ClaimMask.hasEmail(model.getAllowedClaimsMask()));
rep.setGender(ClaimMask.hasGender(model.getAllowedClaimsMask())); rep.setGender(ClaimMask.hasGender(model.getAllowedClaimsMask()));
rep.setLocale(ClaimMask.hasLocale(model.getAllowedClaimsMask())); rep.setLocale(ClaimMask.hasLocale(model.getAllowedClaimsMask()));
rep.setName(ClaimMask.hasName(model.getAllowedClaimsMask())); rep.setName(ClaimMask.hasName(model.getAllowedClaimsMask()));
rep.setPhone(ClaimMask.hasPhone(model.getAllowedClaimsMask())); rep.setPhone(ClaimMask.hasPhone(model.getAllowedClaimsMask()));
rep.setPicture(ClaimMask.hasPicture(model.getAllowedClaimsMask())); rep.setPicture(ClaimMask.hasPicture(model.getAllowedClaimsMask()));
rep.setProfile(ClaimMask.hasProfile(model.getAllowedClaimsMask())); rep.setProfile(ClaimMask.hasProfile(model.getAllowedClaimsMask()));
rep.setWebsite(ClaimMask.hasWebsite(model.getAllowedClaimsMask())); rep.setWebsite(ClaimMask.hasWebsite(model.getAllowedClaimsMask()));
rep.setUsername(ClaimMask.hasUsername(model.getAllowedClaimsMask())); rep.setUsername(ClaimMask.hasUsername(model.getAllowedClaimsMask()));
return rep; return rep;
} }
public static FederatedIdentityRepresentation toRepresentation(FederatedIdentityModel socialLink) { public static FederatedIdentityRepresentation toRepresentation(FederatedIdentityModel socialLink) {
FederatedIdentityRepresentation rep = new FederatedIdentityRepresentation(); FederatedIdentityRepresentation rep = new FederatedIdentityRepresentation();
rep.setUserName(socialLink.getUserName()); rep.setUserName(socialLink.getUserName());
rep.setIdentityProvider(socialLink.getIdentityProvider()); rep.setIdentityProvider(socialLink.getIdentityProvider());
rep.setUserId(socialLink.getUserId()); rep.setUserId(socialLink.getUserId());
return rep; return rep;
} }
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()) {
ClientModel client = clientSession.getClient(); ClientModel client = clientSession.getClient();
if (client instanceof ApplicationModel) { if (client instanceof ApplicationModel) {
rep.getApplications().put(client.getId(), client.getClientId()); rep.getApplications().put(client.getId(), client.getClientId());
} else if (client instanceof OAuthClientModel) { } else if (client instanceof OAuthClientModel) {
rep.getClients().put(client.getId(), client.getClientId()); rep.getClients().put(client.getId(), client.getClientId());
} }
} }
return rep; return rep;
} }
public static ApplicationRepresentation toRepresentation(ApplicationModel applicationModel) { public static ApplicationRepresentation toRepresentation(ApplicationModel applicationModel) {
ApplicationRepresentation rep = new ApplicationRepresentation(); ApplicationRepresentation rep = new ApplicationRepresentation();
rep.setId(applicationModel.getId()); rep.setId(applicationModel.getId());
rep.setName(applicationModel.getName()); rep.setName(applicationModel.getName());
rep.setEnabled(applicationModel.isEnabled()); rep.setEnabled(applicationModel.isEnabled());
rep.setAdminUrl(applicationModel.getManagementUrl()); rep.setAdminUrl(applicationModel.getManagementUrl());
rep.setPublicClient(applicationModel.isPublicClient()); rep.setPublicClient(applicationModel.isPublicClient());
rep.setFrontchannelLogout(applicationModel.isFrontchannelLogout()); rep.setFrontchannelLogout(applicationModel.isFrontchannelLogout());
rep.setProtocol(applicationModel.getProtocol()); rep.setProtocol(applicationModel.getProtocol());
rep.setAttributes(applicationModel.getAttributes()); rep.setAttributes(applicationModel.getAttributes());
rep.setFullScopeAllowed(applicationModel.isFullScopeAllowed()); rep.setFullScopeAllowed(applicationModel.isFullScopeAllowed());
rep.setBearerOnly(applicationModel.isBearerOnly()); rep.setBearerOnly(applicationModel.isBearerOnly());
rep.setSurrogateAuthRequired(applicationModel.isSurrogateAuthRequired()); rep.setSurrogateAuthRequired(applicationModel.isSurrogateAuthRequired());
rep.setBaseUrl(applicationModel.getBaseUrl()); rep.setBaseUrl(applicationModel.getBaseUrl());
rep.setNotBefore(applicationModel.getNotBefore()); rep.setNotBefore(applicationModel.getNotBefore());
rep.setNodeReRegistrationTimeout(applicationModel.getNodeReRegistrationTimeout()); rep.setNodeReRegistrationTimeout(applicationModel.getNodeReRegistrationTimeout());
Set<String> redirectUris = applicationModel.getRedirectUris(); Set<String> redirectUris = applicationModel.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
rep.setRedirectUris(new LinkedList<String>(redirectUris)); rep.setRedirectUris(new LinkedList<String>(redirectUris));
} }
Set<String> webOrigins = applicationModel.getWebOrigins(); Set<String> webOrigins = applicationModel.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
rep.setWebOrigins(new LinkedList<String>(webOrigins)); rep.setWebOrigins(new LinkedList<String>(webOrigins));
} }
if (!applicationModel.getDefaultRoles().isEmpty()) { if (!applicationModel.getDefaultRoles().isEmpty()) {
rep.setDefaultRoles(applicationModel.getDefaultRoles().toArray(new String[0])); rep.setDefaultRoles(applicationModel.getDefaultRoles().toArray(new String[0]));
} }
if (!applicationModel.getRegisteredNodes().isEmpty()) { if (!applicationModel.getRegisteredNodes().isEmpty()) {
rep.setRegisteredNodes(new HashMap<String, Integer>(applicationModel.getRegisteredNodes())); rep.setRegisteredNodes(new HashMap<String, Integer>(applicationModel.getRegisteredNodes()));
} }
if (!applicationModel.getIdentityProviders().isEmpty()) { if (!applicationModel.getIdentityProviders().isEmpty()) {
rep.setIdentityProviders(toRepresentation(applicationModel.getIdentityProviders())); rep.setIdentityProviders(toRepresentation(applicationModel.getIdentityProviders()));
} }
if (!applicationModel.getProtocolMappers().isEmpty()) { if (!applicationModel.getProtocolMappers().isEmpty()) {
List<ProtocolMapperRepresentation> mappings = new LinkedList<ProtocolMapperRepresentation>(); List<ProtocolMapperRepresentation> mappings = new LinkedList<ProtocolMapperRepresentation>();
for (ProtocolMapperModel model : applicationModel.getProtocolMappers()) { for (ProtocolMapperModel model : applicationModel.getProtocolMappers()) {
mappings.add(toRepresentation(model)); mappings.add(toRepresentation(model));
} }
rep.setProtocolMappers(mappings); rep.setProtocolMappers(mappings);
} }
return rep; return rep;
} }
private static List<ClientIdentityProviderMappingRepresentation> toRepresentation(List<ClientIdentityProviderMappingModel> identityProviders) { private static List<ClientIdentityProviderMappingRepresentation> toRepresentation(
ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>(); List<ClientIdentityProviderMappingModel> identityProviders) {
ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>();
for (ClientIdentityProviderMappingModel model : identityProviders) { for (ClientIdentityProviderMappingModel model : identityProviders) {
ClientIdentityProviderMappingRepresentation representation = new ClientIdentityProviderMappingRepresentation(); ClientIdentityProviderMappingRepresentation representation = new ClientIdentityProviderMappingRepresentation();
representation.setId(model.getIdentityProvider()); representation.setId(model.getIdentityProvider());
representation.setRetrieveToken(model.isRetrieveToken()); representation.setRetrieveToken(model.isRetrieveToken());
representations.add(representation); representations.add(representation);
} }
return representations; return representations;
} }
public static OAuthClientRepresentation toRepresentation(OAuthClientModel model) { public static OAuthClientRepresentation toRepresentation(OAuthClientModel model) {
OAuthClientRepresentation rep = new OAuthClientRepresentation(); OAuthClientRepresentation rep = new OAuthClientRepresentation();
rep.setId(model.getId()); rep.setId(model.getId());
rep.setName(model.getClientId()); rep.setName(model.getClientId());
rep.setEnabled(model.isEnabled()); rep.setEnabled(model.isEnabled());
rep.setPublicClient(model.isPublicClient()); rep.setPublicClient(model.isPublicClient());
rep.setFrontchannelLogout(model.isFrontchannelLogout()); rep.setFrontchannelLogout(model.isFrontchannelLogout());
rep.setProtocol(model.getProtocol()); rep.setProtocol(model.getProtocol());
rep.setAttributes(model.getAttributes()); rep.setAttributes(model.getAttributes());
rep.setFullScopeAllowed(model.isFullScopeAllowed()); rep.setFullScopeAllowed(model.isFullScopeAllowed());
rep.setDirectGrantsOnly(model.isDirectGrantsOnly()); rep.setDirectGrantsOnly(model.isDirectGrantsOnly());
Set<String> redirectUris = model.getRedirectUris(); Set<String> redirectUris = model.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
rep.setRedirectUris(new LinkedList<String>(redirectUris)); rep.setRedirectUris(new LinkedList<String>(redirectUris));
} }
Set<String> webOrigins = model.getWebOrigins(); Set<String> webOrigins = model.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
rep.setWebOrigins(new LinkedList<String>(webOrigins)); rep.setWebOrigins(new LinkedList<String>(webOrigins));
} }
rep.setNotBefore(model.getNotBefore()); rep.setNotBefore(model.getNotBefore());
if (!model.getIdentityProviders().isEmpty()) { if (!model.getIdentityProviders().isEmpty()) {
rep.setIdentityProviders(toRepresentation(model.getIdentityProviders())); rep.setIdentityProviders(toRepresentation(model.getIdentityProviders()));
} }
if (!model.getProtocolMappers().isEmpty()) { if (!model.getProtocolMappers().isEmpty()) {
List<ProtocolMapperRepresentation> mappings = new LinkedList<ProtocolMapperRepresentation>(); List<ProtocolMapperRepresentation> mappings = new LinkedList<ProtocolMapperRepresentation>();
for (ProtocolMapperModel mapper : model.getProtocolMappers()) { for (ProtocolMapperModel mapper : model.getProtocolMappers()) {
mappings.add(toRepresentation(mapper)); mappings.add(toRepresentation(mapper));
} }
rep.setProtocolMappers(mappings); rep.setProtocolMappers(mappings);
} }
return rep; return rep;
} }
public static UserFederationProviderRepresentation toRepresentation(UserFederationProviderModel model) { public static UserFederationProviderRepresentation toRepresentation(UserFederationProviderModel model) {
UserFederationProviderRepresentation rep = new UserFederationProviderRepresentation(); UserFederationProviderRepresentation rep = new UserFederationProviderRepresentation();
rep.setId(model.getId()); rep.setId(model.getId());
rep.setConfig(model.getConfig()); rep.setConfig(model.getConfig());
rep.setProviderName(model.getProviderName()); rep.setProviderName(model.getProviderName());
rep.setPriority(model.getPriority()); rep.setPriority(model.getPriority());
rep.setDisplayName(model.getDisplayName()); rep.setDisplayName(model.getDisplayName());
rep.setFullSyncPeriod(model.getFullSyncPeriod()); rep.setFullSyncPeriod(model.getFullSyncPeriod());
rep.setChangedSyncPeriod(model.getChangedSyncPeriod()); rep.setChangedSyncPeriod(model.getChangedSyncPeriod());
rep.setLastSync(model.getLastSync()); rep.setLastSync(model.getLastSync());
return rep; return rep;
} }
public static IdentityProviderRepresentation toRepresentation(IdentityProviderModel identityProviderModel) { public static IdentityProviderRepresentation toRepresentation(IdentityProviderModel identityProviderModel) {
IdentityProviderRepresentation providerRep = new IdentityProviderRepresentation(); IdentityProviderRepresentation providerRep = new IdentityProviderRepresentation();
providerRep.setInternalId(identityProviderModel.getInternalId()); providerRep.setInternalId(identityProviderModel.getInternalId());
providerRep.setProviderId(identityProviderModel.getProviderId()); providerRep.setProviderId(identityProviderModel.getProviderId());
providerRep.setId(identityProviderModel.getId()); providerRep.setId(identityProviderModel.getId());
providerRep.setName(identityProviderModel.getName()); providerRep.setName(identityProviderModel.getName());
providerRep.setEnabled(identityProviderModel.isEnabled()); providerRep.setEnabled(identityProviderModel.isEnabled());
providerRep.setStoreToken(identityProviderModel.isStoreToken()); providerRep.setStoreToken(identityProviderModel.isStoreToken());
providerRep.setUpdateProfileFirstLogin(identityProviderModel.isUpdateProfileFirstLogin()); providerRep.setUpdateProfileFirstLogin(identityProviderModel.isUpdateProfileFirstLogin());
providerRep.setAuthenticateByDefault(identityProviderModel.isAuthenticateByDefault()); providerRep.setAuthenticateByDefault(identityProviderModel.isAuthenticateByDefault());
providerRep.setConfig(identityProviderModel.getConfig()); providerRep.setConfig(identityProviderModel.getConfig());
return providerRep; return providerRep;
} }
public static ProtocolMapperRepresentation toRepresentation(ProtocolMapperModel model) { public static ProtocolMapperRepresentation toRepresentation(ProtocolMapperModel model) {
ProtocolMapperRepresentation rep = new ProtocolMapperRepresentation(); ProtocolMapperRepresentation rep = new ProtocolMapperRepresentation();
rep.setId(model.getId()); rep.setId(model.getId());
rep.setProtocol(model.getProtocol()); rep.setProtocol(model.getProtocol());
Map<String, String> config = new HashMap<String, String>(); Map<String, String> config = new HashMap<String, String>();
config.putAll(model.getConfig()); config.putAll(model.getConfig());
rep.setConfig(config); rep.setConfig(config);
rep.setName(model.getName()); rep.setName(model.getName());
rep.setProtocolMapper(model.getProtocolMapper()); rep.setProtocolMapper(model.getProtocolMapper());
rep.setConsentText(model.getConsentText()); rep.setConsentText(model.getConsentText());
rep.setConsentRequired(model.isConsentRequired()); rep.setConsentRequired(model.isConsentRequired());
return rep; return rep;
} }
} }

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,329 +8,347 @@ 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 $
*/ */
public class CachedRealm { public class CachedRealm {
private String id; private String id;
private String name; private String name;
private boolean enabled; private boolean enabled;
private SslRequired sslRequired; private SslRequired sslRequired;
private boolean registrationAllowed; private boolean registrationAllowed;
private boolean rememberMe; protected boolean registrationEmailAsUsername;
private boolean verifyEmail; private boolean rememberMe;
private boolean passwordCredentialGrantAllowed; private boolean verifyEmail;
private boolean resetPasswordAllowed; private boolean passwordCredentialGrantAllowed;
private boolean identityFederationEnabled; private boolean resetPasswordAllowed;
//--- brute force settings private boolean identityFederationEnabled;
private boolean bruteForceProtected; // --- brute force settings
private int maxFailureWaitSeconds; private boolean bruteForceProtected;
private int minimumQuickLoginWaitSeconds; private int maxFailureWaitSeconds;
private int waitIncrementSeconds; private int minimumQuickLoginWaitSeconds;
private long quickLoginCheckMilliSeconds; private int waitIncrementSeconds;
private int maxDeltaTimeSeconds; private long quickLoginCheckMilliSeconds;
private int failureFactor; private int maxDeltaTimeSeconds;
//--- end brute force settings private int failureFactor;
// --- end brute force settings
private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionIdleTimeout;
private int accessTokenLifespan; private int ssoSessionMaxLifespan;
private int accessCodeLifespan; private int accessTokenLifespan;
private int accessCodeLifespanUserAction; private int accessCodeLifespan;
private int accessCodeLifespanLogin; private int accessCodeLifespanUserAction;
private int notBefore; private int accessCodeLifespanLogin;
private PasswordPolicy passwordPolicy; private int notBefore;
private PasswordPolicy passwordPolicy;
private String publicKeyPem;
private String privateKeyPem; private String publicKeyPem;
private String certificatePem; private String privateKeyPem;
private String codeSecret; private String certificatePem;
private String codeSecret;
private String loginTheme;
private String accountTheme; private String loginTheme;
private String adminTheme; private String accountTheme;
private String emailTheme; private String adminTheme;
private String masterAdminApp; private String emailTheme;
private String masterAdminApp;
private List<RequiredCredentialModel> requiredCredentials = new ArrayList<RequiredCredentialModel>();
private List<UserFederationProviderModel> userFederationProviders = new ArrayList<UserFederationProviderModel>(); private List<RequiredCredentialModel> requiredCredentials = new ArrayList<RequiredCredentialModel>();
private List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>(); private List<UserFederationProviderModel> userFederationProviders = new ArrayList<UserFederationProviderModel>();
private List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>();
private Map<String, String> browserSecurityHeaders = new HashMap<String, String>();
private Map<String, String> smtpConfig = new HashMap<String, String>(); private Map<String, String> browserSecurityHeaders = new HashMap<String, String>();
private Map<String, String> smtpConfig = new HashMap<String, String>();
private boolean eventsEnabled;
private long eventsExpiration; private boolean eventsEnabled;
private Set<String> eventsListeners = new HashSet<String>(); private long eventsExpiration;
private List<String> defaultRoles = new LinkedList<String>(); private Set<String> eventsListeners = new HashSet<String>();
private Map<String, String> realmRoles = new HashMap<String, String>(); private List<String> defaultRoles = new LinkedList<String>();
private Map<String, String> applications = new HashMap<String, String>(); private Map<String, String> realmRoles = new HashMap<String, String>();
private Map<String, String> clients = new HashMap<String, String>(); private Map<String, String> applications = new HashMap<String, String>();
private Map<String, String> clients = new HashMap<String, String>();
public CachedRealm() {
} public CachedRealm() {
}
public CachedRealm(RealmCache cache, RealmProvider delegate, RealmModel model) {
id = model.getId(); public CachedRealm(RealmCache cache, RealmProvider delegate, RealmModel model) {
name = model.getName(); id = model.getId();
enabled = model.isEnabled(); name = model.getName();
sslRequired = model.getSslRequired(); enabled = model.isEnabled();
registrationAllowed = model.isRegistrationAllowed(); sslRequired = model.getSslRequired();
rememberMe = model.isRememberMe(); registrationAllowed = model.isRegistrationAllowed();
verifyEmail = model.isVerifyEmail(); registrationEmailAsUsername = model.isRegistrationEmailAsUsername();
passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed(); rememberMe = model.isRememberMe();
resetPasswordAllowed = model.isResetPasswordAllowed(); verifyEmail = model.isVerifyEmail();
identityFederationEnabled = model.isIdentityFederationEnabled(); passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed();
//--- brute force settings resetPasswordAllowed = model.isResetPasswordAllowed();
bruteForceProtected = model.isBruteForceProtected(); identityFederationEnabled = model.isIdentityFederationEnabled();
maxFailureWaitSeconds = model.getMaxFailureWaitSeconds(); // --- brute force settings
minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds(); bruteForceProtected = model.isBruteForceProtected();
waitIncrementSeconds = model.getWaitIncrementSeconds(); maxFailureWaitSeconds = model.getMaxFailureWaitSeconds();
quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds(); minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds();
maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds(); waitIncrementSeconds = model.getWaitIncrementSeconds();
failureFactor = model.getFailureFactor(); quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds();
//--- end brute force settings maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds();
failureFactor = model.getFailureFactor();
ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout(); // --- end brute force settings
ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan();
accessTokenLifespan = model.getAccessTokenLifespan(); ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout();
accessCodeLifespan = model.getAccessCodeLifespan(); ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan();
accessCodeLifespanUserAction = model.getAccessCodeLifespanUserAction(); accessTokenLifespan = model.getAccessTokenLifespan();
accessCodeLifespanLogin = model.getAccessCodeLifespanLogin(); accessCodeLifespan = model.getAccessCodeLifespan();
notBefore = model.getNotBefore(); accessCodeLifespanUserAction = model.getAccessCodeLifespanUserAction();
passwordPolicy = model.getPasswordPolicy(); accessCodeLifespanLogin = model.getAccessCodeLifespanLogin();
notBefore = model.getNotBefore();
publicKeyPem = model.getPublicKeyPem(); passwordPolicy = model.getPasswordPolicy();
privateKeyPem = model.getPrivateKeyPem();
certificatePem = model.getCertificatePem(); publicKeyPem = model.getPublicKeyPem();
codeSecret = model.getCodeSecret(); privateKeyPem = model.getPrivateKeyPem();
certificatePem = model.getCertificatePem();
loginTheme = model.getLoginTheme(); codeSecret = model.getCodeSecret();
accountTheme = model.getAccountTheme();
adminTheme = model.getAdminTheme(); loginTheme = model.getLoginTheme();
emailTheme = model.getEmailTheme(); accountTheme = model.getAccountTheme();
adminTheme = model.getAdminTheme();
requiredCredentials = model.getRequiredCredentials(); emailTheme = model.getEmailTheme();
userFederationProviders = model.getUserFederationProviders();
requiredCredentials = model.getRequiredCredentials();
this.identityProviders = new ArrayList<IdentityProviderModel>(); userFederationProviders = model.getUserFederationProviders();
for (IdentityProviderModel identityProviderModel : model.getIdentityProviders()) { this.identityProviders = new ArrayList<IdentityProviderModel>();
this.identityProviders.add(new IdentityProviderModel(identityProviderModel));
} for (IdentityProviderModel identityProviderModel : model.getIdentityProviders()) {
this.identityProviders.add(new IdentityProviderModel(identityProviderModel));
smtpConfig.putAll(model.getSmtpConfig()); }
browserSecurityHeaders.putAll(model.getBrowserSecurityHeaders());
smtpConfig.putAll(model.getSmtpConfig());
eventsEnabled = model.isEventsEnabled(); browserSecurityHeaders.putAll(model.getBrowserSecurityHeaders());
eventsExpiration = model.getEventsExpiration();
eventsListeners.addAll(model.getEventsListeners()); eventsEnabled = model.isEventsEnabled();
defaultRoles.addAll(model.getDefaultRoles()); eventsExpiration = model.getEventsExpiration();
masterAdminApp = model.getMasterAdminApp().getId(); eventsListeners.addAll(model.getEventsListeners());
defaultRoles.addAll(model.getDefaultRoles());
for (RoleModel role : model.getRoles()) { masterAdminApp = model.getMasterAdminApp().getId();
realmRoles.put(role.getName(), role.getId());
CachedRole cachedRole = new CachedRealmRole(role, model); for (RoleModel role : model.getRoles()) {
cache.addCachedRole(cachedRole); realmRoles.put(role.getName(), role.getId());
} CachedRole cachedRole = new CachedRealmRole(role, model);
cache.addCachedRole(cachedRole);
for (ApplicationModel app : model.getApplications()) { }
applications.put(app.getName(), app.getId());
CachedApplication cachedApp = new CachedApplication(cache, delegate, model, app); for (ApplicationModel app : model.getApplications()) {
cache.addCachedApplication(cachedApp); applications.put(app.getName(), app.getId());
} CachedApplication cachedApp = new CachedApplication(cache, delegate, model, app);
cache.addCachedApplication(cachedApp);
for (OAuthClientModel client : model.getOAuthClients()) { }
clients.put(client.getClientId(), client.getId());
CachedOAuthClient cachedApp = new CachedOAuthClient(cache, delegate, model, client); for (OAuthClientModel client : model.getOAuthClients()) {
cache.addCachedOAuthClient(cachedApp); clients.put(client.getClientId(), client.getId());
} CachedOAuthClient cachedApp = new CachedOAuthClient(cache, delegate, model, client);
cache.addCachedOAuthClient(cachedApp);
} }
}
public String getId() {
return id; public String getId() {
} return id;
}
public String getMasterAdminApp() {
return masterAdminApp; public String getMasterAdminApp() {
} return masterAdminApp;
}
public String getName() {
return name; public String getName() {
} return name;
}
public List<String> getDefaultRoles() {
return defaultRoles; public List<String> getDefaultRoles() {
} return defaultRoles;
}
public Map<String, String> getRealmRoles() {
return realmRoles; public Map<String, String> getRealmRoles() {
} return realmRoles;
}
public Map<String, String> getApplications() {
return applications; public Map<String, String> getApplications() {
} return applications;
}
public Map<String, String> getClients() {
return clients; public Map<String, String> getClients() {
} return clients;
}
public boolean isEnabled() {
return enabled; public boolean isEnabled() {
} return enabled;
}
public SslRequired getSslRequired() {
return sslRequired; public SslRequired getSslRequired() {
} return sslRequired;
}
public boolean isRegistrationAllowed() {
return registrationAllowed; public boolean isRegistrationAllowed() {
} return registrationAllowed;
}
public boolean isPasswordCredentialGrantAllowed() {
return passwordCredentialGrantAllowed; public boolean isRegistrationEmailAsUsername() {
} return registrationEmailAsUsername;
}
public boolean isRememberMe() {
return this.rememberMe; public boolean isPasswordCredentialGrantAllowed() {
} return passwordCredentialGrantAllowed;
}
public boolean isBruteForceProtected() {
return bruteForceProtected; public boolean isRememberMe() {
} return this.rememberMe;
}
public int getMaxFailureWaitSeconds() {
return this.maxFailureWaitSeconds;
}
public int getWaitIncrementSeconds() { public boolean isBruteForceProtected() {
return this.waitIncrementSeconds; return bruteForceProtected;
} }
public int getMinimumQuickLoginWaitSeconds() { public int getMaxFailureWaitSeconds() {
return this.minimumQuickLoginWaitSeconds; return this.maxFailureWaitSeconds;
} }
public long getQuickLoginCheckMilliSeconds() { public int getWaitIncrementSeconds() {
return quickLoginCheckMilliSeconds; return this.waitIncrementSeconds;
} }
public int getMaxDeltaTimeSeconds() {
return maxDeltaTimeSeconds;
}
public int getFailureFactor() {
return failureFactor;
}
public boolean isVerifyEmail() {
return verifyEmail;
}
public boolean isResetPasswordAllowed() {
return resetPasswordAllowed;
}
public int getSsoSessionIdleTimeout() { public int getMinimumQuickLoginWaitSeconds() {
return ssoSessionIdleTimeout; return this.minimumQuickLoginWaitSeconds;
} }
public long getQuickLoginCheckMilliSeconds() {
return quickLoginCheckMilliSeconds;
}
public int getMaxDeltaTimeSeconds() {
return maxDeltaTimeSeconds;
}
public int getFailureFactor() {
return failureFactor;
}
public int getSsoSessionMaxLifespan() { public boolean isVerifyEmail() {
return ssoSessionMaxLifespan; return verifyEmail;
} }
public int getAccessTokenLifespan() { public boolean isResetPasswordAllowed() {
return accessTokenLifespan; return resetPasswordAllowed;
} }
public int getSsoSessionIdleTimeout() {
return ssoSessionIdleTimeout;
}
public int getAccessCodeLifespan() { public int getSsoSessionMaxLifespan() {
return accessCodeLifespan; return ssoSessionMaxLifespan;
} }
public int getAccessCodeLifespanUserAction() { public int getAccessTokenLifespan() {
return accessCodeLifespanUserAction; return accessTokenLifespan;
} }
public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; public int getAccessCodeLifespan() {
} return accessCodeLifespan;
}
public String getPublicKeyPem() {
return publicKeyPem; public int getAccessCodeLifespanUserAction() {
} return accessCodeLifespanUserAction;
}
public String getPrivateKeyPem() {
return privateKeyPem; public int getAccessCodeLifespanLogin() {
} return accessCodeLifespanLogin;
}
public String getCodeSecret() {
return codeSecret; public String getPublicKeyPem() {
} return publicKeyPem;
}
public List<RequiredCredentialModel> getRequiredCredentials() {
return requiredCredentials; public String getPrivateKeyPem() {
} return privateKeyPem;
}
public PasswordPolicy getPasswordPolicy() {
return passwordPolicy; public String getCodeSecret() {
} return codeSecret;
}
public boolean isIdentityFederationEnabled() {
return identityFederationEnabled; public List<RequiredCredentialModel> getRequiredCredentials() {
} return requiredCredentials;
}
public Map<String, String> getSmtpConfig() {
return smtpConfig; public PasswordPolicy getPasswordPolicy() {
} return passwordPolicy;
}
public Map<String, String> getBrowserSecurityHeaders() {
return browserSecurityHeaders; public boolean isIdentityFederationEnabled() {
} return identityFederationEnabled;
}
public String getLoginTheme() {
return loginTheme; public Map<String, String> getSmtpConfig() {
} return smtpConfig;
}
public String getAccountTheme() {
return accountTheme; public Map<String, String> getBrowserSecurityHeaders() {
} return browserSecurityHeaders;
}
public String getAdminTheme() {
return this.adminTheme; public String getLoginTheme() {
} return loginTheme;
}
public String getEmailTheme() {
return emailTheme; public String getAccountTheme() {
} return accountTheme;
}
public int getNotBefore() {
return notBefore; public String getAdminTheme() {
} return this.adminTheme;
}
public boolean isEventsEnabled() {
return eventsEnabled; public String getEmailTheme() {
} return emailTheme;
}
public long getEventsExpiration() {
return eventsExpiration; public int getNotBefore() {
} return notBefore;
}
public Set<String> getEventsListeners() {
return eventsListeners; public boolean isEventsEnabled() {
} return eventsEnabled;
}
public List<UserFederationProviderModel> getUserFederationProviders() {
return userFederationProviders; public long getEventsExpiration() {
} return eventsExpiration;
}
public String getCertificatePem() {
return certificatePem; public Set<String> getEventsListeners() {
} return eventsListeners;
}
public List<IdentityProviderModel> getIdentityProviders() {
return identityProviders; public List<UserFederationProviderModel> getUserFederationProviders() {
} return userFederationProviders;
}
public String getCertificatePem() {
return certificatePem;
}
public List<IdentityProviderModel> getIdentityProviders() {
return identityProviders;
}
} }

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,432 +23,433 @@ 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 passwordCredentialGrantAllowed; protected boolean registrationEmailAsUsername;
@Column(name="VERIFY_EMAIL") @Column(name = "PASSWORD_CRED_GRANT_ALLOWED")
protected boolean verifyEmail; protected boolean passwordCredentialGrantAllowed;
@Column(name="RESET_PASSWORD_ALLOWED") @Column(name = "VERIFY_EMAIL")
protected boolean resetPasswordAllowed; protected boolean verifyEmail;
@Column(name="REMEMBER_ME") @Column(name = "RESET_PASSWORD_ALLOWED")
protected boolean rememberMe; protected boolean resetPasswordAllowed;
@Column(name="PASSWORD_POLICY") @Column(name = "REMEMBER_ME")
protected String passwordPolicy; protected boolean rememberMe;
@Column(name = "PASSWORD_POLICY")
@Column(name="SSO_IDLE_TIMEOUT") protected String passwordPolicy;
private int ssoSessionIdleTimeout;
@Column(name="SSO_MAX_LIFESPAN") @Column(name = "SSO_IDLE_TIMEOUT")
private int ssoSessionMaxLifespan; private int ssoSessionIdleTimeout;
@Column(name="ACCESS_TOKEN_LIFESPAN") @Column(name = "SSO_MAX_LIFESPAN")
protected int accessTokenLifespan; private int ssoSessionMaxLifespan;
@Column(name="ACCESS_CODE_LIFESPAN") @Column(name = "ACCESS_TOKEN_LIFESPAN")
protected int accessCodeLifespan; protected int accessTokenLifespan;
@Column(name="USER_ACTION_LIFESPAN") @Column(name = "ACCESS_CODE_LIFESPAN")
protected int accessCodeLifespanUserAction; protected int accessCodeLifespan;
@Column(name="LOGIN_LIFESPAN") @Column(name = "USER_ACTION_LIFESPAN")
protected int accessCodeLifespanLogin; protected int accessCodeLifespanUserAction;
@Column(name="NOT_BEFORE") @Column(name = "LOGIN_LIFESPAN")
protected int notBefore; protected int accessCodeLifespanLogin;
@Column(name = "NOT_BEFORE")
@Column(name="PUBLIC_KEY", length = 2048) protected int notBefore;
protected String publicKeyPem;
@Column(name="PRIVATE_KEY", length = 2048) @Column(name = "PUBLIC_KEY", length = 2048)
protected String privateKeyPem; protected String publicKeyPem;
@Column(name="CERTIFICATE", length = 2048) @Column(name = "PRIVATE_KEY", length = 2048)
protected String certificatePem; protected String privateKeyPem;
@Column(name="CODE_SECRET", length = 255) @Column(name = "CERTIFICATE", length = 2048)
protected String codeSecret; protected String certificatePem;
@Column(name = "CODE_SECRET", length = 255)
@Column(name="LOGIN_THEME") protected String codeSecret;
protected String loginTheme;
@Column(name="ACCOUNT_THEME") @Column(name = "LOGIN_THEME")
protected String accountTheme; protected String loginTheme;
@Column(name="ADMIN_THEME") @Column(name = "ACCOUNT_THEME")
protected String adminTheme; protected String accountTheme;
@Column(name="EMAIL_THEME") @Column(name = "ADMIN_THEME")
protected String emailTheme; protected String adminTheme;
@Column(name = "EMAIL_THEME")
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") protected String emailTheme;
Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>();
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>();
Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true) Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@JoinTable(name="FED_PROVIDERS")
List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>(); @OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name = "FED_PROVIDERS")
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>();
@JoinTable(name="REALM_APPLICATION", joinColumns={ @JoinColumn(name="APPLICATION_ID") }, inverseJoinColumns={ @JoinColumn(name="REALM_ID") })
Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>(); @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name = "REALM_APPLICATION", joinColumns = { @JoinColumn(name = "APPLICATION_ID") }, inverseJoinColumns = { @JoinColumn(name = "REALM_ID") })
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>();
Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
@ElementCollection Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@MapKeyColumn(name="NAME")
@Column(name="VALUE") @ElementCollection
@CollectionTable(name="REALM_SMTP_CONFIG", joinColumns={ @JoinColumn(name="REALM_ID") }) @MapKeyColumn(name = "NAME")
protected Map<String, String> smtpConfig = new HashMap<String, String>(); @Column(name = "VALUE")
@CollectionTable(name = "REALM_SMTP_CONFIG", joinColumns = { @JoinColumn(name = "REALM_ID") })
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) protected Map<String, String> smtpConfig = new HashMap<String, String>();
@JoinTable(name="REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name="REALM_ID")}, inverseJoinColumns = { @JoinColumn(name="ROLE_ID")})
protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>(); @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true)
@JoinTable(name = "REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name = "REALM_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
@Column(name="EVENTS_ENABLED") protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
protected boolean eventsEnabled;
@Column(name="EVENTS_EXPIRATION") @Column(name = "EVENTS_ENABLED")
protected long eventsExpiration; protected boolean eventsEnabled;
@Column(name = "EVENTS_EXPIRATION")
@ElementCollection protected long eventsExpiration;
@Column(name="VALUE")
@CollectionTable(name="REALM_EVENTS_LISTENERS", joinColumns={ @JoinColumn(name="REALM_ID") }) @ElementCollection
protected Set<String> eventsListeners = new HashSet<String>(); @Column(name = "VALUE")
@CollectionTable(name = "REALM_EVENTS_LISTENERS", joinColumns = { @JoinColumn(name = "REALM_ID") })
@OneToOne protected Set<String> eventsListeners = new HashSet<String>();
@JoinColumn(name="MASTER_ADMIN_APP")
protected ApplicationEntity masterAdminApp; @OneToOne
@JoinColumn(name = "MASTER_ADMIN_APP")
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") protected ApplicationEntity masterAdminApp;
protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm")
public String getId() { protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
return id;
} public String getId() {
return id;
public void setId(String id) { }
this.id = id;
} public void setId(String id) {
this.id = id;
public String getName() { }
return name;
} public String getName() {
return name;
public void setName(String name) { }
this.name = name;
} public void setName(String name) {
this.name = name;
public boolean isEnabled() { }
return enabled;
} public boolean isEnabled() {
return enabled;
public void setEnabled(boolean enabled) { }
this.enabled = enabled;
} public void setEnabled(boolean enabled) {
this.enabled = enabled;
public String getSslRequired() { }
return sslRequired;
} public String getSslRequired() {
return sslRequired;
public void setSslRequired(String sslRequired) { }
this.sslRequired = sslRequired;
} public void setSslRequired(String sslRequired) {
this.sslRequired = sslRequired;
public boolean isPasswordCredentialGrantAllowed() { }
return passwordCredentialGrantAllowed;
} public boolean isPasswordCredentialGrantAllowed() {
return passwordCredentialGrantAllowed;
public void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed) { }
this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed;
} public void setPasswordCredentialGrantAllowed(boolean passwordCredentialGrantAllowed) {
this.passwordCredentialGrantAllowed = passwordCredentialGrantAllowed;
public boolean isRegistrationAllowed() { }
return registrationAllowed;
} public boolean isRegistrationAllowed() {
return registrationAllowed;
public void setRegistrationAllowed(boolean registrationAllowed) { }
this.registrationAllowed = registrationAllowed;
} public void setRegistrationAllowed(boolean registrationAllowed) {
this.registrationAllowed = registrationAllowed;
public boolean isRememberMe() { }
return rememberMe;
} public boolean isRegistrationEmailAsUsername() {
return registrationEmailAsUsername;
public void setRememberMe(boolean rememberMe) { }
this.rememberMe = rememberMe;
}
public boolean isVerifyEmail() { public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
return verifyEmail; this.registrationEmailAsUsername = registrationEmailAsUsername;
} }
public void setVerifyEmail(boolean verifyEmail) {
this.verifyEmail = verifyEmail;
}
public boolean isResetPasswordAllowed() {
return resetPasswordAllowed;
}
public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
this.resetPasswordAllowed = resetPasswordAllowed;
}
public int getSsoSessionIdleTimeout() {
return ssoSessionIdleTimeout;
}
public void setSsoSessionIdleTimeout(int ssoSessionIdleTimeout) {
this.ssoSessionIdleTimeout = ssoSessionIdleTimeout;
}
public int getSsoSessionMaxLifespan() {
return ssoSessionMaxLifespan;
}
public void setSsoSessionMaxLifespan(int ssoSessionMaxLifespan) {
this.ssoSessionMaxLifespan = ssoSessionMaxLifespan;
}
public int getAccessTokenLifespan() {
return accessTokenLifespan;
}
public void setAccessTokenLifespan(int accessTokenLifespan) {
this.accessTokenLifespan = accessTokenLifespan;
}
public int getAccessCodeLifespan() {
return accessCodeLifespan;
}
public void setAccessCodeLifespan(int accessCodeLifespan) {
this.accessCodeLifespan = accessCodeLifespan;
}
public int getAccessCodeLifespanUserAction() {
return accessCodeLifespanUserAction;
}
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
}
public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin;
}
public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) {
this.accessCodeLifespanLogin = accessCodeLifespanLogin;
}
public String getPublicKeyPem() {
return publicKeyPem;
}
public void setPublicKeyPem(String publicKeyPem) {
this.publicKeyPem = publicKeyPem;
}
public String getPrivateKeyPem() {
return privateKeyPem;
}
public void setPrivateKeyPem(String privateKeyPem) {
this.privateKeyPem = privateKeyPem;
}
public String getCodeSecret() {
return codeSecret;
}
public void setCodeSecret(String codeSecret) {
this.codeSecret = codeSecret;
}
public Collection<RequiredCredentialEntity> getRequiredCredentials() {
return requiredCredentials;
}
public void setRequiredCredentials(Collection<RequiredCredentialEntity> requiredCredentials) {
this.requiredCredentials = requiredCredentials;
}
public Collection<ApplicationEntity> getApplications() {
return applications;
}
public void setApplications(Collection<ApplicationEntity> applications) {
this.applications = applications;
}
public Collection<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Collection<RoleEntity> roles) {
this.roles = roles;
}
public void addRole(RoleEntity role) {
if (roles == null) {
roles = new ArrayList<RoleEntity>();
}
roles.add(role);
}
public Map<String, String> getSmtpConfig() {
return smtpConfig;
}
public void setSmtpConfig(Map<String, String> smtpConfig) {
this.smtpConfig = smtpConfig;
}
public Collection<RoleEntity> getDefaultRoles() {
return defaultRoles;
}
public void setDefaultRoles(Collection<RoleEntity> defaultRoles) {
this.defaultRoles = defaultRoles;
}
public String getPasswordPolicy() {
return passwordPolicy;
}
public void setPasswordPolicy(String passwordPolicy) {
this.passwordPolicy = passwordPolicy;
}
public String getLoginTheme() {
return loginTheme;
}
public void setLoginTheme(String theme) {
this.loginTheme = theme;
}
public String getAccountTheme() {
return accountTheme;
}
public void setAccountTheme(String theme) {
this.accountTheme = theme;
}
public String getAdminTheme() {
return adminTheme;
}
public void setAdminTheme(String adminTheme) {
this.adminTheme = adminTheme;
}
public String getEmailTheme() {
return emailTheme;
}
public void setEmailTheme(String emailTheme) {
this.emailTheme = emailTheme;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
public boolean isEventsEnabled() {
return eventsEnabled;
}
public void setEventsEnabled(boolean eventsEnabled) {
this.eventsEnabled = eventsEnabled;
}
public long getEventsExpiration() {
return eventsExpiration;
}
public void setEventsExpiration(long eventsExpiration) {
this.eventsExpiration = eventsExpiration;
}
public Set<String> getEventsListeners() {
return eventsListeners;
}
public void setEventsListeners(Set<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public ApplicationEntity getMasterAdminApp() {
return masterAdminApp;
}
public void setMasterAdminApp(ApplicationEntity masterAdminApp) {
this.masterAdminApp = masterAdminApp;
}
public List<UserFederationProviderEntity> getUserFederationProviders() {
return userFederationProviders;
}
public void setUserFederationProviders(List<UserFederationProviderEntity> userFederationProviders) { public boolean isRememberMe() {
this.userFederationProviders = userFederationProviders; return rememberMe;
} }
public Collection<RealmAttributeEntity> getAttributes() { public void setRememberMe(boolean rememberMe) {
return attributes; this.rememberMe = rememberMe;
} }
public void setAttributes(Collection<RealmAttributeEntity> attributes) { public boolean isVerifyEmail() {
this.attributes = attributes; return verifyEmail;
} }
public String getCertificatePem() { public void setVerifyEmail(boolean verifyEmail) {
return certificatePem; this.verifyEmail = verifyEmail;
} }
public void setCertificatePem(String certificatePem) { public boolean isResetPasswordAllowed() {
this.certificatePem = certificatePem; return resetPasswordAllowed;
} }
public List<IdentityProviderEntity> getIdentityProviders() { public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
return this.identityProviders; this.resetPasswordAllowed = resetPasswordAllowed;
} }
public int getSsoSessionIdleTimeout() {
return ssoSessionIdleTimeout;
}
public void setSsoSessionIdleTimeout(int ssoSessionIdleTimeout) {
this.ssoSessionIdleTimeout = ssoSessionIdleTimeout;
}
public void setIdentityProviders(List<IdentityProviderEntity> identityProviders) { public int getSsoSessionMaxLifespan() {
this.identityProviders = identityProviders; return ssoSessionMaxLifespan;
} }
public void addIdentityProvider(IdentityProviderEntity entity) { public void setSsoSessionMaxLifespan(int ssoSessionMaxLifespan) {
entity.setRealm(this); this.ssoSessionMaxLifespan = ssoSessionMaxLifespan;
getIdentityProviders().add(entity); }
}
public int getAccessTokenLifespan() {
return accessTokenLifespan;
}
public void setAccessTokenLifespan(int accessTokenLifespan) {
this.accessTokenLifespan = accessTokenLifespan;
}
public int getAccessCodeLifespan() {
return accessCodeLifespan;
}
public void setAccessCodeLifespan(int accessCodeLifespan) {
this.accessCodeLifespan = accessCodeLifespan;
}
public int getAccessCodeLifespanUserAction() {
return accessCodeLifespanUserAction;
}
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
}
public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin;
}
public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) {
this.accessCodeLifespanLogin = accessCodeLifespanLogin;
}
public String getPublicKeyPem() {
return publicKeyPem;
}
public void setPublicKeyPem(String publicKeyPem) {
this.publicKeyPem = publicKeyPem;
}
public String getPrivateKeyPem() {
return privateKeyPem;
}
public void setPrivateKeyPem(String privateKeyPem) {
this.privateKeyPem = privateKeyPem;
}
public String getCodeSecret() {
return codeSecret;
}
public void setCodeSecret(String codeSecret) {
this.codeSecret = codeSecret;
}
public Collection<RequiredCredentialEntity> getRequiredCredentials() {
return requiredCredentials;
}
public void setRequiredCredentials(Collection<RequiredCredentialEntity> requiredCredentials) {
this.requiredCredentials = requiredCredentials;
}
public Collection<ApplicationEntity> getApplications() {
return applications;
}
public void setApplications(Collection<ApplicationEntity> applications) {
this.applications = applications;
}
public Collection<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Collection<RoleEntity> roles) {
this.roles = roles;
}
public void addRole(RoleEntity role) {
if (roles == null) {
roles = new ArrayList<RoleEntity>();
}
roles.add(role);
}
public Map<String, String> getSmtpConfig() {
return smtpConfig;
}
public void setSmtpConfig(Map<String, String> smtpConfig) {
this.smtpConfig = smtpConfig;
}
public Collection<RoleEntity> getDefaultRoles() {
return defaultRoles;
}
public void setDefaultRoles(Collection<RoleEntity> defaultRoles) {
this.defaultRoles = defaultRoles;
}
public String getPasswordPolicy() {
return passwordPolicy;
}
public void setPasswordPolicy(String passwordPolicy) {
this.passwordPolicy = passwordPolicy;
}
public String getLoginTheme() {
return loginTheme;
}
public void setLoginTheme(String theme) {
this.loginTheme = theme;
}
public String getAccountTheme() {
return accountTheme;
}
public void setAccountTheme(String theme) {
this.accountTheme = theme;
}
public String getAdminTheme() {
return adminTheme;
}
public void setAdminTheme(String adminTheme) {
this.adminTheme = adminTheme;
}
public String getEmailTheme() {
return emailTheme;
}
public void setEmailTheme(String emailTheme) {
this.emailTheme = emailTheme;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
public boolean isEventsEnabled() {
return eventsEnabled;
}
public void setEventsEnabled(boolean eventsEnabled) {
this.eventsEnabled = eventsEnabled;
}
public long getEventsExpiration() {
return eventsExpiration;
}
public void setEventsExpiration(long eventsExpiration) {
this.eventsExpiration = eventsExpiration;
}
public Set<String> getEventsListeners() {
return eventsListeners;
}
public void setEventsListeners(Set<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public ApplicationEntity getMasterAdminApp() {
return masterAdminApp;
}
public void setMasterAdminApp(ApplicationEntity masterAdminApp) {
this.masterAdminApp = masterAdminApp;
}
public List<UserFederationProviderEntity> getUserFederationProviders() {
return userFederationProviders;
}
public void setUserFederationProviders(List<UserFederationProviderEntity> userFederationProviders) {
this.userFederationProviders = userFederationProviders;
}
public Collection<RealmAttributeEntity> getAttributes() {
return attributes;
}
public void setAttributes(Collection<RealmAttributeEntity> attributes) {
this.attributes = attributes;
}
public String getCertificatePem() {
return certificatePem;
}
public void setCertificatePem(String certificatePem) {
this.certificatePem = certificatePem;
}
public List<IdentityProviderEntity> getIdentityProviders() {
return this.identityProviders;
}
public void setIdentityProviders(List<IdentityProviderEntity> identityProviders) {
this.identityProviders = identityProviders;
}
public void addIdentityProvider(IdentityProviderEntity entity) {
entity.setRealm(this);
getIdentityProviders().add(entity);
}
} }

View file

@ -21,58 +21,59 @@ import org.keycloak.representations.idm.CredentialRepresentation;
*/ */
public class ApplianceBootstrap { public class ApplianceBootstrap {
private static final Logger logger = Logger.getLogger(ApplianceBootstrap.class); private static final Logger logger = Logger.getLogger(ApplianceBootstrap.class);
public void bootstrap(KeycloakSessionFactory sessionFactory, String contextPath) { public void bootstrap(KeycloakSessionFactory sessionFactory, String contextPath) {
KeycloakSession session = sessionFactory.create(); KeycloakSession session = sessionFactory.create();
session.getTransaction().begin(); session.getTransaction().begin();
try { try {
bootstrap(session, contextPath); bootstrap(session, contextPath);
session.getTransaction().commit(); session.getTransaction().commit();
} finally { } finally {
session.close(); session.close();
} }
} }
public void bootstrap(KeycloakSession session, String contextPath) { public void bootstrap(KeycloakSession session, String contextPath) {
String adminRealmName = Config.getAdminRealm(); String adminRealmName = Config.getAdminRealm();
if (session.realms().getRealm(adminRealmName) != null) { if (session.realms().getRealm(adminRealmName) != null) {
return; return;
} }
logger.info("Initializing " + adminRealmName + " realm"); logger.info("Initializing " + adminRealmName + " realm");
RealmManager manager = new RealmManager(session); RealmManager manager = new RealmManager(session);
manager.setContextPath(contextPath); manager.setContextPath(contextPath);
RealmModel realm = manager.createRealm(adminRealmName, adminRealmName); RealmModel realm = manager.createRealm(adminRealmName, adminRealmName);
realm.setName(adminRealmName); realm.setName(adminRealmName);
realm.setEnabled(true); realm.setEnabled(true);
realm.addRequiredCredential(CredentialRepresentation.PASSWORD); realm.addRequiredCredential(CredentialRepresentation.PASSWORD);
realm.setSsoSessionIdleTimeout(1800); realm.setSsoSessionIdleTimeout(1800);
realm.setAccessTokenLifespan(60); realm.setAccessTokenLifespan(60);
realm.setSsoSessionMaxLifespan(36000); realm.setSsoSessionMaxLifespan(36000);
realm.setAccessCodeLifespan(60); realm.setAccessCodeLifespan(60);
realm.setAccessCodeLifespanUserAction(300); realm.setAccessCodeLifespanUserAction(300);
realm.setSslRequired(SslRequired.EXTERNAL); realm.setSslRequired(SslRequired.EXTERNAL);
realm.setRegistrationAllowed(false); realm.setRegistrationAllowed(false);
KeycloakModelUtils.generateRealmKeys(realm); realm.setRegistrationEmailAsUsername(false);
KeycloakModelUtils.generateRealmKeys(realm);
UserModel adminUser = session.users().addUser(realm, "admin"); UserModel adminUser = session.users().addUser(realm, "admin");
adminUser.setEnabled(true); adminUser.setEnabled(true);
UserCredentialModel password = new UserCredentialModel(); UserCredentialModel password = new UserCredentialModel();
password.setType(UserCredentialModel.PASSWORD); password.setType(UserCredentialModel.PASSWORD);
password.setValue("admin"); password.setValue("admin");
session.users().updateCredential(realm, adminUser, password); session.users().updateCredential(realm, adminUser, password);
adminUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); adminUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
RoleModel adminRole = realm.getRole(AdminRoles.ADMIN); RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
adminUser.grantRole(adminRole); adminUser.grantRole(adminRole);
ApplicationModel accountApp = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APP); ApplicationModel accountApp = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APP);
for (String r : accountApp.getDefaultRoles()) { for (String r : accountApp.getDefaultRoles()) {
adminUser.grantRole(accountApp.getRole(r)); adminUser.grantRole(accountApp.getRole(r));
} }
} }
} }

View file

@ -1,83 +1,86 @@
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,
if (isEmpty(formData.getFirst("firstName"))) { List<String> requiredCredentialTypes) {
return Messages.MISSING_FIRST_NAME; if (isEmpty(formData.getFirst("firstName"))) {
} return Messages.MISSING_FIRST_NAME;
}
if (isEmpty(formData.getFirst("lastName"))) { if (isEmpty(formData.getFirst("lastName"))) {
return Messages.MISSING_LAST_NAME; return Messages.MISSING_LAST_NAME;
} }
if (isEmpty(formData.getFirst("email"))) { if (isEmpty(formData.getFirst("email"))) {
return Messages.MISSING_EMAIL; return Messages.MISSING_EMAIL;
} }
if (!isEmailValid(formData.getFirst("email"))) { if (!isEmailValid(formData.getFirst("email"))) {
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;
} }
if (requiredCredentialTypes.contains(CredentialRepresentation.PASSWORD)) { if (requiredCredentialTypes.contains(CredentialRepresentation.PASSWORD)) {
if (isEmpty(formData.getFirst(CredentialRepresentation.PASSWORD))) { if (isEmpty(formData.getFirst(CredentialRepresentation.PASSWORD))) {
return Messages.MISSING_PASSWORD; return Messages.MISSING_PASSWORD;
} }
if (!formData.getFirst("password").equals(formData.getFirst("password-confirm"))) { if (!formData.getFirst("password").equals(formData.getFirst("password-confirm"))) {
return Messages.INVALID_PASSWORD_CONFIRM; return Messages.INVALID_PASSWORD_CONFIRM;
} }
} }
return null; return null;
} }
public static String validatePassword(MultivaluedMap<String, String> formData, PasswordPolicy policy) { public static String validatePassword(MultivaluedMap<String, String> formData, PasswordPolicy policy) {
return policy.validate(formData.getFirst("password")); return policy.validate(formData.getFirst("password"));
} }
public static String validateUpdateProfileForm(MultivaluedMap<String, String> formData) { public static String validateUpdateProfileForm(MultivaluedMap<String, String> formData) {
if (isEmpty(formData.getFirst("firstName"))) { if (isEmpty(formData.getFirst("firstName"))) {
return Messages.MISSING_FIRST_NAME; return Messages.MISSING_FIRST_NAME;
} }
if (isEmpty(formData.getFirst("lastName"))) { if (isEmpty(formData.getFirst("lastName"))) {
return Messages.MISSING_LAST_NAME; return Messages.MISSING_LAST_NAME;
} }
if (isEmpty(formData.getFirst("email"))) { if (isEmpty(formData.getFirst("email"))) {
return Messages.MISSING_EMAIL; return Messages.MISSING_EMAIL;
} }
if (!isEmailValid(formData.getFirst("email"))) { if (!isEmailValid(formData.getFirst("email"))) {
return Messages.INVALID_EMAIL; return Messages.INVALID_EMAIL;
} }
return null; return null;
} }
public static boolean isEmpty(String s) { public static boolean isEmpty(String s) {
return s == null || s.length() == 0; return s == null || s.length() == 0;
} }
public static boolean isEmailValid(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
public static boolean isEmailValid(String email) {
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
* *
@ -62,231 +63,268 @@ import java.util.Set;
*/ */
public class AdminAPITest { public class AdminAPITest {
@ClassRule @ClassRule
public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule() { public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule() {
@Override @Override
protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) { protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) {
} }
}; };
private static String createToken() { private static String createToken() {
KeycloakSession session = keycloakRule.startSession(); KeycloakSession session = keycloakRule.startSession();
try { try {
RealmManager manager = new RealmManager(session); RealmManager manager = new RealmManager(session);
RealmModel adminRealm = manager.getRealm(Config.getAdminRealm()); RealmModel adminRealm = manager.getRealm(Config.getAdminRealm());
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);
return tm.encodeToken(adminRealm, token); AccessToken token = tm.createClientAccessToken(session, tm.getAccess(null, adminConsole, admin), adminRealm,
} finally { adminConsole, admin, userSession, null);
keycloakRule.stopSession(session, true); return tm.encodeToken(adminRealm, token);
} } finally {
} keycloakRule.stopSession(session, true);
}
}
protected void testCreateRealm(RealmRepresentation rep) { protected void testCreateRealm(RealmRepresentation rep) {
String token = createToken(); String token = createToken();
final String authHeader = "Bearer " + token; final String authHeader = "Bearer " + token;
ClientRequestFilter authFilter = new ClientRequestFilter() { ClientRequestFilter authFilter = new ClientRequestFilter() {
@Override @Override
public void filter(ClientRequestContext requestContext) throws IOException { public void filter(ClientRequestContext requestContext) throws IOException {
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader); requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
} }
}; };
Client client = ClientBuilder.newBuilder().register(authFilter).build(); Client client = ClientBuilder.newBuilder().register(authFilter).build();
UriBuilder authBase = UriBuilder.fromUri("http://localhost:8081/auth"); UriBuilder authBase = UriBuilder.fromUri("http://localhost:8081/auth");
WebTarget adminRealms = client.target(AdminRoot.realmsUrl(authBase)); WebTarget adminRealms = client.target(AdminRoot.realmsUrl(authBase));
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
RealmRepresentation newRep = new RealmRepresentation();
newRep.setRealm(rep.getRealm());
newRep.setEnabled(rep.isEnabled());
{
Response response = adminRealms.request().post(Entity.json(newRep));
Assert.assertEquals(201, response.getStatus());
response.close();
}
// todo test with full import with initial create
RealmRepresentation storedRealm = realmTarget.request().get(RealmRepresentation.class);
checkRealmRep(newRep, storedRealm);
// create with just name, enabled, and id, just like admin console Response updateResponse = realmTarget.request().put(Entity.json(rep));
RealmRepresentation newRep = new RealmRepresentation(); Assert.assertEquals(204, updateResponse.getStatus());
newRep.setRealm(rep.getRealm()); updateResponse.close();
newRep.setEnabled(rep.isEnabled()); storedRealm = realmTarget.request().get(RealmRepresentation.class);
{ checkRealmRep(rep, storedRealm);
Response response = adminRealms.request().post(Entity.json(newRep));
Assert.assertEquals(201, response.getStatus());
response.close();
}
// todo test with full import with initial create
RealmRepresentation storedRealm = realmTarget.request().get(RealmRepresentation.class);
checkRealmRep(newRep, storedRealm);
Response updateResponse = realmTarget.request().put(Entity.json(rep)); if (rep.getApplications() != null) {
Assert.assertEquals(204, updateResponse.getStatus()); WebTarget applicationsTarget = realmTarget.path("applications");
updateResponse.close(); for (ApplicationRepresentation appRep : rep.getApplications()) {
storedRealm = realmTarget.request().get(RealmRepresentation.class); ApplicationRepresentation newApp = new ApplicationRepresentation();
checkRealmRep(rep, storedRealm); if (appRep.getId() != null)
newApp.setId(appRep.getId());
newApp.setName(appRep.getName());
if (appRep.getSecret() != null) {
newApp.setSecret(appRep.getSecret());
}
Response appCreateResponse = applicationsTarget.request().post(Entity.json(newApp));
Assert.assertEquals(201, appCreateResponse.getStatus());
appCreateResponse.close();
WebTarget appTarget = applicationsTarget.path(appRep.getName());
CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class);
if (appRep.getSecret() != null)
Assert.assertEquals(appRep.getSecret(), cred.getValue());
CredentialRepresentation newCred = appTarget.path("client-secret").request()
.post(null, CredentialRepresentation.class);
Assert.assertNotEquals(newCred.getValue(), cred.getValue());
if (rep.getApplications() != null) { Response appUpdateResponse = appTarget.request().put(Entity.json(appRep));
WebTarget applicationsTarget = realmTarget.path("applications"); Assert.assertEquals(204, appUpdateResponse.getStatus());
for (ApplicationRepresentation appRep : rep.getApplications()) { appUpdateResponse.close();
ApplicationRepresentation newApp = new ApplicationRepresentation();
if (appRep.getId() != null) newApp.setId(appRep.getId());
newApp.setName(appRep.getName());
if (appRep.getSecret() != null) {
newApp.setSecret(appRep.getSecret());
}
Response appCreateResponse = applicationsTarget.request().post(Entity.json(newApp));
Assert.assertEquals(201, appCreateResponse.getStatus());
appCreateResponse.close();
WebTarget appTarget = applicationsTarget.path(appRep.getName());
CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class);
if (appRep.getSecret() != null) Assert.assertEquals(appRep.getSecret(), cred.getValue());
CredentialRepresentation newCred = appTarget.path("client-secret").request().post(null, CredentialRepresentation.class);
Assert.assertNotEquals(newCred.getValue(), cred.getValue());
Response appUpdateResponse = appTarget.request().put(Entity.json(appRep)); ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class);
Assert.assertEquals(204, appUpdateResponse.getStatus());
appUpdateResponse.close();
checkAppUpdate(appRep, storedApp);
ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class); }
}
checkAppUpdate(appRep, storedApp); // delete realm
{
Response response = adminRealms.path(realmName).request().delete();
Assert.assertEquals(204, response.getStatus());
response.close();
} }
} client.close();
}
// delete realm protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) {
{ if (appRep.getName() != null)
Response response = adminRealms.path(realmName).request().delete(); Assert.assertEquals(appRep.getName(), storedApp.getName());
Assert.assertEquals(204, response.getStatus()); if (appRep.isEnabled() != null)
response.close(); Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled());
if (appRep.isBearerOnly() != null)
Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly());
if (appRep.isPublicClient() != null)
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) {
client.close(); Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore());
} }
if (appRep.getDefaultRoles() != null) {
Set<String> set = new HashSet<String>();
for (String val : appRep.getDefaultRoles()) {
set.add(val);
}
Set<String> storedSet = new HashSet<String>();
for (String val : storedApp.getDefaultRoles()) {
storedSet.add(val);
}
protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) { Assert.assertEquals(set, storedSet);
if (appRep.getName() != null) Assert.assertEquals(appRep.getName(), storedApp.getName()); }
if (appRep.isEnabled() != null) Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled());
if (appRep.isBearerOnly() != null) Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly());
if (appRep.isPublicClient() != null) 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) { List<String> redirectUris = appRep.getRedirectUris();
Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore()); if (redirectUris != null) {
} Set<String> set = new HashSet<String>();
if (appRep.getDefaultRoles() != null) { for (String val : appRep.getRedirectUris()) {
Set<String> set = new HashSet<String>(); set.add(val);
for (String val : appRep.getDefaultRoles()) { }
set.add(val); Set<String> storedSet = new HashSet<String>();
} for (String val : storedApp.getRedirectUris()) {
Set<String> storedSet = new HashSet<String>(); storedSet.add(val);
for (String val : storedApp.getDefaultRoles()) { }
storedSet.add(val);
}
Assert.assertEquals(set, storedSet); Assert.assertEquals(set, storedSet);
} }
List<String> redirectUris = appRep.getRedirectUris(); List<String> webOrigins = appRep.getWebOrigins();
if (redirectUris != null) { if (webOrigins != null) {
Set<String> set = new HashSet<String>(); Set<String> set = new HashSet<String>();
for (String val : appRep.getRedirectUris()) { for (String val : appRep.getWebOrigins()) {
set.add(val); set.add(val);
} }
Set<String> storedSet = new HashSet<String>(); Set<String> storedSet = new HashSet<String>();
for (String val : storedApp.getRedirectUris()) { for (String val : storedApp.getWebOrigins()) {
storedSet.add(val); storedSet.add(val);
} }
Assert.assertEquals(set, storedSet); Assert.assertEquals(set, storedSet);
} }
}
List<String> webOrigins = appRep.getWebOrigins(); protected void checkRealmRep(RealmRepresentation rep, RealmRepresentation storedRealm) {
if (webOrigins != null) { if (rep.getId() != null) {
Set<String> set = new HashSet<String>(); Assert.assertEquals(rep.getId(), storedRealm.getId());
for (String val : appRep.getWebOrigins()) { }
set.add(val); if (rep.getRealm() != null) {
} Assert.assertEquals(rep.getRealm(), storedRealm.getRealm());
Set<String> storedSet = new HashSet<String>(); }
for (String val : storedApp.getWebOrigins()) { if (rep.isEnabled() != null)
storedSet.add(val); Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled());
} if (rep.isBruteForceProtected() != null)
Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected());
if (rep.getMaxFailureWaitSeconds() != null)
Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null)
Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
if (rep.getWaitIncrementSeconds() != null)
Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
if (rep.getQuickLoginCheckMilliSeconds() != null)
Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null)
Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
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)
Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
if (rep.getNotBefore() != null)
Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore());
if (rep.getAccessTokenLifespan() != null)
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) {
Assert.assertNotNull(storedRealm.getRequiredCredentials());
for (String cred : rep.getRequiredCredentials()) {
Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred));
}
}
if (rep.getLoginTheme() != null)
Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme());
if (rep.getAccountTheme() != null)
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());
Assert.assertEquals(set, storedSet); if (rep.getPasswordPolicy() != null)
} Assert.assertEquals(rep.getPasswordPolicy(), storedRealm.getPasswordPolicy());
}
protected void checkRealmRep(RealmRepresentation rep, RealmRepresentation storedRealm) { if (rep.getDefaultRoles() != null) {
if (rep.getId() != null) { Assert.assertNotNull(storedRealm.getDefaultRoles());
Assert.assertEquals(rep.getId(), storedRealm.getId()); for (String role : rep.getDefaultRoles()) {
} Assert.assertTrue(storedRealm.getDefaultRoles().contains(role));
if (rep.getRealm() != null) { }
Assert.assertEquals(rep.getRealm(), storedRealm.getRealm()); }
}
if (rep.isEnabled() != null) Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled());
if (rep.isBruteForceProtected() != null) Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected());
if (rep.getMaxFailureWaitSeconds() != null) Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
if (rep.getWaitIncrementSeconds() != null) Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
if (rep.getQuickLoginCheckMilliSeconds() != null) Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
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.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)
Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
if (rep.getNotBefore() != null) Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore());
if (rep.getAccessTokenLifespan() != null) 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) {
Assert.assertNotNull(storedRealm.getRequiredCredentials());
for (String cred : rep.getRequiredCredentials()) {
Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred));
}
}
if (rep.getLoginTheme() != null) Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme());
if (rep.getAccountTheme() != null) 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.getSmtpServer() != null) {
Assert.assertEquals(rep.getSmtpServer(), storedRealm.getSmtpServer());
}
if (rep.getDefaultRoles() != null) { if (rep.getBrowserSecurityHeaders() != null) {
Assert.assertNotNull(storedRealm.getDefaultRoles()); Assert.assertEquals(rep.getBrowserSecurityHeaders(), storedRealm.getBrowserSecurityHeaders());
for (String role : rep.getDefaultRoles()) { }
Assert.assertTrue(storedRealm.getDefaultRoles().contains(role));
}
}
if (rep.getSmtpServer() != null) { }
Assert.assertEquals(rep.getSmtpServer(), storedRealm.getSmtpServer());
}
if (rep.getBrowserSecurityHeaders() != null) { protected void testCreateRealm(String path) {
Assert.assertEquals(rep.getBrowserSecurityHeaders(), storedRealm.getBrowserSecurityHeaders()); RealmRepresentation rep = KeycloakServer.loadJson(getClass().getResourceAsStream(path), RealmRepresentation.class);
} Assert.assertNotNull(rep);
testCreateRealm(rep);
}
} @Test
public void testAdminApi() {
protected void testCreateRealm(String path) { RealmRepresentation empty = new RealmRepresentation();
RealmRepresentation rep = KeycloakServer.loadJson(getClass().getResourceAsStream(path), RealmRepresentation.class); empty.setEnabled(true);
Assert.assertNotNull(rep); empty.setRealm("empty");
testCreateRealm(rep); testCreateRealm(empty);
} testCreateRealm("/admin-test/testrealm.json");
}
@Test
public void testAdminApi() {
RealmRepresentation empty = new RealmRepresentation();
empty.setEnabled(true);
empty.setRealm("empty");
testCreateRealm(empty);
testCreateRealm("/admin-test/testrealm.json");
}
} }

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,67 +11,67 @@ 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.setResetPasswordAllowed(true); realm.setRegistrationEmailAsUsername(true);
realm.setSslRequired(SslRequired.EXTERNAL); realm.setResetPasswordAllowed(true);
realm.setVerifyEmail(true); realm.setSslRequired(SslRequired.EXTERNAL);
realm.setAccessTokenLifespan(1000); realm.setVerifyEmail(true);
realm.setPasswordPolicy(new PasswordPolicy("length")); realm.setAccessTokenLifespan(1000);
realm.setAccessCodeLifespan(1001); realm.setPasswordPolicy(new PasswordPolicy("length"));
realm.setAccessCodeLifespanUserAction(1002); realm.setAccessCodeLifespan(1001);
KeycloakModelUtils.generateRealmKeys(realm); realm.setAccessCodeLifespanUserAction(1002);
realm.addDefaultRole("default-role"); KeycloakModelUtils.generateRealmKeys(realm);
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);
RealmModel copy = importExport(realm, "copy"); RealmModel copy = importExport(realm, "copy");
assertEquals(realm, copy); assertEquals(realm, copy);
} }
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.isResetPasswordAllowed(), actual.isResetPasswordAllowed()); Assert.assertEquals(expected.isRegistrationEmailAsUsername(), actual.isRegistrationEmailAsUsername());
Assert.assertEquals(expected.getSslRequired(), actual.getSslRequired()); Assert.assertEquals(expected.isResetPasswordAllowed(), actual.isResetPasswordAllowed());
Assert.assertEquals(expected.isVerifyEmail(), actual.isVerifyEmail()); Assert.assertEquals(expected.getSslRequired(), actual.getSslRequired());
Assert.assertEquals(expected.getAccessTokenLifespan(), actual.getAccessTokenLifespan()); Assert.assertEquals(expected.isVerifyEmail(), actual.isVerifyEmail());
Assert.assertEquals(expected.getAccessTokenLifespan(), actual.getAccessTokenLifespan());
Assert.assertEquals(expected.getAccessCodeLifespan(), actual.getAccessCodeLifespan()); Assert.assertEquals(expected.getAccessCodeLifespan(), actual.getAccessCodeLifespan());
Assert.assertEquals(expected.getAccessCodeLifespanUserAction(), actual.getAccessCodeLifespanUserAction()); Assert.assertEquals(expected.getAccessCodeLifespanUserAction(), actual.getAccessCodeLifespanUserAction());
Assert.assertEquals(expected.getPublicKeyPem(), actual.getPublicKeyPem()); Assert.assertEquals(expected.getPublicKeyPem(), actual.getPublicKeyPem());
Assert.assertEquals(expected.getPrivateKeyPem(), actual.getPrivateKeyPem()); Assert.assertEquals(expected.getPrivateKeyPem(), actual.getPrivateKeyPem());
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) {
RealmRepresentation representation = ModelToRepresentation.toRepresentation(src, true); RealmRepresentation representation = ModelToRepresentation.toRepresentation(src, true);
representation.setRealm(copyName); representation.setRealm(copyName);
representation.setId(copyName); representation.setId(copyName);
RealmModel copy = realmManager.importRealm(representation); RealmModel copy = realmManager.importRealm(representation);
return realmManager.getRealm(copy.getId()); return realmManager.getRealm(copy.getId());
} }
} }

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",