Use ClientModel wherever possible

This commit is contained in:
Bill Burke 2014-02-26 22:04:57 -05:00
parent c02d532001
commit 48d39bf977
48 changed files with 611 additions and 368 deletions

View file

@ -1,5 +1,6 @@
package org.keycloak.login; package org.keycloak.login;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -38,7 +39,7 @@ public interface LoginForms {
public LoginForms setUser(UserModel user); public LoginForms setUser(UserModel user);
public LoginForms setClient(UserModel client); public LoginForms setClient(ClientModel client);
public LoginForms setFormData(MultivaluedMap<String, String> formData); public LoginForms setFormData(MultivaluedMap<String, String> formData);

View file

@ -17,6 +17,7 @@ import org.keycloak.login.freemarker.model.RegisterBean;
import org.keycloak.login.freemarker.model.SocialBean; import org.keycloak.login.freemarker.model.SocialBean;
import org.keycloak.login.freemarker.model.TotpBean; import org.keycloak.login.freemarker.model.TotpBean;
import org.keycloak.login.freemarker.model.UrlBean; import org.keycloak.login.freemarker.model.UrlBean;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -63,7 +64,7 @@ public class FreeMarkerLoginForms implements LoginForms {
private UserModel user; private UserModel user;
private UserModel client; private ClientModel client;
private UriInfo uriInfo; private UriInfo uriInfo;
@ -240,7 +241,7 @@ public class FreeMarkerLoginForms implements LoginForms {
return this; return this;
} }
public FreeMarkerLoginForms setClient(UserModel client) { public FreeMarkerLoginForms setClient(ClientModel client) {
this.client = client; this.client = client;
return this; return this;
} }

View file

@ -21,6 +21,7 @@
*/ */
package org.keycloak.login.freemarker.model; package org.keycloak.login.freemarker.model;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -36,11 +37,11 @@ public class OAuthGrantBean {
private List<RoleModel> realmRolesRequested; private List<RoleModel> realmRolesRequested;
private MultivaluedMap<String, RoleModel> resourceRolesRequested; private MultivaluedMap<String, RoleModel> resourceRolesRequested;
private String code; private String code;
private UserModel client; private ClientModel client;
private String oAuthCode; private String oAuthCode;
private String action; private String action;
public OAuthGrantBean(String code, UserModel client, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) { public OAuthGrantBean(String code, ClientModel client, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) {
this.code = code; this.code = code;
this.client = client; this.client = client;
this.realmRolesRequested = realmRolesRequested; this.realmRolesRequested = realmRolesRequested;
@ -60,7 +61,7 @@ public class OAuthGrantBean {
} }
public String getClient() { public String getClient() {
return client.getLoginName(); return client.getAgent().getLoginName();
} }
} }

View file

@ -14,10 +14,6 @@ public interface ApplicationModel extends RoleContainerModel, ClientModel {
void setName(String name); void setName(String name);
boolean isEnabled();
void setEnabled(boolean enabled);
boolean isSurrogateAuthRequired(); boolean isSurrogateAuthRequired();
void setSurrogateAuthRequired(boolean surrogateAuthRequired); void setSurrogateAuthRequired(boolean surrogateAuthRequired);
@ -38,7 +34,7 @@ public interface ApplicationModel extends RoleContainerModel, ClientModel {
Set<RoleModel> getApplicationRoleMappings(UserModel user); Set<RoleModel> getApplicationRoleMappings(UserModel user);
Set<RoleModel> getApplicationScopeMappings(UserModel user); Set<RoleModel> getApplicationScopeMappings(ClientModel client);
void addScope(RoleModel role); void addScope(RoleModel role);

View file

@ -1,15 +1,38 @@
package org.keycloak.models; package org.keycloak.models;
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 interface ClientModel { public interface ClientModel {
String getId();
UserModel getAgent();
long getAllowedClaimsMask(); long getAllowedClaimsMask();
void setAllowedClaimsMask(long mask); void setAllowedClaimsMask(long mask);
UserModel getAgent(); Set<String> getWebOrigins();
String getId(); void setWebOrigins(Set<String> webOrigins);
void addWebOrigin(String webOrigin);
void removeWebOrigin(String webOrigin);
Set<String> getRedirectUris();
void setRedirectUris(Set<String> redirectUris);
void addRedirectUri(String redirectUri);
void removeRedirectUri(String redirectUri);
boolean isEnabled();
void setEnabled(boolean enabled);
} }

View file

@ -107,6 +107,8 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void updateDefaultRoles(String[] defaultRoles); void updateDefaultRoles(String[] defaultRoles);
ClientModel findClient(String clientId);
Map<String, ApplicationModel> getApplicationNameMap(); Map<String, ApplicationModel> getApplicationNameMap();
List<ApplicationModel> getApplications(); List<ApplicationModel> getApplications();
@ -173,7 +175,7 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
Set<RoleModel> getRealmRoleMappings(UserModel user); Set<RoleModel> getRealmRoleMappings(UserModel user);
Set<RoleModel> getRealmScopeMappings(UserModel user); Set<RoleModel> getRealmScopeMappings(ClientModel client);
String getLoginTheme(); String getLoginTheme();
@ -193,5 +195,5 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
*/ */
UserCredentialModel getSecret(UserModel user); UserCredentialModel getSecret(UserModel user);
boolean hasScope(UserModel user, RoleModel role); boolean hasScope(ClientModel client, RoleModel role);
} }

View file

@ -8,7 +8,7 @@ import java.util.Set;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
public interface ScopeMapperModel { public interface ScopeMapperModel {
Set<RoleModel> getScopeMappings(UserModel agent); Set<RoleModel> getScopeMappings(ClientModel client);
void addScopeMapping(UserModel agent, RoleModel role); void addScopeMapping(ClientModel client, RoleModel role);
void deleteScopeMapping(UserModel user, RoleModel role); void deleteScopeMapping(ClientModel client, RoleModel role);
} }

View file

@ -37,22 +37,6 @@ public interface UserModel {
void removeRequiredAction(RequiredAction action); void removeRequiredAction(RequiredAction action);
Set<String> getWebOrigins();
void setWebOrigins(Set<String> webOrigins);
void addWebOrigin(String webOrigin);
void removeWebOrigin(String webOrigin);
Set<String> getRedirectUris();
void setRedirectUris(Set<String> redirectUris);
void addRedirectUri(String redirectUri);
void removeRedirectUri(String redirectUri);
String getFirstName(); String getFirstName();
void setFirstName(String firstName); void setFirstName(String firstName);

View file

@ -1,6 +1,7 @@
package org.keycloak.models.jpa; package org.keycloak.models.jpa;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
@ -22,13 +23,13 @@ import java.util.Set;
public class ApplicationAdapter implements ApplicationModel { public class ApplicationAdapter implements ApplicationModel {
protected EntityManager em; protected EntityManager em;
protected ApplicationEntity application; protected ApplicationEntity entity;
protected RealmModel realm; protected RealmModel realm;
public ApplicationAdapter(RealmModel realm, EntityManager em, ApplicationEntity application) { public ApplicationAdapter(RealmModel realm, EntityManager em, ApplicationEntity entity) {
this.realm = realm; this.realm = realm;
this.em = em; this.em = em;
this.application = application; this.entity = entity;
} }
@Override @Override
@ -38,79 +39,79 @@ public class ApplicationAdapter implements ApplicationModel {
@Override @Override
public UserModel getAgent() { public UserModel getAgent() {
return new UserAdapter(application.getApplicationUser()); return new UserAdapter(entity.getApplicationUser());
} }
@Override @Override
public String getId() { public String getId() {
return application.getId(); return entity.getId();
} }
@Override @Override
public String getName() { public String getName() {
return application.getName(); return entity.getName();
} }
@Override @Override
public void setName(String name) { public void setName(String name) {
application.setName(name); entity.setName(name);
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return application.isEnabled(); return entity.isEnabled();
} }
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
application.setEnabled(enabled); entity.setEnabled(enabled);
} }
@Override @Override
public long getAllowedClaimsMask() { public long getAllowedClaimsMask() {
return application.getAllowedClaimsMask(); return entity.getAllowedClaimsMask();
} }
@Override @Override
public void setAllowedClaimsMask(long mask) { public void setAllowedClaimsMask(long mask) {
application.setAllowedClaimsMask(mask); entity.setAllowedClaimsMask(mask);
} }
@Override @Override
public boolean isSurrogateAuthRequired() { public boolean isSurrogateAuthRequired() {
return application.isSurrogateAuthRequired(); return entity.isSurrogateAuthRequired();
} }
@Override @Override
public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
application.setSurrogateAuthRequired(surrogateAuthRequired); entity.setSurrogateAuthRequired(surrogateAuthRequired);
} }
@Override @Override
public String getManagementUrl() { public String getManagementUrl() {
return application.getManagementUrl(); return entity.getManagementUrl();
} }
@Override @Override
public void setManagementUrl(String url) { public void setManagementUrl(String url) {
application.setManagementUrl(url); entity.setManagementUrl(url);
} }
@Override @Override
public String getBaseUrl() { public String getBaseUrl() {
return application.getBaseUrl(); return entity.getBaseUrl();
} }
@Override @Override
public void setBaseUrl(String url) { public void setBaseUrl(String url) {
application.setBaseUrl(url); entity.setBaseUrl(url);
} }
@Override @Override
public RoleModel getRole(String name) { public RoleModel getRole(String name) {
TypedQuery<ApplicationRoleEntity> query = em.createNamedQuery("getAppRoleByName", ApplicationRoleEntity.class); TypedQuery<ApplicationRoleEntity> query = em.createNamedQuery("getAppRoleByName", ApplicationRoleEntity.class);
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("application", application); query.setParameter("application", entity);
List<ApplicationRoleEntity> roles = query.getResultList(); List<ApplicationRoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null; if (roles.size() == 0) return null;
return new RoleAdapter(realm, em, roles.get(0)); return new RoleAdapter(realm, em, roles.get(0));
@ -120,13 +121,13 @@ public class ApplicationAdapter implements ApplicationModel {
public RoleModel addRole(String name) { public RoleModel addRole(String name) {
RoleModel role = getRole(name); RoleModel role = getRole(name);
if (role != null) return role; if (role != null) return role;
ApplicationRoleEntity entity = new ApplicationRoleEntity(); ApplicationRoleEntity roleEntity = new ApplicationRoleEntity();
entity.setName(name); roleEntity.setName(name);
entity.setApplication(application); roleEntity.setApplication(entity);
em.persist(entity); em.persist(roleEntity);
application.getRoles().add(entity); entity.getRoles().add(roleEntity);
em.flush(); em.flush();
return new RoleAdapter(realm, em, entity); return new RoleAdapter(realm, em, roleEntity);
} }
@Override @Override
@ -138,8 +139,8 @@ public class ApplicationAdapter implements ApplicationModel {
ApplicationRoleEntity role = (ApplicationRoleEntity)roleAdapter.getRole(); ApplicationRoleEntity role = (ApplicationRoleEntity)roleAdapter.getRole();
application.getRoles().remove(role); entity.getRoles().remove(role);
application.getDefaultRoles().remove(role); entity.getDefaultRoles().remove(role);
em.createQuery("delete from " + UserScopeMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", role).executeUpdate(); em.createQuery("delete from " + UserScopeMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", role).executeUpdate();
em.createQuery("delete from " + UserRoleMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", role).executeUpdate(); em.createQuery("delete from " + UserRoleMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", role).executeUpdate();
@ -153,7 +154,7 @@ public class ApplicationAdapter implements ApplicationModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>(); Set<RoleModel> list = new HashSet<RoleModel>();
Collection<ApplicationRoleEntity> roles = application.getRoles(); Collection<ApplicationRoleEntity> roles = entity.getRoles();
if (roles == null) return list; if (roles == null) return list;
for (RoleEntity entity : roles) { for (RoleEntity entity : roles) {
list.add(new RoleAdapter(realm, em, entity)); list.add(new RoleAdapter(realm, em, entity));
@ -168,7 +169,7 @@ public class ApplicationAdapter implements ApplicationModel {
// Check if it's application role and belongs to this application // Check if it's application role and belongs to this application
if (entity == null || !(entity instanceof ApplicationRoleEntity)) return null; if (entity == null || !(entity instanceof ApplicationRoleEntity)) return null;
ApplicationRoleEntity appRoleEntity = (ApplicationRoleEntity)entity; ApplicationRoleEntity appRoleEntity = (ApplicationRoleEntity)entity;
return (appRoleEntity.getApplication().equals(this.application)) ? new RoleAdapter(this.realm, em, appRoleEntity) : null; return (appRoleEntity.getApplication().equals(this.entity)) ? new RoleAdapter(this.realm, em, appRoleEntity) : null;
} }
@Override @Override
@ -191,8 +192,8 @@ public class ApplicationAdapter implements ApplicationModel {
} }
@Override @Override
public Set<RoleModel> getApplicationScopeMappings(UserModel user) { public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> roleMappings = realm.getScopeMappings(user); Set<RoleModel> roleMappings = realm.getScopeMappings(client);
Set<RoleModel> appRoles = new HashSet<RoleModel>(); Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) { for (RoleModel role : roleMappings) {
@ -214,7 +215,7 @@ public class ApplicationAdapter implements ApplicationModel {
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
Collection<RoleEntity> entities = application.getDefaultRoles(); Collection<RoleEntity> entities = entity.getDefaultRoles();
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
if (entities == null) return roles; if (entities == null) return roles;
for (RoleEntity entity : entities) { for (RoleEntity entity : entities) {
@ -229,7 +230,7 @@ public class ApplicationAdapter implements ApplicationModel {
if (role == null) { if (role == null) {
role = addRole(name); role = addRole(name);
} }
Collection<RoleEntity> entities = application.getDefaultRoles(); Collection<RoleEntity> entities = entity.getDefaultRoles();
for (RoleEntity entity : entities) { for (RoleEntity entity : entities) {
if (entity.getId().equals(role.getId())) { if (entity.getId().equals(role.getId())) {
return; return;
@ -248,7 +249,7 @@ public class ApplicationAdapter implements ApplicationModel {
@Override @Override
public void updateDefaultRoles(String[] defaultRoles) { public void updateDefaultRoles(String[] defaultRoles) {
Collection<RoleEntity> entities = application.getDefaultRoles(); Collection<RoleEntity> entities = entity.getDefaultRoles();
Set<String> already = new HashSet<String>(); Set<String> already = new HashSet<String>();
List<RoleEntity> remove = new ArrayList<RoleEntity>(); List<RoleEntity> remove = new ArrayList<RoleEntity>();
for (RoleEntity rel : entities) { for (RoleEntity rel : entities) {
@ -272,7 +273,7 @@ public class ApplicationAdapter implements ApplicationModel {
@Override @Override
public void addScope(RoleModel role) { public void addScope(RoleModel role) {
realm.addScopeMapping(getAgent(), role); realm.addScopeMapping(this, role);
} }
public boolean equals(Object o) { public boolean equals(Object o) {
@ -286,4 +287,49 @@ public class ApplicationAdapter implements ApplicationModel {
public String toString() { public String toString() {
return getName(); return getName();
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
result.addAll(entity.getWebOrigins());
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
entity.setWebOrigins(webOrigins);
}
@Override
public void addWebOrigin(String webOrigin) {
entity.getWebOrigins().add(webOrigin);
}
@Override
public void removeWebOrigin(String webOrigin) {
entity.getWebOrigins().remove(webOrigin);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
result.addAll(entity.getRedirectUris());
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
entity.setRedirectUris(redirectUris);
}
@Override
public void addRedirectUri(String redirectUri) {
entity.getRedirectUris().add(redirectUri);
}
@Override
public void removeRedirectUri(String redirectUri) {
entity.getRedirectUris().remove(redirectUri);
}
} }

View file

@ -4,6 +4,9 @@ import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.jpa.entities.OAuthClientEntity; import org.keycloak.models.jpa.entities.OAuthClientEntity;
import java.util.HashSet;
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 $
@ -24,6 +27,16 @@ public class OAuthClientAdapter implements OAuthClientModel {
return entity.getId(); return entity.getId();
} }
@Override
public boolean isEnabled() {
return getAgent().isEnabled();
}
@Override
public void setEnabled(boolean enabled) {
getAgent().setEnabled(enabled);
}
@Override @Override
public UserModel getAgent() { public UserModel getAgent() {
return new UserAdapter(entity.getAgent()); return new UserAdapter(entity.getAgent());
@ -38,6 +51,51 @@ public class OAuthClientAdapter implements OAuthClientModel {
entity.setAllowedClaimsMask(mask); entity.setAllowedClaimsMask(mask);
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
result.addAll(entity.getWebOrigins());
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
entity.setWebOrigins(webOrigins);
}
@Override
public void addWebOrigin(String webOrigin) {
entity.getWebOrigins().add(webOrigin);
}
@Override
public void removeWebOrigin(String webOrigin) {
entity.getWebOrigins().remove(webOrigin);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
result.addAll(entity.getRedirectUris());
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
entity.setRedirectUris(redirectUris);
}
@Override
public void addRedirectUri(String redirectUri) {
entity.getRedirectUris().add(redirectUri);
}
@Override
public void removeRedirectUri(String redirectUri) {
entity.getRedirectUris().remove(redirectUri);
}
} }

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa; package org.keycloak.models.jpa;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.jpa.entities.ApplicationEntity; import org.keycloak.models.jpa.entities.ApplicationEntity;
import org.keycloak.models.jpa.entities.CredentialEntity; import org.keycloak.models.jpa.entities.CredentialEntity;
@ -558,6 +559,13 @@ public class RealmAdapter implements RealmModel {
em.flush(); em.flush();
} }
@Override
public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId);
if (model != null) return model;
return getOAuthClient(clientId);
}
@Override @Override
public Map<String, ApplicationModel> getApplicationNameMap() { public Map<String, ApplicationModel> getApplicationNameMap() {
Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>(); Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>();
@ -926,8 +934,8 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public boolean hasScope(UserModel user, RoleModel role) { public boolean hasScope(ClientModel client, RoleModel role) {
Set<RoleModel> roles = getScopeMappings(user); Set<RoleModel> roles = getScopeMappings(client);
if (roles.contains(role)) return true; if (roles.contains(role)) return true;
for (RoleModel mapping : roles) { for (RoleModel mapping : roles) {
@ -996,8 +1004,8 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public Set<RoleModel> getRealmScopeMappings(UserModel user) { public Set<RoleModel> getRealmScopeMappings(ClientModel client) {
Set<RoleModel> roleMappings = getScopeMappings(user); Set<RoleModel> roleMappings = getScopeMappings(client);
Set<RoleModel> appRoles = new HashSet<RoleModel>(); Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) { for (RoleModel role : roleMappings) {
@ -1014,9 +1022,9 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getScopeMappings(UserModel agent) { public Set<RoleModel> getScopeMappings(ClientModel client) {
TypedQuery<UserScopeMappingEntity> query = em.createNamedQuery("userScopeMappings", UserScopeMappingEntity.class); TypedQuery<UserScopeMappingEntity> query = em.createNamedQuery("userScopeMappings", UserScopeMappingEntity.class);
query.setParameter("user", ((UserAdapter)agent).getUser()); query.setParameter("user", ((UserAdapter)client.getAgent()).getUser());
List<UserScopeMappingEntity> entities = query.getResultList(); List<UserScopeMappingEntity> entities = query.getResultList();
Set<RoleModel> roles = new HashSet<RoleModel>(); Set<RoleModel> roles = new HashSet<RoleModel>();
for (UserScopeMappingEntity entity : entities) { for (UserScopeMappingEntity entity : entities) {
@ -1026,8 +1034,9 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public void addScopeMapping(UserModel agent, RoleModel role) { public void addScopeMapping(ClientModel client, RoleModel role) {
if (hasScope(agent, role)) return; UserModel agent = client.getAgent();
if (hasScope(client, role)) return;
UserScopeMappingEntity entity = new UserScopeMappingEntity(); UserScopeMappingEntity entity = new UserScopeMappingEntity();
entity.setUser(((UserAdapter) agent).getUser()); entity.setUser(((UserAdapter) agent).getUser());
entity.setRole(((RoleAdapter)role).getRole()); entity.setRole(((RoleAdapter)role).getRole());
@ -1035,8 +1044,9 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public void deleteScopeMapping(UserModel user, RoleModel role) { public void deleteScopeMapping(ClientModel client, RoleModel role) {
TypedQuery<UserScopeMappingEntity> query = getRealmScopeMappingQuery((UserAdapter) user, (RoleAdapter) role); UserModel agent = client.getAgent();
TypedQuery<UserScopeMappingEntity> query = getRealmScopeMappingQuery((UserAdapter) agent, (RoleAdapter) role);
List<UserScopeMappingEntity> results = query.getResultList(); List<UserScopeMappingEntity> results = query.getResultList();
if (results.size() == 0) return; if (results.size() == 0) return;
for (UserScopeMappingEntity entity : results) { for (UserScopeMappingEntity entity : results) {

View file

@ -99,49 +99,6 @@ public class UserAdapter implements UserModel {
user.getRequiredActions().remove(action); user.getRequiredActions().remove(action);
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
result.addAll(user.getWebOrigins());
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
user.setWebOrigins(webOrigins);
}
@Override
public void addWebOrigin(String webOrigin) {
user.getWebOrigins().add(webOrigin);
}
@Override
public void removeWebOrigin(String webOrigin) {
user.getWebOrigins().remove(webOrigin);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
result.addAll(user.getRedirectUris());
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
user.setRedirectUris(redirectUris);
}
@Override
public void addRedirectUri(String redirectUri) {
user.getRedirectUris().add(redirectUri);
}
@Override
public void removeRedirectUri(String redirectUri) {
user.getRedirectUris().remove(redirectUri);
}
@Override @Override
public String getFirstName() { public String getFirstName() {

View file

@ -1,6 +1,8 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -11,6 +13,8 @@ import javax.persistence.OneToMany;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
@ -35,6 +39,14 @@ public class ApplicationEntity {
@OneToOne(fetch = FetchType.EAGER) @OneToOne(fetch = FetchType.EAGER)
private UserEntity applicationUser; private UserEntity applicationUser;
@ElementCollection
@CollectionTable
protected Set<String> webOrigins = new HashSet<String>();
@ElementCollection
@CollectionTable
protected Set<String> redirectUris = new HashSet<String>();
@OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application") @OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application")
Collection<ApplicationRoleEntity> roles = new ArrayList<ApplicationRoleEntity>(); Collection<ApplicationRoleEntity> roles = new ArrayList<ApplicationRoleEntity>();
@ -128,4 +140,22 @@ public class ApplicationEntity {
public void setAllowedClaimsMask(long allowedClaimsMask) { public void setAllowedClaimsMask(long allowedClaimsMask) {
this.allowedClaimsMask = allowedClaimsMask; this.allowedClaimsMask = allowedClaimsMask;
} }
public Set<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(Set<String> webOrigins) {
this.webOrigins = webOrigins;
}
public Set<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(Set<String> redirectUris) {
this.redirectUris = redirectUris;
}
} }

View file

@ -1,5 +1,7 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -11,6 +13,9 @@ import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
import java.util.HashSet;
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 $
@ -30,6 +35,15 @@ public class OAuthClientEntity {
private String name; private String name;
private long allowedClaimsMask; private long allowedClaimsMask;
@ElementCollection
@CollectionTable
protected Set<String> webOrigins = new HashSet<String>();
@ElementCollection
@CollectionTable
protected Set<String> redirectUris = new HashSet<String>();
@OneToOne(fetch = FetchType.EAGER) @OneToOne(fetch = FetchType.EAGER)
private UserEntity agent; private UserEntity agent;
@ -72,4 +86,22 @@ public class OAuthClientEntity {
this.allowedClaimsMask = allowedClaimsMask; this.allowedClaimsMask = allowedClaimsMask;
} }
public Set<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(Set<String> webOrigins) {
this.webOrigins = webOrigins;
}
public Set<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(Set<String> redirectUris) {
this.redirectUris = redirectUris;
}
} }

View file

@ -60,14 +60,6 @@ public class UserEntity {
@CollectionTable @CollectionTable
protected Set<UserModel.RequiredAction> requiredActions = new HashSet<UserModel.RequiredAction>(); protected Set<UserModel.RequiredAction> requiredActions = new HashSet<UserModel.RequiredAction>();
@ElementCollection
@CollectionTable
protected Set<String> webOrigins = new HashSet<String>();
@ElementCollection
@CollectionTable
protected Set<String> redirectUris = new HashSet<String>();
@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true) @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
protected Collection<CredentialEntity> credentials = new ArrayList<CredentialEntity>(); protected Collection<CredentialEntity> credentials = new ArrayList<CredentialEntity>();
@ -151,22 +143,6 @@ public class UserEntity {
this.requiredActions = requiredActions; this.requiredActions = requiredActions;
} }
public Set<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(Set<String> webOrigins) {
this.webOrigins = webOrigins;
}
public Set<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(Set<String> redirectUris) {
this.redirectUris = redirectUris;
}
public RealmEntity getRealm() { public RealmEntity getRealm() {
return realm; return realm;
} }

View file

@ -3,6 +3,7 @@ package org.keycloak.models.mongo.keycloak.adapters;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.QueryBuilder; import com.mongodb.QueryBuilder;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.mongo.api.AbstractMongoIdentifiableEntity; import org.keycloak.models.mongo.api.AbstractMongoIdentifiableEntity;
@ -201,9 +202,9 @@ public class ApplicationAdapter extends AbstractAdapter implements ApplicationMo
} }
@Override @Override
public Set<RoleModel> getApplicationScopeMappings(UserModel user) { public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> result = new HashSet<RoleModel>(); Set<RoleModel> result = new HashSet<RoleModel>();
List<RoleEntity> roles = MongoModelUtils.getAllScopesOfUser(user, invocationContext); List<RoleEntity> roles = MongoModelUtils.getAllScopesOfUser(client.getAgent(), invocationContext);
for (RoleEntity role : roles) { for (RoleEntity role : roles) {
if (getId().equals(role.getApplicationId())) { if (getId().equals(role.getApplicationId())) {
@ -247,4 +248,57 @@ public class ApplicationAdapter extends AbstractAdapter implements ApplicationMo
public AbstractMongoIdentifiableEntity getMongoEntity() { public AbstractMongoIdentifiableEntity getMongoEntity() {
return application; return application;
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
if (application.getWebOrigins() != null) {
result.addAll(application.getWebOrigins());
}
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
List<String> result = new ArrayList<String>();
result.addAll(webOrigins);
application.setWebOrigins(result);
}
@Override
public void addWebOrigin(String webOrigin) {
getMongoStore().pushItemToList(application, "webOrigins", webOrigin, true, invocationContext);
}
@Override
public void removeWebOrigin(String webOrigin) {
getMongoStore().pullItemFromList(application, "webOrigins", webOrigin, invocationContext);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
if (application.getRedirectUris() != null) {
result.addAll(application.getRedirectUris());
}
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
List<String> result = new ArrayList<String>();
result.addAll(redirectUris);
application.setRedirectUris(result);
}
@Override
public void addRedirectUri(String redirectUri) {
getMongoStore().pushItemToList(application, "redirectUris", redirectUri, true, invocationContext);
}
@Override
public void removeRedirectUri(String redirectUri) {
getMongoStore().pullItemFromList(application, "redirectUris", redirectUri, invocationContext);
}
} }

View file

@ -7,6 +7,11 @@ import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.models.mongo.keycloak.entities.OAuthClientEntity; import org.keycloak.models.mongo.keycloak.entities.OAuthClientEntity;
import org.keycloak.models.mongo.keycloak.entities.UserEntity; import org.keycloak.models.mongo.keycloak.entities.UserEntity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/ */
@ -40,6 +45,16 @@ public class OAuthClientAdapter extends AbstractAdapter implements OAuthClientMo
delegate.setAllowedClaimsMask(mask); delegate.setAllowedClaimsMask(mask);
} }
@Override
public boolean isEnabled() {
return getAgent().isEnabled();
}
@Override
public void setEnabled(boolean enabled) {
getAgent().setEnabled(enabled);
}
@Override @Override
public UserModel getAgent() { public UserModel getAgent() {
// This is not thread-safe. Assumption is that OAuthClientAdapter instance is per-client object // This is not thread-safe. Assumption is that OAuthClientAdapter instance is per-client object
@ -54,4 +69,57 @@ public class OAuthClientAdapter extends AbstractAdapter implements OAuthClientMo
public AbstractMongoIdentifiableEntity getMongoEntity() { public AbstractMongoIdentifiableEntity getMongoEntity() {
return delegate; return delegate;
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
if (delegate.getWebOrigins() != null) {
result.addAll(delegate.getWebOrigins());
}
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
List<String> result = new ArrayList<String>();
result.addAll(webOrigins);
delegate.setWebOrigins(result);
}
@Override
public void addWebOrigin(String webOrigin) {
getMongoStore().pushItemToList(delegate, "webOrigins", webOrigin, true, invocationContext);
}
@Override
public void removeWebOrigin(String webOrigin) {
getMongoStore().pullItemFromList(delegate, "webOrigins", webOrigin, invocationContext);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
if (delegate.getRedirectUris() != null) {
result.addAll(delegate.getRedirectUris());
}
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
List<String> result = new ArrayList<String>();
result.addAll(redirectUris);
delegate.setRedirectUris(result);
}
@Override
public void addRedirectUri(String redirectUri) {
getMongoStore().pushItemToList(delegate, "redirectUris", redirectUri, true, invocationContext);
}
@Override
public void removeRedirectUri(String redirectUri) {
getMongoStore().pullItemFromList(delegate, "redirectUris", redirectUri, invocationContext);
}
} }

View file

@ -4,6 +4,7 @@ import com.mongodb.DBObject;
import com.mongodb.QueryBuilder; import com.mongodb.QueryBuilder;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.OAuthClientModel; import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy; import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
@ -485,6 +486,14 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
updateRealm(); updateRealm();
} }
@Override
public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId);
if (model != null) return model;
return getOAuthClient(clientId);
}
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
ApplicationEntity appData = getMongoStore().loadEntity(ApplicationEntity.class, id, invocationContext); ApplicationEntity appData = getMongoStore().loadEntity(ApplicationEntity.class, id, invocationContext);
@ -607,9 +616,9 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
} }
@Override @Override
public Set<RoleModel> getScopeMappings(UserModel user) { public Set<RoleModel> getScopeMappings(ClientModel client) {
Set<RoleModel> result = new HashSet<RoleModel>(); Set<RoleModel> result = new HashSet<RoleModel>();
List<RoleEntity> roles = MongoModelUtils.getAllScopesOfUser(user, invocationContext); List<RoleEntity> roles = MongoModelUtils.getAllScopesOfUser(client.getAgent(), invocationContext);
for (RoleEntity role : roles) { for (RoleEntity role : roles) {
if (getId().equals(role.getRealmId())) { if (getId().equals(role.getRealmId())) {
@ -623,8 +632,8 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
} }
@Override @Override
public Set<RoleModel> getRealmScopeMappings(UserModel user) { public Set<RoleModel> getRealmScopeMappings(ClientModel client) {
Set<RoleModel> allScopes = getScopeMappings(user); Set<RoleModel> allScopes = getScopeMappings(client);
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user? // Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>(); Set<RoleModel> realmRoles = new HashSet<RoleModel>();
@ -639,8 +648,8 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
} }
@Override @Override
public boolean hasScope(UserModel user, RoleModel role) { public boolean hasScope(ClientModel client, RoleModel role) {
Set<RoleModel> roles = getScopeMappings(user); Set<RoleModel> roles = getScopeMappings(client);
if (roles.contains(role)) return true; if (roles.contains(role)) return true;
for (RoleModel mapping : roles) { for (RoleModel mapping : roles) {
@ -651,14 +660,14 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
@Override @Override
public void addScopeMapping(UserModel agent, RoleModel role) { public void addScopeMapping(ClientModel client, RoleModel role) {
UserEntity userEntity = ((UserAdapter)agent).getUser(); UserEntity userEntity = ((UserAdapter)client.getAgent()).getUser();
getMongoStore().pushItemToList(userEntity, "scopeIds", role.getId(), true, invocationContext); getMongoStore().pushItemToList(userEntity, "scopeIds", role.getId(), true, invocationContext);
} }
@Override @Override
public void deleteScopeMapping(UserModel user, RoleModel role) { public void deleteScopeMapping(ClientModel client, RoleModel role) {
UserEntity userEntity = ((UserAdapter)user).getUser(); UserEntity userEntity = ((UserAdapter)client.getAgent()).getUser();
getMongoStore().pullItemFromList(userEntity, "scopeIds", role.getId(), invocationContext); getMongoStore().pullItemFromList(userEntity, "scopeIds", role.getId(), invocationContext);
} }

View file

@ -124,59 +124,6 @@ public class UserAdapter extends AbstractAdapter implements UserModel {
return user; return user;
} }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
if (user.getWebOrigins() != null) {
result.addAll(user.getWebOrigins());
}
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
List<String> result = new ArrayList<String>();
result.addAll(webOrigins);
user.setWebOrigins(result);
updateUser();
}
@Override
public void addWebOrigin(String webOrigin) {
getMongoStore().pushItemToList(user, "webOrigins", webOrigin, true, invocationContext);
}
@Override
public void removeWebOrigin(String webOrigin) {
getMongoStore().pullItemFromList(user, "webOrigins", webOrigin, invocationContext);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
if (user.getRedirectUris() != null) {
result.addAll(user.getRedirectUris());
}
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
List<String> result = new ArrayList<String>();
result.addAll(redirectUris);
user.setRedirectUris(result);
updateUser();
}
@Override
public void addRedirectUri(String redirectUri) {
getMongoStore().pushItemToList(user, "redirectUris", redirectUri, true, invocationContext);
}
@Override
public void removeRedirectUri(String redirectUri) {
getMongoStore().pullItemFromList(user, "redirectUris", redirectUri, invocationContext);
}
@Override @Override
public Set<RequiredAction> getRequiredActions() { public Set<RequiredAction> getRequiredActions() {

View file

@ -26,6 +26,9 @@ public class ApplicationEntity extends AbstractMongoIdentifiableEntity implement
private String resourceUserId; private String resourceUserId;
private String realmId; private String realmId;
private long allowedClaimsMask; private long allowedClaimsMask;
private List<String> webOrigins;
private List<String> redirectUris;
// We are using names of defaultRoles (not ids) // We are using names of defaultRoles (not ids)
private List<String> defaultRoles = new ArrayList<String>(); private List<String> defaultRoles = new ArrayList<String>();
@ -84,6 +87,26 @@ public class ApplicationEntity extends AbstractMongoIdentifiableEntity implement
this.resourceUserId = resourceUserId; this.resourceUserId = resourceUserId;
} }
@MongoField
public List<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(List<String> webOrigins) {
this.webOrigins = webOrigins;
}
@MongoField
public List<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(List<String> redirectUris) {
this.redirectUris = redirectUris;
}
@MongoField @MongoField
public long getAllowedClaimsMask() { public long getAllowedClaimsMask() {
return allowedClaimsMask; return allowedClaimsMask;

View file

@ -6,6 +6,8 @@ import org.keycloak.models.mongo.api.MongoEntity;
import org.keycloak.models.mongo.api.MongoField; import org.keycloak.models.mongo.api.MongoField;
import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
import java.util.List;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/ */
@ -17,6 +19,8 @@ public class OAuthClientEntity extends AbstractMongoIdentifiableEntity implement
private String oauthAgentId; private String oauthAgentId;
private String realmId; private String realmId;
private long allowedClaimsMask; private long allowedClaimsMask;
private List<String> webOrigins;
private List<String> redirectUris;
@MongoField @MongoField
public String getName() { public String getName() {
@ -54,6 +58,26 @@ public class OAuthClientEntity extends AbstractMongoIdentifiableEntity implement
this.allowedClaimsMask = allowedClaimsMask; this.allowedClaimsMask = allowedClaimsMask;
} }
@MongoField
public List<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(List<String> webOrigins) {
this.webOrigins = webOrigins;
}
@MongoField
public List<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(List<String> redirectUris) {
this.redirectUris = redirectUris;
}
@Override @Override
public void afterRemove(MongoStoreInvocationContext context) { public void afterRemove(MongoStoreInvocationContext context) {
// Remove user of this oauthClient // Remove user of this oauthClient

View file

@ -30,8 +30,6 @@ public class UserEntity extends AbstractMongoIdentifiableEntity implements Mongo
private List<String> scopeIds; private List<String> scopeIds;
private Map<String, String> attributes; private Map<String, String> attributes;
private List<String> webOrigins;
private List<String> redirectUris;
private List<UserModel.RequiredAction> requiredActions; private List<UserModel.RequiredAction> requiredActions;
private List<CredentialEntity> credentials = new ArrayList<CredentialEntity>(); private List<CredentialEntity> credentials = new ArrayList<CredentialEntity>();
private List<SocialLinkEntity> socialLinks; private List<SocialLinkEntity> socialLinks;
@ -135,24 +133,6 @@ public class UserEntity extends AbstractMongoIdentifiableEntity implements Mongo
this.attributes = attributes; this.attributes = attributes;
} }
@MongoField
public List<String> getWebOrigins() {
return webOrigins;
}
public void setWebOrigins(List<String> webOrigins) {
this.webOrigins = webOrigins;
}
@MongoField
public List<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(List<String> redirectUris) {
this.redirectUris = redirectUris;
}
@MongoField @MongoField
public List<UserModel.RequiredAction> getRequiredActions() { public List<UserModel.RequiredAction> getRequiredActions() {
return requiredActions; return requiredActions;

View file

@ -184,10 +184,10 @@ public class AdapterTest extends AbstractModelTest {
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); realmModel.grantRole(user, appRole);
realmModel.addScopeMapping(client.getAgent(), appRole); realmModel.addScopeMapping(client, appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
realmModel.addScopeMapping(app.getAgent(), realmRole); realmModel.addScopeMapping(app, realmRole);
Assert.assertTrue(realmModel.removeApplication(app.getId())); Assert.assertTrue(realmModel.removeApplication(app.getId()));
Assert.assertFalse(realmModel.removeApplication(app.getId())); Assert.assertFalse(realmModel.removeApplication(app.getId()));
@ -212,10 +212,10 @@ public class AdapterTest extends AbstractModelTest {
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); realmModel.grantRole(user, appRole);
realmModel.addScopeMapping(client.getAgent(), appRole); realmModel.addScopeMapping(client, appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
realmModel.addScopeMapping(app.getAgent(), realmRole); realmModel.addScopeMapping(app, realmRole);
Assert.assertTrue(identitySession.removeRealm(realmModel.getId())); Assert.assertTrue(identitySession.removeRealm(realmModel.getId()));
Assert.assertFalse(identitySession.removeRealm(realmModel.getId())); Assert.assertFalse(identitySession.removeRealm(realmModel.getId()));
@ -235,10 +235,10 @@ public class AdapterTest extends AbstractModelTest {
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); realmModel.grantRole(user, appRole);
realmModel.addScopeMapping(client.getAgent(), appRole); realmModel.addScopeMapping(client, appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
realmModel.addScopeMapping(app.getAgent(), realmRole); realmModel.addScopeMapping(app, realmRole);
Assert.assertTrue(realmModel.removeRoleById(realmRole.getId())); Assert.assertTrue(realmModel.removeRoleById(realmRole.getId()));
Assert.assertFalse(realmModel.removeRoleById(realmRole.getId())); Assert.assertFalse(realmModel.removeRoleById(realmRole.getId()));

View file

@ -37,11 +37,11 @@ public class ApplicationModelTest extends AbstractModelTest {
application.addDefaultRole("role-1"); application.addDefaultRole("role-1");
application.addDefaultRole("role-2"); application.addDefaultRole("role-2");
application.getAgent().addRedirectUri("redirect-1"); application.addRedirectUri("redirect-1");
application.getAgent().addRedirectUri("redirect-2"); application.addRedirectUri("redirect-2");
application.getAgent().addWebOrigin("origin-1"); application.addWebOrigin("origin-1");
application.getAgent().addWebOrigin("origin-2"); application.addWebOrigin("origin-2");
application.updateApplication(); application.updateApplication();
} }
@ -69,11 +69,8 @@ public class ApplicationModelTest extends AbstractModelTest {
Assert.assertEquals(expected.getManagementUrl(), actual.getManagementUrl()); Assert.assertEquals(expected.getManagementUrl(), actual.getManagementUrl());
Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles()); Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles());
UserModel auser = actual.getAgent(); Assert.assertTrue(expected.getRedirectUris().containsAll(actual.getRedirectUris()));
UserModel euser = expected.getAgent(); Assert.assertTrue(expected.getWebOrigins().containsAll(actual.getWebOrigins()));
Assert.assertTrue(euser.getRedirectUris().containsAll(auser.getRedirectUris()));
Assert.assertTrue(euser.getWebOrigins().containsAll(auser.getWebOrigins()));
} }
public static void assertEquals(List<RoleModel> expected, List<RoleModel> actual) { public static void assertEquals(List<RoleModel> expected, List<RoleModel> actual) {

View file

@ -60,7 +60,7 @@ public class CompositeRolesModelTest extends AbstractModelTest {
ApplicationModel application = realm.getApplicationByName(applicationName); ApplicationModel application = realm.getApplicationByName(applicationName);
Set<RoleModel> roleMappings = realm.getRoleMappings(user); Set<RoleModel> roleMappings = realm.getRoleMappings(user);
Set<RoleModel> scopeMappings = realm.getScopeMappings(application.getAgent()); Set<RoleModel> scopeMappings = realm.getScopeMappings(application);
Set<RoleModel> appRoles = application.getRoles(); Set<RoleModel> appRoles = application.getRoles();
if (appRoles != null) scopeMappings.addAll(appRoles); if (appRoles != null) scopeMappings.addAll(appRoles);

View file

@ -6,6 +6,7 @@ import org.junit.Test;
import org.junit.runners.MethodSorters; import org.junit.runners.MethodSorters;
import org.keycloak.models.AccountRoles; import org.keycloak.models.AccountRoles;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel; import org.keycloak.models.RequiredCredentialModel;
@ -47,8 +48,6 @@ public class ImportTest extends AbstractModelTest {
UserModel user = realm.getUser("loginclient"); UserModel user = realm.getUser("loginclient");
Assert.assertNotNull(user); Assert.assertNotNull(user);
Set<RoleModel> scopes = realm.getRealmScopeMappings(user);
Assert.assertEquals(0, scopes.size());
Assert.assertEquals(0, realm.getSocialLinks(user).size()); Assert.assertEquals(0, realm.getSocialLinks(user).size());
List<ApplicationModel> resources = realm.getApplications(); List<ApplicationModel> resources = realm.getApplications();
@ -103,7 +102,7 @@ public class ImportTest extends AbstractModelTest {
// Test scope relationship // Test scope relationship
UserModel oauthClient = realm.getUser("oauthclient"); ClientModel oauthClient = realm.findClient("oauthclient");
Assert.assertNotNull(oauthClient); Assert.assertNotNull(oauthClient);
Set<RoleModel> allScopes = realm.getScopeMappings(oauthClient); Set<RoleModel> allScopes = realm.getScopeMappings(oauthClient);
Assert.assertEquals(2, allScopes.size()); Assert.assertEquals(2, allScopes.size());

View file

@ -2,6 +2,8 @@ package org.keycloak.model.test;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction; import org.keycloak.models.UserModel.RequiredAction;
@ -19,15 +21,9 @@ public class UserModelTest extends AbstractModelTest {
user.setLastName("last-name"); user.setLastName("last-name");
user.setEmail("email"); user.setEmail("email");
user.addRedirectUri("redirect-1");
user.addRedirectUri("redirect-2");
user.addRequiredAction(RequiredAction.CONFIGURE_TOTP); user.addRequiredAction(RequiredAction.CONFIGURE_TOTP);
user.addRequiredAction(RequiredAction.UPDATE_PASSWORD); user.addRequiredAction(RequiredAction.UPDATE_PASSWORD);
user.addWebOrigin("origin-1");
user.addWebOrigin("origin-2");
UserModel persisted = realmManager.getRealm(realm.getId()).getUser("user"); UserModel persisted = realmManager.getRealm(realm.getId()).getUser("user");
assertEquals(user, persisted); assertEquals(user, persisted);
@ -39,21 +35,38 @@ public class UserModelTest extends AbstractModelTest {
@Test @Test
public void webOriginSetTest() { public void webOriginSetTest() {
RealmModel realm = realmManager.createRealm("original"); RealmModel realm = realmManager.createRealm("original");
UserModel user = realm.addUser("user"); ClientModel client = realm.addApplication("user");
Assert.assertTrue(user.getWebOrigins().isEmpty()); Assert.assertTrue(client.getWebOrigins().isEmpty());
user.addWebOrigin("origin-1"); client.addWebOrigin("origin-1");
Assert.assertEquals(1, user.getWebOrigins().size()); Assert.assertEquals(1, client.getWebOrigins().size());
user.addWebOrigin("origin-2"); client.addWebOrigin("origin-2");
Assert.assertEquals(2, user.getWebOrigins().size()); Assert.assertEquals(2, client.getWebOrigins().size());
user.removeWebOrigin("origin-2"); client.removeWebOrigin("origin-2");
Assert.assertEquals(1, user.getWebOrigins().size()); Assert.assertEquals(1, client.getWebOrigins().size());
client.removeWebOrigin("origin-1");
Assert.assertTrue(client.getWebOrigins().isEmpty());
client = realm.addOAuthClient("oauthclient2");
Assert.assertTrue(client.getWebOrigins().isEmpty());
client.addWebOrigin("origin-1");
Assert.assertEquals(1, client.getWebOrigins().size());
client.addWebOrigin("origin-2");
Assert.assertEquals(2, client.getWebOrigins().size());
client.removeWebOrigin("origin-2");
Assert.assertEquals(1, client.getWebOrigins().size());
client.removeWebOrigin("origin-1");
Assert.assertTrue(client.getWebOrigins().isEmpty());
user.removeWebOrigin("origin-1");
Assert.assertTrue(user.getWebOrigins().isEmpty());
} }
@Test @Test
@ -101,9 +114,7 @@ public class UserModelTest extends AbstractModelTest {
Assert.assertEquals(expected.getLoginName(), actual.getLoginName()); Assert.assertEquals(expected.getLoginName(), actual.getLoginName());
Assert.assertEquals(expected.getFirstName(), actual.getFirstName()); Assert.assertEquals(expected.getFirstName(), actual.getFirstName());
Assert.assertEquals(expected.getLastName(), actual.getLastName()); Assert.assertEquals(expected.getLastName(), actual.getLastName());
Assert.assertArrayEquals(expected.getRedirectUris().toArray(), actual.getRedirectUris().toArray());
Assert.assertArrayEquals(expected.getRequiredActions().toArray(), actual.getRequiredActions().toArray()); Assert.assertArrayEquals(expected.getRequiredActions().toArray(), actual.getRequiredActions().toArray());
Assert.assertArrayEquals(expected.getWebOrigins().toArray(), actual.getWebOrigins().toArray());
} }
} }

View file

@ -1,5 +1,6 @@
package org.keycloak.services.managers; package org.keycloak.services.managers;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -29,7 +30,7 @@ public class AccessCodeEntry {
protected AccessToken token; protected AccessToken token;
protected UserModel user; protected UserModel user;
protected Set<RequiredAction> requiredActions; protected Set<RequiredAction> requiredActions;
protected UserModel client; protected ClientModel client;
protected List<RoleModel> realmRolesRequested = new ArrayList<RoleModel>(); protected List<RoleModel> realmRolesRequested = new ArrayList<RoleModel>();
MultivaluedMap<String, RoleModel> resourceRolesRequested = new MultivaluedHashMap<String, RoleModel>(); MultivaluedMap<String, RoleModel> resourceRolesRequested = new MultivaluedHashMap<String, RoleModel>();
@ -73,11 +74,11 @@ public class AccessCodeEntry {
this.token = token; this.token = token;
} }
public UserModel getClient() { public ClientModel getClient() {
return client; return client;
} }
public void setClient(UserModel client) { public void setClient(ClientModel client) {
this.client = client; this.client = client;
} }

View file

@ -9,6 +9,7 @@ import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider; import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
@ -66,7 +67,7 @@ public class AppAuthManager extends AuthenticationManager {
throw new BadRequestException(); throw new BadRequestException();
} }
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) { if (!client.getLoginName().equals(accessCode.getClient().getAgent().getLoginName())) {
logger.debug("bad client"); logger.debug("bad client");
throw new BadRequestException(); throw new BadRequestException();
} }
@ -74,7 +75,7 @@ public class AppAuthManager extends AuthenticationManager {
return createLoginCookie(realm, accessCode.getUser(), accessCode.getClient(), cookieName, uri.getRawPath(), false); return createLoginCookie(realm, accessCode.getUser(), accessCode.getClient(), cookieName, uri.getRawPath(), false);
} }
public NewCookie createRefreshCookie(RealmModel realm, UserModel user, UserModel client, URI uri) { public NewCookie createRefreshCookie(RealmModel realm, UserModel user, ClientModel client, URI uri) {
return createLoginCookie(realm, user, client, cookieName, uri.getRawPath(), false); return createLoginCookie(realm, user, client, cookieName, uri.getRawPath(), false);
} }
@ -117,9 +118,9 @@ public class AppAuthManager extends AuthenticationManager {
return null; return null;
} }
UserModel client = null; ClientModel client = null;
if (token.getIssuedFor() != null) { if (token.getIssuedFor() != null) {
client = realm.getUser(token.getIssuedFor()); client = realm.findClient(token.getIssuedFor());
if (client == null || !client.isEnabled()) { if (client == null || !client.isEnabled()) {
logger.info("Unknown client in cookie"); logger.info("Unknown client in cookie");
expireCookie(cookie.getName(), cookie.getPath()); expireCookie(cookie.getName(), cookie.getPath());
@ -158,9 +159,9 @@ public class AppAuthManager extends AuthenticationManager {
throw new NotAuthorizedException("invalid_user"); throw new NotAuthorizedException("invalid_user");
} }
UserModel client = null; ClientModel client = null;
if (token.getIssuedFor() != null) { if (token.getIssuedFor() != null) {
client = realm.getUser(token.getIssuedFor()); client = realm.findClient(token.getIssuedFor());
if (client == null || !client.isEnabled()) { if (client == null || !client.isEnabled()) {
throw new NotAuthorizedException("invalid_user"); throw new NotAuthorizedException("invalid_user");
} }

View file

@ -5,6 +5,7 @@ import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.logging.Logger;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimMask; import org.keycloak.models.ClaimMask;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
@ -73,13 +74,13 @@ public class ApplicationManager {
if (resourceRep.getRedirectUris() != null) { if (resourceRep.getRedirectUris() != null) {
for (String redirectUri : resourceRep.getRedirectUris()) { for (String redirectUri : resourceRep.getRedirectUris()) {
resourceUser.addRedirectUri(redirectUri); applicationModel.addRedirectUri(redirectUri);
} }
} }
if (resourceRep.getWebOrigins() != null) { if (resourceRep.getWebOrigins() != null) {
for (String webOrigin : resourceRep.getWebOrigins()) { for (String webOrigin : resourceRep.getWebOrigins()) {
logger.debug("Application: {0} webOrigin: {1}", resourceUser.getLoginName(), webOrigin); logger.debug("Application: {0} webOrigin: {1}", resourceUser.getLoginName(), webOrigin);
resourceUser.addWebOrigin(webOrigin); applicationModel.addWebOrigin(webOrigin);
} }
} }
@ -117,13 +118,13 @@ public class ApplicationManager {
public void createScopeMappings(RealmModel realm, ApplicationModel applicationModel, List<ScopeMappingRepresentation> mappings) { public void createScopeMappings(RealmModel realm, ApplicationModel applicationModel, List<ScopeMappingRepresentation> mappings) {
for (ScopeMappingRepresentation mapping : mappings) { for (ScopeMappingRepresentation mapping : mappings) {
UserModel user = realm.getUser(mapping.getUsername());
for (String roleString : mapping.getRoles()) { for (String roleString : mapping.getRoles()) {
RoleModel role = applicationModel.getRole(roleString.trim()); RoleModel role = applicationModel.getRole(roleString.trim());
if (role == null) { if (role == null) {
role = applicationModel.addRole(roleString.trim()); role = applicationModel.addRole(roleString.trim());
} }
realm.addScopeMapping(user, role); ClientModel client = realm.findClient(mapping.getUsername());
realm.addScopeMapping(client, role);
} }
} }
} }
@ -162,12 +163,12 @@ public class ApplicationManager {
List<String> redirectUris = rep.getRedirectUris(); List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
resource.getAgent().setRedirectUris(new HashSet<String>(redirectUris)); resource.setRedirectUris(new HashSet<String>(redirectUris));
} }
List<String> webOrigins = rep.getWebOrigins(); List<String> webOrigins = rep.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
resource.getAgent().setWebOrigins(new HashSet<String>(webOrigins)); resource.setWebOrigins(new HashSet<String>(webOrigins));
} }
if (rep.getClaims() != null) { if (rep.getClaims() != null) {
@ -184,12 +185,12 @@ public class ApplicationManager {
rep.setSurrogateAuthRequired(applicationModel.isSurrogateAuthRequired()); rep.setSurrogateAuthRequired(applicationModel.isSurrogateAuthRequired());
rep.setBaseUrl(applicationModel.getBaseUrl()); rep.setBaseUrl(applicationModel.getBaseUrl());
Set<String> redirectUris = applicationModel.getAgent().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.getAgent().getWebOrigins(); Set<String> webOrigins = applicationModel.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
rep.setWebOrigins(new LinkedList<String>(webOrigins)); rep.setWebOrigins(new LinkedList<String>(webOrigins));
} }

View file

@ -1,5 +1,6 @@
package org.keycloak.services.managers; package org.keycloak.services.managers;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
@ -13,9 +14,9 @@ public class Auth {
private final RealmModel realm; private final RealmModel realm;
private final AccessToken token; private final AccessToken token;
private final UserModel user; private final UserModel user;
private final UserModel client; private final ClientModel client;
public Auth(RealmModel realm, UserModel user, UserModel client) { public Auth(RealmModel realm, UserModel user, ClientModel client) {
this.cookie = true; this.cookie = true;
this.realm = realm; this.realm = realm;
this.token = null; this.token = null;
@ -24,7 +25,7 @@ public class Auth {
this.client = client; this.client = client;
} }
public Auth(AccessToken token, UserModel user, UserModel client) { public Auth(AccessToken token, UserModel user, ClientModel client) {
this.cookie = false; this.cookie = false;
this.token = token; this.token = token;
this.realm = null; this.realm = null;
@ -45,7 +46,7 @@ public class Auth {
return user; return user;
} }
public UserModel getClient() { public ClientModel getClient() {
return client; return client;
} }

View file

@ -6,6 +6,7 @@ import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.RSATokenVerifier; import org.keycloak.RSATokenVerifier;
import org.keycloak.VerificationException; import org.keycloak.VerificationException;
import org.keycloak.jose.jws.JWSBuilder; import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel; import org.keycloak.models.RequiredCredentialModel;
@ -56,10 +57,10 @@ public class AuthenticationManager {
return createLoginCookie(realm, user, null, cookieName, cookiePath, rememberMe); return createLoginCookie(realm, user, null, cookieName, cookiePath, rememberMe);
} }
protected NewCookie createLoginCookie(RealmModel realm, UserModel user, UserModel client, String cookieName, String cookiePath, boolean rememberMe) { protected NewCookie createLoginCookie(RealmModel realm, UserModel user, ClientModel client, String cookieName, String cookiePath, boolean rememberMe) {
AccessToken identityToken = createIdentityToken(realm, user); AccessToken identityToken = createIdentityToken(realm, user);
if (client != null) { if (client != null) {
identityToken.issuedFor(client.getLoginName()); identityToken.issuedFor(client.getAgent().getLoginName());
} }
String encoded = encodeToken(realm, identityToken); String encoded = encodeToken(realm, identityToken);
boolean secureOnly = !realm.isSslNotRequired(); boolean secureOnly = !realm.isSslNotRequired();

View file

@ -72,12 +72,12 @@ public class OAuthClientManager {
model.getAgent().setEnabled(rep.isEnabled()); model.getAgent().setEnabled(rep.isEnabled());
List<String> redirectUris = rep.getRedirectUris(); List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
model.getAgent().setRedirectUris(new HashSet<String>(redirectUris)); model.setRedirectUris(new HashSet<String>(redirectUris));
} }
List<String> webOrigins = rep.getWebOrigins(); List<String> webOrigins = rep.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
model.getAgent().setWebOrigins(new HashSet<String>(webOrigins)); model.setWebOrigins(new HashSet<String>(webOrigins));
} }
if (rep.getClaims() != null) { if (rep.getClaims() != null) {
@ -90,12 +90,12 @@ public class OAuthClientManager {
rep.setId(model.getId()); rep.setId(model.getId());
rep.setName(model.getAgent().getLoginName()); rep.setName(model.getAgent().getLoginName());
rep.setEnabled(model.getAgent().isEnabled()); rep.setEnabled(model.getAgent().isEnabled());
Set<String> redirectUris = model.getAgent().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.getAgent().getWebOrigins(); Set<String> webOrigins = model.getWebOrigins();
if (webOrigins != null) { if (webOrigins != null) {
rep.setWebOrigins(new LinkedList<String>(webOrigins)); rep.setWebOrigins(new LinkedList<String>(webOrigins));
} }

View file

@ -4,6 +4,7 @@ import org.jboss.resteasy.logging.Logger;
import org.keycloak.models.AccountRoles; import org.keycloak.models.AccountRoles;
import org.keycloak.models.AdminRoles; import org.keycloak.models.AdminRoles;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuthClientModel; import org.keycloak.models.OAuthClientModel;
@ -361,7 +362,8 @@ public class RealmManager {
role = newRealm.addRole(roleString.trim()); role = newRealm.addRole(roleString.trim());
} }
UserModel user = userMap.get(scope.getUsername()); UserModel user = userMap.get(scope.getUsername());
newRealm.addScopeMapping(user, role); ClientModel client = newRealm.findClient(user.getLoginName());
newRealm.addScopeMapping(client, role);
} }
} }

View file

@ -87,13 +87,13 @@ public class TokenManager {
public AccessCodeEntry createAccessCode(String scopeParam, String state, String redirect, RealmModel realm, UserModel client, UserModel user) { public AccessCodeEntry createAccessCode(String scopeParam, String state, String redirect, RealmModel realm, ClientModel client, UserModel user) {
AccessCodeEntry code = createAccessCodeEntry(scopeParam, state, redirect, realm, client, user); AccessCodeEntry code = createAccessCodeEntry(scopeParam, state, redirect, realm, client, user);
accessCodeMap.put(code.getId(), code); accessCodeMap.put(code.getId(), code);
return code; return code;
} }
private AccessCodeEntry createAccessCodeEntry(String scopeParam, String state, String redirect, RealmModel realm, UserModel client, UserModel user) { private AccessCodeEntry createAccessCodeEntry(String scopeParam, String state, String redirect, RealmModel realm, ClientModel client, UserModel user) {
AccessCodeEntry code = new AccessCodeEntry(); AccessCodeEntry code = new AccessCodeEntry();
List<RoleModel> realmRolesRequested = code.getRealmRolesRequested(); List<RoleModel> realmRolesRequested = code.getRealmRolesRequested();
MultivaluedMap<String, RoleModel> resourceRolesRequested = code.getResourceRolesRequested(); MultivaluedMap<String, RoleModel> resourceRolesRequested = code.getResourceRolesRequested();
@ -117,7 +117,7 @@ public class TokenManager {
return code; return code;
} }
public AccessToken refreshAccessToken(RealmModel realm, UserModel client, String encodedRefreshToken) throws OAuthErrorException { public AccessToken refreshAccessToken(RealmModel realm, ClientModel client, String encodedRefreshToken) throws OAuthErrorException {
JWSInput jws = new JWSInput(encodedRefreshToken); JWSInput jws = new JWSInput(encodedRefreshToken);
RefreshToken refreshToken = null; RefreshToken refreshToken = null;
try { try {
@ -142,7 +142,7 @@ public class TokenManager {
} }
ApplicationModel clientApp = realm.getApplicationByName(client.getLoginName()); ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null;
if (refreshToken.getRealmAccess() != null) { if (refreshToken.getRealmAccess() != null) {
@ -180,15 +180,14 @@ public class TokenManager {
} }
} }
ClientModel claimRequesterModel = getClaimRequester(realm, client);
AccessToken accessToken = initToken(realm, claimRequesterModel, client, user); AccessToken accessToken = initToken(realm, client, user);
accessToken.setRealmAccess(refreshToken.getRealmAccess()); accessToken.setRealmAccess(refreshToken.getRealmAccess());
accessToken.setResourceAccess(refreshToken.getResourceAccess()); accessToken.setResourceAccess(refreshToken.getResourceAccess());
return accessToken; return accessToken;
} }
public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, UserModel client, UserModel user) { public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, ClientModel client, UserModel user) {
return createClientAccessToken(scopeParam, realm, client, user, new LinkedList<RoleModel>(), new MultivaluedHashMap<String, RoleModel>()); return createClientAccessToken(scopeParam, realm, client, user, new LinkedList<RoleModel>(), new MultivaluedHashMap<String, RoleModel>());
} }
@ -199,15 +198,14 @@ public class TokenManager {
} }
public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, UserModel client, UserModel user, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) { public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, ClientModel client, UserModel user, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) {
AccessScope scopeMap = null; AccessScope scopeMap = null;
if (scopeParam != null) scopeMap = decodeScope(scopeParam); if (scopeParam != null) scopeMap = decodeScope(scopeParam);
Set<RoleModel> roleMappings = realm.getRoleMappings(user); Set<RoleModel> roleMappings = realm.getRoleMappings(user);
Set<RoleModel> scopeMappings = realm.getScopeMappings(client); Set<RoleModel> scopeMappings = realm.getScopeMappings(client);
ClientModel claimRequesterModel = getClaimRequester(realm, client); ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null;
ApplicationModel clientApp = realm.getApplicationByName(client.getLoginName());
Set<RoleModel> clientAppRoles = clientApp == null ? null : clientApp.getRoles(); Set<RoleModel> clientAppRoles = clientApp == null ? null : clientApp.getRoles();
if (clientAppRoles != null) scopeMappings.addAll(clientAppRoles); if (clientAppRoles != null) scopeMappings.addAll(clientAppRoles);
@ -233,7 +231,7 @@ public class TokenManager {
} }
} }
AccessToken token = initToken(realm, claimRequesterModel, client, user); AccessToken token = initToken(realm, client, user);
if (realmRolesRequested.size() > 0) { if (realmRolesRequested.size() > 0) {
for (RoleModel role : realmRolesRequested) { for (RoleModel role : realmRolesRequested) {
@ -286,13 +284,13 @@ public class TokenManager {
protected AccessToken initToken(RealmModel realm, ClientModel claimer, UserModel client, UserModel user) { protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user) {
AccessToken token = new AccessToken(); AccessToken token = new AccessToken();
token.id(KeycloakModelUtils.generateId()); token.id(KeycloakModelUtils.generateId());
token.subject(user.getId()); token.subject(user.getId());
token.audience(realm.getName()); token.audience(realm.getName());
token.issuedNow(); token.issuedNow();
token.issuedFor(client.getLoginName()); token.issuedFor(client.getAgent().getLoginName());
token.issuer(realm.getName()); token.issuer(realm.getName());
if (realm.getAccessTokenLifespan() > 0) { if (realm.getAccessTokenLifespan() > 0) {
token.expiration((System.currentTimeMillis() / 1000) + realm.getAccessTokenLifespan()); token.expiration((System.currentTimeMillis() / 1000) + realm.getAccessTokenLifespan());
@ -301,7 +299,7 @@ public class TokenManager {
if (allowedOrigins != null) { if (allowedOrigins != null) {
token.setAllowedOrigins(allowedOrigins); token.setAllowedOrigins(allowedOrigins);
} }
initClaims(token, claimer, user); initClaims(token, client, user);
return token; return token;
} }
@ -385,7 +383,7 @@ public class TokenManager {
return this; return this;
} }
public AccessTokenResponseBuilder generateAccessToken(String scopeParam, UserModel client, UserModel user) { public AccessTokenResponseBuilder generateAccessToken(String scopeParam, ClientModel client, UserModel user) {
accessToken = createClientAccessToken(scopeParam, realm, client, user); accessToken = createClientAccessToken(scopeParam, realm, client, user);
return this; return this;
} }

View file

@ -7,6 +7,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.ResponseBuilder;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.models.ClientModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
/** /**
@ -52,7 +53,7 @@ public class Cors {
return this; return this;
} }
public Cors allowedOrigins(UserModel client) { public Cors allowedOrigins(ClientModel client) {
if (client != null) { if (client != null) {
allowedOrigins = client.getWebOrigins(); allowedOrigins = client.getWebOrigins();
} }

View file

@ -26,6 +26,7 @@ import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.login.LoginForms; import org.keycloak.login.LoginForms;
import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider; import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -244,7 +245,7 @@ public class RequiredActionsService {
String redirect = uriInfo.getQueryParameters().getFirst("redirect_uri"); String redirect = uriInfo.getQueryParameters().getFirst("redirect_uri");
String clientId = uriInfo.getQueryParameters().getFirst("client_id"); String clientId = uriInfo.getQueryParameters().getFirst("client_id");
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
return Flows.oauth(realm, request, uriInfo, authManager, tokenManager).forwardToSecurityFailure( return Flows.oauth(realm, request, uriInfo, authManager, tokenManager).forwardToSecurityFailure(
"Unknown login requester."); "Unknown login requester.");

View file

@ -24,6 +24,7 @@ package org.keycloak.services.resources;
import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.HttpResponse;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.SocialLinkModel; import org.keycloak.models.SocialLinkModel;
@ -117,7 +118,7 @@ public class SocialResource {
String clientId = requestData.getClientAttributes().get("clientId"); String clientId = requestData.getClientAttributes().get("clientId");
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
} }
@ -192,7 +193,7 @@ public class SocialResource {
SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri); SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester: " + clientId); logger.warn("Unknown login requester: " + clientId);
return Flows.forms(realm, request, uriInfo).setError("Unknown login requester.").createErrorPage(); return Flows.forms(realm, request, uriInfo).setError("Unknown login requester.").createErrorPage();

View file

@ -8,6 +8,7 @@ import org.keycloak.OAuthErrorException;
import org.keycloak.jose.jws.JWSBuilder; import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider; import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction; import org.keycloak.models.KeycloakTransaction;
@ -137,7 +138,7 @@ public class TokenService {
throw new NotAcceptableException("HTTPS required"); throw new NotAcceptableException("HTTPS required");
} }
UserModel client = authorizeClient(authorizationHeader); ClientModel client = authorizeClient(authorizationHeader);
String username = form.getFirst(AuthenticationManager.FORM_USERNAME); String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
@ -176,7 +177,7 @@ public class TokenService {
throw new NotAcceptableException("HTTPS required"); throw new NotAcceptableException("HTTPS required");
} }
UserModel client = authorizeClient(authorizationHeader); ClientModel client = authorizeClient(authorizationHeader);
String refreshToken = form.getFirst("refresh_token"); String refreshToken = form.getFirst("refresh_token");
AccessToken accessToken = null; AccessToken accessToken = null;
try { try {
@ -211,7 +212,7 @@ public class TokenService {
if (!realm.isEnabled()) { if (!realm.isEnabled()) {
return oauth.forwardToSecurityFailure("Realm not enabled."); return oauth.forwardToSecurityFailure("Realm not enabled.");
} }
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
} }
@ -282,7 +283,7 @@ public class TokenService {
logger.warn("Realm not enabled"); logger.warn("Realm not enabled");
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester."); logger.warn("Unknown login requester.");
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
@ -355,7 +356,7 @@ public class TokenService {
throw new NotAuthorizedException("Realm not enabled"); throw new NotAuthorizedException("Realm not enabled");
} }
UserModel client = authorizeClient(authorizationHeader); ClientModel client = authorizeClient(authorizationHeader);
String code = formData.getFirst("code"); String code = formData.getFirst("code");
if (code == null) { if (code == null) {
@ -403,7 +404,7 @@ public class TokenService {
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res) return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build(); .build();
} }
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) { if (!client.getAgent().getLoginName().equals(accessCode.getClient().getAgent().getLoginName())) {
Map<String, String> res = new HashMap<String, String>(); Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant"); res.put("error", "invalid_grant");
res.put("error_description", "Auth error"); res.put("error_description", "Auth error");
@ -419,7 +420,7 @@ public class TokenService {
return Cors.add(request, Response.ok(res)).allowedOrigins(client).allowedMethods("POST").build(); return Cors.add(request, Response.ok(res)).allowedOrigins(client).allowedMethods("POST").build();
} }
protected UserModel authorizeClient(String authorizationHeader) { protected ClientModel authorizeClient(String authorizationHeader) {
if (authorizationHeader == null) { if (authorizationHeader == null) {
throw new NotAuthorizedException("No Authorization header to authenticate client", "Basic realm=\"" + realm.getName() + "\""); throw new NotAuthorizedException("No Authorization header to authenticate client", "Basic realm=\"" + realm.getName() + "\"");
} }
@ -431,7 +432,7 @@ public class TokenService {
String client_id = usernameSecret[0]; String client_id = usernameSecret[0];
String clientSecret = usernameSecret[1]; String clientSecret = usernameSecret[1];
UserModel client = realm.getUser(client_id); ClientModel client = realm.findClient(client_id);
if (client == null) { if (client == null) {
Map<String, String> error = new HashMap<String, String>(); Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client"); error.put("error", "invalid_client");
@ -446,7 +447,7 @@ public class TokenService {
throw new BadRequestException("Client is not enabled", Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build()); throw new BadRequestException("Client is not enabled", Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build());
} }
if (!realm.validateSecret(client, clientSecret)) { if (!realm.validateSecret(client.getAgent(), clientSecret)) {
Map<String, String> error = new HashMap<String, String>(); Map<String, String> error = new HashMap<String, String>();
error.put("error", "unauthorized_client"); error.put("error", "unauthorized_client");
throw new BadRequestException("Unauthorized Client", Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build()); throw new BadRequestException("Unauthorized Client", Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build());
@ -470,7 +471,7 @@ public class TokenService {
logger.warn("Realm not enabled"); logger.warn("Realm not enabled");
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester: " + clientId); logger.warn("Unknown login requester: " + clientId);
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
@ -488,8 +489,8 @@ public class TokenService {
logger.info("Checking roles..."); logger.info("Checking roles...");
RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE); RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE);
RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE); RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client, resourceRole); boolean isResource = realm.hasRole(client.getAgent(), resourceRole);
if (!isResource && !realm.hasRole(client, identityRequestRole)) { if (!isResource && !realm.hasRole(client.getAgent(), identityRequestRole)) {
logger.warn("Login requester not allowed to request login."); logger.warn("Login requester not allowed to request login.");
return oauth.forwardToSecurityFailure("Login requester not allowed to request login."); return oauth.forwardToSecurityFailure("Login requester not allowed to request login.");
} }
@ -523,7 +524,7 @@ public class TokenService {
logger.warn("Realm not enabled"); logger.warn("Realm not enabled");
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester."); logger.warn("Unknown login requester.");
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
@ -615,7 +616,7 @@ public class TokenService {
return location.build(); return location.build();
} }
public static String verifyRedirectUri(String redirectUri, UserModel client) { public static String verifyRedirectUri(String redirectUri, ClientModel client) {
if (redirectUri == null) { if (redirectUri == null) {
return client.getRedirectUris().size() == 1 ? client.getRedirectUris().iterator().next() : null; return client.getRedirectUris().size() == 1 ? client.getRedirectUris().iterator().next() : null;
} else if (client.getRedirectUris().isEmpty()) { } else if (client.getRedirectUris().isEmpty()) {

View file

@ -145,7 +145,7 @@ public class ApplicationResource {
@Path("scope-mappings") @Path("scope-mappings")
public ScopeMappedResource getScopeMappedResource() { public ScopeMappedResource getScopeMappedResource() {
return new ScopeMappedResource(realm, auth, application.getAgent(), session); return new ScopeMappedResource(realm, auth, application, session);
} }
@Path("roles") @Path("roles")
@ -160,7 +160,7 @@ public class ApplicationResource {
{ {
auth.requireView(); auth.requireView();
return application.getAgent().getWebOrigins(); return application.getWebOrigins();
} }
@Path("allowed-origins") @Path("allowed-origins")
@ -170,7 +170,7 @@ public class ApplicationResource {
{ {
auth.requireManage(); auth.requireManage();
application.getAgent().setWebOrigins(allowedOrigins); application.setWebOrigins(allowedOrigins);
} }
@Path("allowed-origins") @Path("allowed-origins")
@ -181,7 +181,7 @@ public class ApplicationResource {
auth.requireManage(); auth.requireManage();
for (String origin : allowedOrigins) { for (String origin : allowedOrigins) {
application.getAgent().removeWebOrigin(origin); application.removeWebOrigin(origin);
} }
} }

View file

@ -131,7 +131,7 @@ public class OAuthClientResource {
@Path("scope-mappings") @Path("scope-mappings")
public ScopeMappedResource getScopeMappedResource() { public ScopeMappedResource getScopeMappedResource() {
return new ScopeMappedResource(realm, auth, oauthClient.getAgent(), session); return new ScopeMappedResource(realm, auth, oauthClient, session);
} }

View file

@ -2,6 +2,7 @@ package org.keycloak.services.resources.admin;
import org.jboss.resteasy.annotations.cache.NoCache; import org.jboss.resteasy.annotations.cache.NoCache;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
@ -33,13 +34,13 @@ import java.util.Set;
public class ScopeMappedResource { public class ScopeMappedResource {
protected RealmModel realm; protected RealmModel realm;
private RealmAuth auth; private RealmAuth auth;
protected UserModel agent; protected ClientModel client;
protected KeycloakSession session; protected KeycloakSession session;
public ScopeMappedResource(RealmModel realm, RealmAuth auth, UserModel account, KeycloakSession session) { public ScopeMappedResource(RealmModel realm, RealmAuth auth, ClientModel client, KeycloakSession session) {
this.realm = realm; this.realm = realm;
this.auth = auth; this.auth = auth;
this.agent = account; this.client = client;
this.session = session; this.session = session;
} }
@ -50,7 +51,7 @@ public class ScopeMappedResource {
auth.requireView(); auth.requireView();
MappingsRepresentation all = new MappingsRepresentation(); MappingsRepresentation all = new MappingsRepresentation();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(agent); Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client);
RealmManager manager = new RealmManager(session); RealmManager manager = new RealmManager(session);
if (realmMappings.size() > 0) { if (realmMappings.size() > 0) {
List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>();
@ -64,7 +65,7 @@ public class ScopeMappedResource {
if (applications.size() > 0) { if (applications.size() > 0) {
Map<String, ApplicationMappingsRepresentation> appMappings = new HashMap<String, ApplicationMappingsRepresentation>(); Map<String, ApplicationMappingsRepresentation> appMappings = new HashMap<String, ApplicationMappingsRepresentation>();
for (ApplicationModel app : applications) { for (ApplicationModel app : applications) {
Set<RoleModel> roleMappings = app.getApplicationScopeMappings(agent); Set<RoleModel> roleMappings = app.getApplicationScopeMappings(client);
if (roleMappings.size() > 0) { if (roleMappings.size() > 0) {
ApplicationMappingsRepresentation mappings = new ApplicationMappingsRepresentation(); ApplicationMappingsRepresentation mappings = new ApplicationMappingsRepresentation();
mappings.setApplicationId(app.getId()); mappings.setApplicationId(app.getId());
@ -89,7 +90,7 @@ public class ScopeMappedResource {
public List<RoleRepresentation> getRealmScopeMappings() { public List<RoleRepresentation> getRealmScopeMappings() {
auth.requireView(); auth.requireView();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(agent); Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client);
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
RealmManager manager = new RealmManager(session); RealmManager manager = new RealmManager(session);
for (RoleModel roleModel : realmMappings) { for (RoleModel roleModel : realmMappings) {
@ -109,7 +110,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException(); throw new NotFoundException();
} }
realm.addScopeMapping(agent, roleModel); realm.addScopeMapping(client, roleModel);
} }
@ -122,9 +123,9 @@ public class ScopeMappedResource {
auth.requireManage(); auth.requireManage();
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = realm.getRealmScopeMappings(agent); Set<RoleModel> roleModels = realm.getRealmScopeMappings(client);
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(agent, roleModel); realm.deleteScopeMapping(client, roleModel);
} }
} else { } else {
@ -133,7 +134,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException(); throw new NotFoundException();
} }
realm.deleteScopeMapping(agent, roleModel); realm.deleteScopeMapping(client, roleModel);
} }
} }
} }
@ -151,7 +152,7 @@ public class ScopeMappedResource {
throw new NotFoundException(); throw new NotFoundException();
} }
Set<RoleModel> mappings = app.getApplicationScopeMappings(agent); Set<RoleModel> mappings = app.getApplicationScopeMappings(client);
List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : mappings) { for (RoleModel roleModel : mappings) {
mapRep.add(ModelToRepresentation.toRepresentation(roleModel)); mapRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -176,7 +177,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException(); throw new NotFoundException();
} }
realm.addScopeMapping(agent, roleModel); realm.addScopeMapping(client, roleModel);
} }
} }
@ -194,9 +195,9 @@ public class ScopeMappedResource {
} }
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = app.getApplicationScopeMappings(agent); Set<RoleModel> roleModels = app.getApplicationScopeMappings(client);
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(agent, roleModel); realm.deleteScopeMapping(client, roleModel);
} }
} else { } else {
@ -205,7 +206,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException(); throw new NotFoundException();
} }
realm.deleteScopeMapping(agent, roleModel); realm.deleteScopeMapping(client, roleModel);
} }
} }
} }

View file

@ -3,6 +3,7 @@ package org.keycloak.services.resources.admin;
import org.jboss.resteasy.annotations.cache.NoCache; import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.logging.Logger;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
@ -467,7 +468,7 @@ public class UsersResource {
String state = null; String state = null;
String scope = null; String scope = null;
UserModel client = realm.getUser(clientId); ClientModel client = realm.findClient(clientId);
if (client == null || !client.isEnabled()) { if (client == null || !client.isEnabled()) {
return Flows.errors().error("Account management not enabled", Response.Status.INTERNAL_SERVER_ERROR); return Flows.errors().error("Account management not enabled", Response.Status.INTERNAL_SERVER_ERROR);
} }

View file

@ -23,6 +23,7 @@ package org.keycloak.services.resources.flows;
import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.models.OAuthClientModel; import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
@ -88,7 +89,7 @@ public class OAuthFlows {
return location.build(); return location.build();
} }
public Response redirectError(UserModel client, String error, String state, String redirect) { public Response redirectError(ClientModel client, String error, String state, String redirect) {
UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("error", error); UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("error", error);
if (state != null) { if (state != null) {
redirectUri.queryParam("state", state); redirectUri.queryParam("state", state);
@ -97,19 +98,19 @@ public class OAuthFlows {
return Response.status(302).location(redirectUri.build()).build(); return Response.status(302).location(redirectUri.build()).build();
} }
public Response processAccessCode(String scopeParam, String state, String redirect, UserModel client, UserModel user) { public Response processAccessCode(String scopeParam, String state, String redirect, ClientModel client, UserModel user) {
return processAccessCode(scopeParam, state, redirect, client, user, false); return processAccessCode(scopeParam, state, redirect, client, user, false);
} }
public Response processAccessCode(String scopeParam, String state, String redirect, UserModel client, UserModel user, boolean rememberMe) { public Response processAccessCode(String scopeParam, String state, String redirect, ClientModel client, UserModel user, boolean rememberMe) {
isTotpConfigurationRequired(user); isTotpConfigurationRequired(user);
isEmailVerificationRequired(user); isEmailVerificationRequired(user);
RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE); RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE);
RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE); RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client, resourceRole); boolean isResource = realm.hasRole(client.getAgent(), resourceRole);
if (!isResource && !realm.hasRole(client, identityRequestRole)) { if (!isResource && !realm.hasRole(client.getAgent(), identityRequestRole)) {
return forwardToSecurityFailure("Login requester not allowed to request login."); return forwardToSecurityFailure("Login requester not allowed to request login.");
} }
AccessCodeEntry accessCode = tokenManager.createAccessCode(scopeParam, state, redirect, realm, client, user); AccessCodeEntry accessCode = tokenManager.createAccessCode(scopeParam, state, redirect, realm, client, user);
@ -128,7 +129,7 @@ public class OAuthFlows {
if (!isResource if (!isResource
&& (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested().size() > 0)) { && (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested().size() > 0)) {
OAuthClientModel oauthClient = realm.getOAuthClient(client.getLoginName()); OAuthClientModel oauthClient = realm.getOAuthClient(client.getAgent().getLoginName());
accessCode.setExpiration(System.currentTimeMillis() / 1000 + realm.getAccessCodeLifespanUserAction()); accessCode.setExpiration(System.currentTimeMillis() / 1000 + realm.getAccessCodeLifespanUserAction());
return Flows.forms(realm, request, uriInfo).setAccessCode(accessCode.getId(), accessCode.getCode()). return Flows.forms(realm, request, uriInfo).setAccessCode(accessCode.getId(), accessCode.getCode()).
setAccessRequest(accessCode.getRealmRolesRequested(), accessCode.getResourceRolesRequested()). setAccessRequest(accessCode.getRealmRolesRequested(), accessCode.getResourceRolesRequested()).

View file

@ -12,6 +12,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.keycloak.models.AccountRoles; import org.keycloak.models.AccountRoles;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -65,11 +66,11 @@ public class ProfileTest {
appRealm.updateCredential(user2, creds); appRealm.updateCredential(user2, creds);
ApplicationModel app = appRealm.getApplicationNameMap().get("test-app"); ApplicationModel app = appRealm.getApplicationNameMap().get("test-app");
appRealm.addScopeMapping(app.getAgent(), accountApp.getRole(AccountRoles.VIEW_PROFILE)); appRealm.addScopeMapping(app, accountApp.getRole(AccountRoles.VIEW_PROFILE));
app.getAgent().addWebOrigin("http://localtest.me:8081"); app.addWebOrigin("http://localtest.me:8081");
UserModel thirdParty = appRealm.getUser("third-party"); ClientModel thirdParty = appRealm.findClient("third-party");
appRealm.addScopeMapping(thirdParty, accountApp.getRole(AccountRoles.VIEW_PROFILE)); appRealm.addScopeMapping(thirdParty, accountApp.getRole(AccountRoles.VIEW_PROFILE));
} }
}); });

View file

@ -82,8 +82,7 @@ public class AuthorizationCodeTest {
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
for (ApplicationModel app : appRealm.getApplications()) { for (ApplicationModel app : appRealm.getApplications()) {
if (app.getName().equals("test-app")) { if (app.getName().equals("test-app")) {
UserModel client = app.getAgent(); app.addRedirectUri(oauth.getRedirectUri());
client.addRedirectUri(oauth.getRedirectUri());
} }
} }
} }

View file

@ -48,7 +48,7 @@ public class OAuthRedirectUriTest {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
ApplicationModel app = appRealm.getApplicationNameMap().get("test-app"); ApplicationModel app = appRealm.getApplicationNameMap().get("test-app");
app.getAgent().addRedirectUri("http://localhost:8081/app"); app.addRedirectUri("http://localhost:8081/app");
} }
}); });
@ -81,7 +81,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().addRedirectUri("http://localhost:8081/app2"); appRealm.getApplicationNameMap().get("test-app").addRedirectUri("http://localhost:8081/app2");
} }
}); });
@ -95,7 +95,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().removeRedirectUri("http://localhost:8081/app2"); appRealm.getApplicationNameMap().get("test-app").removeRedirectUri("http://localhost:8081/app2");
} }
}); });
} }
@ -106,7 +106,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().removeRedirectUri("http://localhost:8081/app"); appRealm.getApplicationNameMap().get("test-app").removeRedirectUri("http://localhost:8081/app");
} }
}); });
@ -120,7 +120,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().addRedirectUri("http://localhost:8081/app"); appRealm.getApplicationNameMap().get("test-app").addRedirectUri("http://localhost:8081/app");
} }
}); });
} }
@ -131,7 +131,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().removeRedirectUri("http://localhost:8081/app"); appRealm.getApplicationNameMap().get("test-app").removeRedirectUri("http://localhost:8081/app");
} }
}); });
@ -144,7 +144,7 @@ public class OAuthRedirectUriTest {
keycloakRule.configure(new KeycloakRule.KeycloakSetup() { keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override @Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getApplicationNameMap().get("test-app").getAgent().addRedirectUri("http://localhost:8081/app"); appRealm.getApplicationNameMap().get("test-app").addRedirectUri("http://localhost:8081/app");
} }
}); });
} }

View file

@ -3,6 +3,7 @@ package org.keycloak.testsuite.performance;
import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger; import org.apache.log.Logger;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.SocialLinkModel; import org.keycloak.models.SocialLinkModel;
@ -95,7 +96,8 @@ public class ReadUsersWorker implements Worker {
// Read scopes of user in realm // Read scopes of user in realm
if (readScopes) { if (readScopes) {
realm.getScopeMappings(user); ClientModel client = realm.findClient(username);
realm.getScopeMappings(client);
} }
// Validate password (shoould be same as username) // Validate password (shoould be same as username)