remove clientmodel.agent phase1

This commit is contained in:
Bill Burke 2014-02-27 13:55:04 -05:00
parent f8da693fd0
commit 3fc273070e
29 changed files with 63 additions and 319 deletions

View file

@ -61,7 +61,7 @@ public class OAuthGrantBean {
} }
public String getClient() { public String getClient() {
return client.getAgent().getLoginName(); return client.getClientId();
} }
} }

View file

@ -7,8 +7,20 @@ import java.util.Set;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
public interface ClientModel { public interface ClientModel {
/**
* Internal database key
*
* @return
*/
String getId(); String getId();
/**
* String exposed to outside world
*
* @return
*/
String getClientId();
UserModel getAgent(); UserModel getAgent();
long getAllowedClaimsMask(); long getAllowedClaimsMask();

View file

@ -9,8 +9,6 @@ public interface Constants {
String ADMIN_CONSOLE_APPLICATION = "admin-console"; String ADMIN_CONSOLE_APPLICATION = "admin-console";
String INTERNAL_ROLE = "KEYCLOAK_"; String INTERNAL_ROLE = "KEYCLOAK_";
String APPLICATION_ROLE = INTERNAL_ROLE + "_APPLICATION";
String IDENTITY_REQUESTER_ROLE = INTERNAL_ROLE + "_IDENTITY_REQUESTER";
String ACCOUNT_MANAGEMENT_APP = "account"; String ACCOUNT_MANAGEMENT_APP = "account";
} }

View file

@ -117,24 +117,11 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
boolean removeApplication(String id); boolean removeApplication(String id);
List<RequiredCredentialModel> getRequiredApplicationCredentials();
List<RequiredCredentialModel> getRequiredOAuthClientCredentials();
ApplicationModel getApplicationById(String id); ApplicationModel getApplicationById(String id);
ApplicationModel getApplicationByName(String name); ApplicationModel getApplicationByName(String name);
void addRequiredOAuthClientCredential(String type);
void addRequiredResourceCredential(String type);
void updateRequiredCredentials(Set<String> creds); void updateRequiredCredentials(Set<String> creds);
void updateRequiredOAuthClientCredentials(Set<String> creds);
void updateRequiredApplicationCredentials(Set<String> creds);
UserModel getUserBySocialLink(SocialLinkModel socialLink); UserModel getUserBySocialLink(SocialLinkModel socialLink);
Set<SocialLinkModel> getSocialLinks(UserModel user); Set<SocialLinkModel> getSocialLinks(UserModel user);

View file

@ -48,6 +48,11 @@ public class ApplicationAdapter implements ApplicationModel {
return entity.getId(); return entity.getId();
} }
@Override
public String getClientId() {
return getName();
}
@Override @Override
public String getName() { public String getName() {
return entity.getName(); return entity.getName();

View file

@ -27,6 +27,11 @@ public class OAuthClientAdapter implements OAuthClientModel {
return entity.getId(); return entity.getId();
} }
@Override
public String getClientId() {
return getAgent().getLoginName();
}
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return getAgent().isEnabled(); return getAgent().isEnabled();

View file

@ -313,125 +313,6 @@ public class RealmAdapter implements RealmModel {
return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates. return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override
public List<RequiredCredentialModel> getRequiredApplicationCredentials() {
List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>();
Collection<RequiredCredentialEntity> entities = realm.getRequiredAppCredentials();
if (entities == null) return requiredCredentialModels;
for (RequiredCredentialEntity entity : entities) {
RequiredCredentialModel model = new RequiredCredentialModel();
model.setFormLabel(entity.getFormLabel());
model.setType(entity.getType());
model.setSecret(entity.isSecret());
model.setInput(entity.isInput());
requiredCredentialModels.add(model);
}
return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<RequiredCredentialModel> getRequiredOAuthClientCredentials() {
List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>();
Collection<RequiredCredentialEntity> entities = realm.getRequiredOAuthClCredentials();
if (entities == null) return requiredCredentialModels;
for (RequiredCredentialEntity entity : entities) {
RequiredCredentialModel model = new RequiredCredentialModel();
model.setFormLabel(entity.getFormLabel());
model.setType(entity.getType());
model.setSecret(entity.isSecret());
model.setInput(entity.isInput());
requiredCredentialModels.add(model);
}
return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates.
}
public void addRequiredOAuthClientCredential(RequiredCredentialModel model) {
RequiredCredentialEntity entity = new RequiredCredentialEntity();
entity.setInput(model.isInput());
entity.setSecret(model.isSecret());
entity.setType(model.getType());
entity.setFormLabel(model.getFormLabel());
em.persist(entity);
realm.getRequiredOAuthClCredentials().add(entity);
em.flush();
}
@Override
public void addRequiredOAuthClientCredential(String type) {
RequiredCredentialModel model = initRequiredCredentialModel(type);
addRequiredOAuthClientCredential(model);
em.flush();
}
public void addRequiredResourceCredential(RequiredCredentialModel model) {
RequiredCredentialEntity entity = new RequiredCredentialEntity();
entity.setInput(model.isInput());
entity.setSecret(model.isSecret());
entity.setType(model.getType());
entity.setFormLabel(model.getFormLabel());
em.persist(entity);
realm.getRequiredAppCredentials().add(entity);
em.flush();
}
@Override
public void addRequiredResourceCredential(String type) {
RequiredCredentialModel model = initRequiredCredentialModel(type);
addRequiredResourceCredential(model);
em.flush();
}
@Override
public void updateRequiredOAuthClientCredentials(Set<String> creds) {
Collection<RequiredCredentialEntity> relationships = realm.getRequiredOAuthClCredentials();
if (relationships == null) relationships = new ArrayList<RequiredCredentialEntity>();
Set<String> already = new HashSet<String>();
List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>();
for (RequiredCredentialEntity rel : relationships) {
if (!creds.contains(rel.getType())) {
remove.add(rel);
} else {
already.add(rel.getType());
}
}
for (RequiredCredentialEntity entity : remove) {
relationships.remove(entity);
em.remove(entity);
}
for (String cred : creds) {
if (!already.contains(cred)) {
addRequiredOAuthClientCredential(cred);
}
}
em.flush();
}
@Override
public void updateRequiredApplicationCredentials(Set<String> creds) {
Collection<RequiredCredentialEntity> relationships = realm.getRequiredAppCredentials();
if (relationships == null) relationships = new ArrayList<RequiredCredentialEntity>();
Set<String> already = new HashSet<String>();
List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>();
for (RequiredCredentialEntity rel : relationships) {
if (!creds.contains(rel.getType())) {
remove.add(rel);
} else {
already.add(rel.getType());
}
}
for (RequiredCredentialEntity entity : remove) {
relationships.remove(entity);
em.remove(entity);
}
for (String cred : creds) {
if (!already.contains(cred)) {
addRequiredResourceCredential(cred);
}
}
em.flush();
}
@Override @Override
public UserModel getUser(String name) { public UserModel getUser(String name) {

View file

@ -62,14 +62,6 @@ public class RealmEntity {
@JoinTable(name="User_RequiredCreds") @JoinTable(name="User_RequiredCreds")
Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>(); Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="App_RequiredCreds")
Collection<RequiredCredentialEntity> requiredAppCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="OAuthClient_RequiredCreds")
Collection<RequiredCredentialEntity> requiredOAuthClCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>(); Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>();
@ -236,22 +228,6 @@ public class RealmEntity {
this.requiredCredentials = requiredCredentials; this.requiredCredentials = requiredCredentials;
} }
public Collection<RequiredCredentialEntity> getRequiredAppCredentials() {
return requiredAppCredentials;
}
public void setRequiredAppCredentials(Collection<RequiredCredentialEntity> requiredAppCredentials) {
this.requiredAppCredentials = requiredAppCredentials;
}
public Collection<RequiredCredentialEntity> getRequiredOAuthClCredentials() {
return requiredOAuthClCredentials;
}
public void setRequiredOAuthClCredentials(Collection<RequiredCredentialEntity> requiredOAuthClCredentials) {
this.requiredOAuthClCredentials = requiredOAuthClCredentials;
}
public Collection<ApplicationEntity> getApplications() { public Collection<ApplicationEntity> getApplications() {
return applications; return applications;
} }

View file

@ -60,6 +60,11 @@ public class ApplicationAdapter extends AbstractAdapter implements ApplicationMo
return application.getId(); return application.getId();
} }
@Override
public String getClientId() {
return getName();
}
@Override @Override
public String getName() { public String getName() {
return application.getName(); return application.getName();

View file

@ -35,6 +35,11 @@ public class OAuthClientAdapter extends AbstractAdapter implements OAuthClientMo
return delegate.getId(); return delegate.getId();
} }
@Override
public String getClientId() {
return getAgent().getLoginName();
}
@Override @Override
public long getAllowedClaimsMask() { public long getAllowedClaimsMask() {
return delegate.getAllowedClaimsMask(); return delegate.getAllowedClaimsMask();

View file

@ -730,18 +730,6 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
addRequiredCredential(credentialModel, realm.getRequiredCredentials()); addRequiredCredential(credentialModel, realm.getRequiredCredentials());
} }
@Override
public void addRequiredResourceCredential(String type) {
RequiredCredentialModel credentialModel = initRequiredCredentialModel(type);
addRequiredCredential(credentialModel, realm.getRequiredApplicationCredentials());
}
@Override
public void addRequiredOAuthClientCredential(String type) {
RequiredCredentialModel credentialModel = initRequiredCredentialModel(type);
addRequiredCredential(credentialModel, realm.getRequiredOAuthClientCredentials());
}
protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) { protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) {
RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); RequiredCredentialEntity credEntity = new RequiredCredentialEntity();
credEntity.setType(credentialModel.getType()); credEntity.setType(credentialModel.getType());
@ -759,16 +747,6 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
updateRequiredCredentials(creds, realm.getRequiredCredentials()); updateRequiredCredentials(creds, realm.getRequiredCredentials());
} }
@Override
public void updateRequiredApplicationCredentials(Set<String> creds) {
updateRequiredCredentials(creds, realm.getRequiredApplicationCredentials());
}
@Override
public void updateRequiredOAuthClientCredentials(Set<String> creds) {
updateRequiredCredentials(creds, realm.getRequiredOAuthClientCredentials());
}
protected void updateRequiredCredentials(Set<String> creds, List<RequiredCredentialEntity> credsEntities) { protected void updateRequiredCredentials(Set<String> creds, List<RequiredCredentialEntity> credsEntities) {
Set<String> already = new HashSet<String>(); Set<String> already = new HashSet<String>();
Set<RequiredCredentialEntity> toRemove = new HashSet<RequiredCredentialEntity>(); Set<RequiredCredentialEntity> toRemove = new HashSet<RequiredCredentialEntity>();
@ -796,16 +774,6 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
return convertRequiredCredentialEntities(realm.getRequiredCredentials()); return convertRequiredCredentialEntities(realm.getRequiredCredentials());
} }
@Override
public List<RequiredCredentialModel> getRequiredApplicationCredentials() {
return convertRequiredCredentialEntities(realm.getRequiredApplicationCredentials());
}
@Override
public List<RequiredCredentialModel> getRequiredOAuthClientCredentials() {
return convertRequiredCredentialEntities(realm.getRequiredOAuthClientCredentials());
}
protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) { protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) {
List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>();

View file

@ -46,8 +46,6 @@ public class RealmEntity extends AbstractMongoIdentifiableEntity implements Mong
private List<String> defaultRoles = new ArrayList<String>(); private List<String> defaultRoles = new ArrayList<String>();
private List<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>(); private List<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
private List<RequiredCredentialEntity> requiredApplicationCredentials = new ArrayList<RequiredCredentialEntity>();
private List<RequiredCredentialEntity> requiredOAuthClientCredentials = new ArrayList<RequiredCredentialEntity>();
private Map<String, String> smtpConfig = new HashMap<String, String>(); private Map<String, String> smtpConfig = new HashMap<String, String>();
private Map<String, String> socialConfig = new HashMap<String, String>(); private Map<String, String> socialConfig = new HashMap<String, String>();
@ -241,24 +239,6 @@ public class RealmEntity extends AbstractMongoIdentifiableEntity implements Mong
this.requiredCredentials = requiredCredentials; this.requiredCredentials = requiredCredentials;
} }
@MongoField
public List<RequiredCredentialEntity> getRequiredApplicationCredentials() {
return requiredApplicationCredentials;
}
public void setRequiredApplicationCredentials(List<RequiredCredentialEntity> requiredApplicationCredentials) {
this.requiredApplicationCredentials = requiredApplicationCredentials;
}
@MongoField
public List<RequiredCredentialEntity> getRequiredOAuthClientCredentials() {
return requiredOAuthClientCredentials;
}
public void setRequiredOAuthClientCredentials(List<RequiredCredentialEntity> requiredOAuthClientCredentials) {
this.requiredOAuthClientCredentials = requiredOAuthClientCredentials;
}
@MongoField @MongoField
public Map<String, String> getSmtpConfig() { public Map<String, String> getSmtpConfig() {
return smtpConfig; return smtpConfig;

View file

@ -139,9 +139,6 @@ public class AdapterTest extends AbstractModelTest {
OAuthClientModel oauth = new OAuthClientManager(realmModel).create("oauth-client"); OAuthClientModel oauth = new OAuthClientManager(realmModel).create("oauth-client");
oauth = realmModel.getOAuthClient("oauth-client"); oauth = realmModel.getOAuthClient("oauth-client");
Assert.assertTrue(realmModel.hasRole(oauth.getAgent(), realmModel.getRole(Constants.IDENTITY_REQUESTER_ROLE)));
} }
@Test @Test
@ -418,7 +415,7 @@ public class AdapterTest extends AbstractModelTest {
realmModel.addRole("admin"); realmModel.addRole("admin");
realmModel.addRole("user"); realmModel.addRole("user");
Set<RoleModel> roles = realmModel.getRoles(); Set<RoleModel> roles = realmModel.getRoles();
Assert.assertEquals(5, roles.size()); Assert.assertEquals(3, roles.size());
UserModel user = realmModel.addUser("bburke"); UserModel user = realmModel.addUser("bburke");
RoleModel realmUserRole = realmModel.getRole("user"); RoleModel realmUserRole = realmModel.getRole("user");
realmModel.grantRole(user, realmUserRole); realmModel.grantRole(user, realmUserRole);

View file

@ -151,8 +151,6 @@ public class ImportTest extends AbstractModelTest {
Assert.assertFalse(realm.isUpdateProfileOnInitialSocialLogin()); Assert.assertFalse(realm.isUpdateProfileOnInitialSocialLogin());
Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction()); Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction());
verifyRequiredCredentials(realm.getRequiredCredentials(), "password"); verifyRequiredCredentials(realm.getRequiredCredentials(), "password");
verifyRequiredCredentials(realm.getRequiredApplicationCredentials(), "secret");
verifyRequiredCredentials(realm.getRequiredOAuthClientCredentials(), "secret");
} }
private void verifyRequiredCredentials(List<RequiredCredentialModel> requiredCreds, String expectedType) { private void verifyRequiredCredentials(List<RequiredCredentialModel> requiredCreds, String expectedType) {

View file

@ -36,7 +36,7 @@ public class AppAuthManager extends AuthenticationManager {
this.tokenManager = tokenManager; this.tokenManager = tokenManager;
} }
public NewCookie createCookie(RealmModel realm, UserModel client, String code, URI uri) { public NewCookie createCookie(RealmModel realm, ClientModel client, String code, URI uri) {
JWSInput input = new JWSInput(code); JWSInput input = new JWSInput(code);
boolean verifiedCode = false; boolean verifiedCode = false;
try { try {
@ -67,7 +67,7 @@ public class AppAuthManager extends AuthenticationManager {
throw new BadRequestException(); throw new BadRequestException();
} }
if (!client.getLoginName().equals(accessCode.getClient().getAgent().getLoginName())) { if (!client.getClientId().equals(accessCode.getClient().getClientId())) {
logger.debug("bad client"); logger.debug("bad client");
throw new BadRequestException(); throw new BadRequestException();
} }

View file

@ -45,8 +45,6 @@ public class ApplianceBootstrap {
realm.setName(Constants.ADMIN_REALM); realm.setName(Constants.ADMIN_REALM);
realm.setEnabled(true); realm.setEnabled(true);
realm.addRequiredCredential(CredentialRepresentation.PASSWORD); realm.addRequiredCredential(CredentialRepresentation.PASSWORD);
realm.addRequiredOAuthClientCredential(CredentialRepresentation.PASSWORD);
realm.addRequiredResourceCredential(CredentialRepresentation.PASSWORD);
realm.setCentralLoginLifespan(3000); realm.setCentralLoginLifespan(3000);
realm.setAccessTokenLifespan(60); realm.setAccessTokenLifespan(60);
realm.setRefreshTokenLifespan(3600); realm.setRefreshTokenLifespan(3600);

View file

@ -46,11 +46,10 @@ public class ApplicationManager {
* Does not create scope or role mappings! * Does not create scope or role mappings!
* *
* @param realm * @param realm
* @param loginRole
* @param resourceRep * @param resourceRep
* @return * @return
*/ */
public ApplicationModel createApplication(RealmModel realm, RoleModel loginRole, ApplicationRepresentation resourceRep) { public ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep) {
logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName()); logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName());
ApplicationModel applicationModel = realm.addApplication(resourceRep.getName()); ApplicationModel applicationModel = realm.addApplication(resourceRep.getName());
applicationModel.setEnabled(resourceRep.isEnabled()); applicationModel.setEnabled(resourceRep.isEnabled());
@ -59,7 +58,6 @@ public class ApplicationManager {
applicationModel.setBaseUrl(resourceRep.getBaseUrl()); applicationModel.setBaseUrl(resourceRep.getBaseUrl());
applicationModel.updateApplication(); applicationModel.updateApplication();
UserModel resourceUser = applicationModel.getAgent();
applicationModel.setSecret(resourceRep.getSecret()); applicationModel.setSecret(resourceRep.getSecret());
if (applicationModel.getSecret() == null) { if (applicationModel.getSecret() == null) {
generateSecret(applicationModel); generateSecret(applicationModel);
@ -73,14 +71,11 @@ public class ApplicationManager {
} }
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}", resourceRep.getName(), webOrigin);
applicationModel.addWebOrigin(webOrigin); applicationModel.addWebOrigin(webOrigin);
} }
} }
realm.grantRole(resourceUser, loginRole);
if (resourceRep.getDefaultRoles() != null) { if (resourceRep.getDefaultRoles() != null) {
applicationModel.updateDefaultRoles(resourceRep.getDefaultRoles()); applicationModel.updateDefaultRoles(resourceRep.getDefaultRoles());
} }
@ -123,15 +118,8 @@ public class ApplicationManager {
} }
} }
public ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep) {
RoleModel loginRole = realm.getRole(Constants.APPLICATION_ROLE);
return createApplication(realm, loginRole, resourceRep);
}
public ApplicationModel createApplication(RealmModel realm, String name) { public ApplicationModel createApplication(RealmModel realm, String name) {
RoleModel loginRole = realm.getRole(Constants.APPLICATION_ROLE);
ApplicationModel app = realm.addApplication(name); ApplicationModel app = realm.addApplication(name);
realm.grantRole(app.getAgent(), loginRole);
generateSecret(app); generateSecret(app);
return app; return app;

View file

@ -60,7 +60,7 @@ public class AuthenticationManager {
protected NewCookie createLoginCookie(RealmModel realm, UserModel user, ClientModel 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.getAgent().getLoginName()); identityToken.issuedFor(client.getClientId());
} }
String encoded = encodeToken(realm, identityToken); String encoded = encodeToken(realm, identityToken);
boolean secureOnly = !realm.isSslNotRequired(); boolean secureOnly = !realm.isSslNotRequired();
@ -174,18 +174,7 @@ public class AuthenticationManager {
Set<String> types = new HashSet<String>(); Set<String> types = new HashSet<String>();
List<RequiredCredentialModel> requiredCredentials = null; for (RequiredCredentialModel credential : realm.getRequiredCredentials()) {
RoleModel applicationRole = realm.getRole(Constants.APPLICATION_ROLE);
RoleModel identityRequesterRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
if (realm.hasRole(user, applicationRole)) {
requiredCredentials = realm.getRequiredApplicationCredentials();
} else if (realm.hasRole(user, identityRequesterRole)) {
requiredCredentials = realm.getRequiredOAuthClientCredentials();
} else {
requiredCredentials = realm.getRequiredCredentials();
}
for (RequiredCredentialModel credential : requiredCredentials) {
types.add(credential.getType()); types.add(credential.getType());
} }

View file

@ -32,18 +32,16 @@ public class OAuthClientManager {
this.realm = realm; this.realm = realm;
} }
public UserCredentialModel generateSecret(RealmModel realm, OAuthClientModel app) { public UserCredentialModel generateSecret(OAuthClientModel app) {
UserCredentialModel secret = UserCredentialModel.generateSecret(); UserCredentialModel secret = UserCredentialModel.generateSecret();
realm.updateCredential(app.getAgent(), secret); app.setSecret(secret.getValue());
return secret; return secret;
} }
public OAuthClientModel create(String name) { public OAuthClientModel create(String name) {
OAuthClientModel model = realm.addOAuthClient(name); OAuthClientModel model = realm.addOAuthClient(name);
RoleModel role = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE); generateSecret(model);
realm.grantRole(model.getAgent(), role);
generateSecret(realm, model);
return model; return model;
} }
@ -61,7 +59,7 @@ public class OAuthClientManager {
} }
public void update(OAuthClientRepresentation rep, OAuthClientModel model) { public void update(OAuthClientRepresentation rep, OAuthClientModel model) {
model.getAgent().setEnabled(rep.isEnabled()); model.setEnabled(rep.isEnabled());
List<String> redirectUris = rep.getRedirectUris(); List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
model.setRedirectUris(new HashSet<String>(redirectUris)); model.setRedirectUris(new HashSet<String>(redirectUris));
@ -80,8 +78,8 @@ public class OAuthClientManager {
public static OAuthClientRepresentation toRepresentation(OAuthClientModel model) { public static OAuthClientRepresentation toRepresentation(OAuthClientModel model) {
OAuthClientRepresentation rep = new OAuthClientRepresentation(); OAuthClientRepresentation rep = new OAuthClientRepresentation();
rep.setId(model.getId()); rep.setId(model.getId());
rep.setName(model.getAgent().getLoginName()); rep.setName(model.getClientId());
rep.setEnabled(model.getAgent().isEnabled()); rep.setEnabled(model.isEnabled());
Set<String> redirectUris = model.getRedirectUris(); Set<String> redirectUris = model.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
rep.setRedirectUris(new LinkedList<String>(redirectUris)); rep.setRedirectUris(new LinkedList<String>(redirectUris));
@ -127,7 +125,7 @@ public class OAuthClientManager {
rep.setSslNotRequired(realmModel.isSslNotRequired()); rep.setSslNotRequired(realmModel.isSslNotRequired());
rep.setAuthServerUrl(baseUri.toString()); rep.setAuthServerUrl(baseUri.toString());
rep.setResource(model.getAgent().getLoginName()); rep.setResource(model.getClientId());
Map<String, String> creds = new HashMap<String, String>(); Map<String, String> creds = new HashMap<String, String>();
creds.put(CredentialRepresentation.SECRET, model.getSecret()); creds.put(CredentialRepresentation.SECRET, model.getSecret());

View file

@ -70,15 +70,10 @@ public class RealmManager {
if (id == null) id = KeycloakModelUtils.generateId(); if (id == null) id = KeycloakModelUtils.generateId();
RealmModel realm = identitySession.createRealm(id, name); RealmModel realm = identitySession.createRealm(id, name);
realm.setName(name); realm.setName(name);
realm.addRole(Constants.APPLICATION_ROLE);
realm.addRole(Constants.IDENTITY_REQUESTER_ROLE);
setupAdminManagement(realm); setupAdminManagement(realm);
setupAccountManagement(realm); setupAccountManagement(realm);
realm.addRequiredOAuthClientCredential(UserCredentialModel.SECRET);
realm.addRequiredResourceCredential(UserCredentialModel.SECRET);
return realm; return realm;
} }
@ -258,9 +253,6 @@ public class RealmManager {
if (rep.getApplications() != null) { if (rep.getApplications() != null) {
Map<String, ApplicationModel> appMap = createApplications(rep, newRealm); Map<String, ApplicationModel> appMap = createApplications(rep, newRealm);
for (ApplicationModel app : appMap.values()) {
userMap.put(app.getAgent().getLoginName(), app.getAgent());
}
} }
if (rep.getRoles() != null) { if (rep.getRoles() != null) {
@ -310,11 +302,7 @@ public class RealmManager {
} }
if (rep.getOauthClients() != null) { if (rep.getOauthClients() != null) {
Map<String, OAuthClientModel> oauthMap = createOAuthClients(rep, newRealm); createOAuthClients(rep, newRealm);
for (OAuthClientModel app : oauthMap.values()) {
userMap.put(app.getAgent().getLoginName(), app.getAgent());
}
} }
// Now that all possible users and applications are created (users, apps, and oauth clients), do role mappings and scope mappings // Now that all possible users and applications are created (users, apps, and oauth clients), do role mappings and scope mappings
@ -364,8 +352,7 @@ public class RealmManager {
if (role == null) { if (role == null) {
role = newRealm.addRole(roleString.trim()); role = newRealm.addRole(roleString.trim());
} }
UserModel user = userMap.get(scope.getClient()); ClientModel client = newRealm.findClient(scope.getClient());
ClientModel client = newRealm.findClient(user.getLoginName());
newRealm.addScopeMapping(client, role); newRealm.addScopeMapping(client, role);
} }
@ -481,34 +468,21 @@ public class RealmManager {
newRealm.addRequiredCredential(requiredCred); newRealm.addRequiredCredential(requiredCred);
} }
public void addResourceRequiredCredential(RealmModel newRealm, String requiredCred) {
newRealm.addRequiredResourceCredential(requiredCred);
}
public void addOAuthClientRequiredCredential(RealmModel newRealm, String requiredCred) {
newRealm.addRequiredOAuthClientCredential(requiredCred);
}
protected Map<String, ApplicationModel> createApplications(RealmRepresentation rep, RealmModel realm) { protected Map<String, ApplicationModel> createApplications(RealmRepresentation rep, RealmModel realm) {
Map<String, ApplicationModel> appMap = new HashMap<String, ApplicationModel>(); Map<String, ApplicationModel> appMap = new HashMap<String, ApplicationModel>();
RoleModel loginRole = realm.getRole(Constants.APPLICATION_ROLE);
ApplicationManager manager = new ApplicationManager(this); ApplicationManager manager = new ApplicationManager(this);
for (ApplicationRepresentation resourceRep : rep.getApplications()) { for (ApplicationRepresentation resourceRep : rep.getApplications()) {
ApplicationModel app = manager.createApplication(realm, loginRole, resourceRep); ApplicationModel app = manager.createApplication(realm, resourceRep);
appMap.put(app.getName(), app); appMap.put(app.getName(), app);
} }
return appMap; return appMap;
} }
protected Map<String, OAuthClientModel> createOAuthClients(RealmRepresentation realmRep, RealmModel realm) { protected void createOAuthClients(RealmRepresentation realmRep, RealmModel realm) {
Map<String, OAuthClientModel> appMap = new HashMap<String, OAuthClientModel>();
OAuthClientManager manager = new OAuthClientManager(realm); OAuthClientManager manager = new OAuthClientManager(realm);
for (OAuthClientRepresentation rep : realmRep.getOauthClients()) { for (OAuthClientRepresentation rep : realmRep.getOauthClients()) {
OAuthClientModel app = manager.create(rep); OAuthClientModel app = manager.create(rep);
appMap.put(app.getAgent().getLoginName(), app);
} }
return appMap;
} }

View file

@ -290,7 +290,7 @@ public class TokenManager {
token.subject(user.getId()); token.subject(user.getId());
token.audience(realm.getName()); token.audience(realm.getName());
token.issuedNow(); token.issuedNow();
token.issuedFor(client.getAgent().getLoginName()); token.issuedFor(client.getClientId());
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());

View file

@ -254,8 +254,7 @@ public class AccountService {
logger.debug("realm not enabled"); logger.debug("realm not enabled");
throw new ForbiddenException(); throw new ForbiddenException();
} }
UserModel client = application.getAgent(); if (!application.isEnabled()) {
if (!client.isEnabled() || !application.isEnabled()) {
logger.debug("account management app not enabled"); logger.debug("account management app not enabled");
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -274,7 +273,7 @@ public class AccountService {
redirectUri = redirectUri.resolve("?referrer=" + referrer); redirectUri = redirectUri.resolve("?referrer=" + referrer);
} }
NewCookie cookie = authManager.createCookie(realm, client, code, Urls.accountBase(uriInfo.getBaseUri()).build(realm.getName())); NewCookie cookie = authManager.createCookie(realm, application, code, Urls.accountBase(uriInfo.getBaseUri()).build(realm.getName()));
return Response.status(302).cookie(cookie).location(redirectUri).build(); return Response.status(302).cookie(cookie).location(redirectUri).build();
} finally { } finally {
authManager.expireCookie(Urls.accountBase(uriInfo.getBaseUri()).build(realm.getName())); authManager.expireCookie(Urls.accountBase(uriInfo.getBaseUri()).build(realm.getName()));

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.ApplicationModel;
import org.keycloak.models.ClientModel; 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;
@ -404,7 +405,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.getAgent().getLoginName().equals(accessCode.getClient().getAgent().getLoginName())) { if (!client.getClientId().equals(accessCode.getClient().getClientId())) {
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");
@ -486,14 +487,6 @@ public class TokenService {
return oauth.forwardToSecurityFailure("Invalid redirect_uri."); return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
} }
logger.info("Checking roles...");
RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE);
RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client.getAgent(), resourceRole);
if (!isResource && !realm.hasRole(client.getAgent(), identityRequestRole)) {
logger.warn("Login requester not allowed to request login.");
return oauth.forwardToSecurityFailure("Login requester not allowed to request login.");
}
logger.info("Checking cookie..."); logger.info("Checking cookie...");
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers); UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers);
if (user != null) { if (user != null) {

View file

@ -325,8 +325,7 @@ public class AdminService {
return redirectOnLoginError("realm not enabled"); return redirectOnLoginError("realm not enabled");
} }
ApplicationModel adminConsole = adminRealm.getApplicationNameMap().get(Constants.ADMIN_CONSOLE_APPLICATION); ApplicationModel adminConsole = adminRealm.getApplicationNameMap().get(Constants.ADMIN_CONSOLE_APPLICATION);
UserModel adminConsoleUser = adminConsole.getAgent(); if (!adminConsole.isEnabled()) {
if (!adminConsole.isEnabled() || !adminConsoleUser.isEnabled()) {
logger.debug("admin app not enabled"); logger.debug("admin app not enabled");
return redirectOnLoginError("admin app not enabled"); return redirectOnLoginError("admin app not enabled");
} }
@ -342,7 +341,7 @@ public class AdminService {
new JaxrsOAuthClient().checkStateCookie(uriInfo, headers); new JaxrsOAuthClient().checkStateCookie(uriInfo, headers);
logger.debug("loginRedirect SUCCESS"); logger.debug("loginRedirect SUCCESS");
NewCookie cookie = authManager.createCookie(adminRealm, adminConsoleUser, code, AdminService.saasCookiePath(uriInfo).build()); NewCookie cookie = authManager.createCookie(adminRealm, adminConsole, code, AdminService.saasCookiePath(uriInfo).build());
URI redirectUri = contextRoot(uriInfo).path(adminPath).build(); URI redirectUri = contextRoot(uriInfo).path(adminPath).build();
if (path != null) { if (path != null) {

View file

@ -112,7 +112,7 @@ public class OAuthClientResource {
logger.debug("regenerateSecret"); logger.debug("regenerateSecret");
UserCredentialModel cred = UserCredentialModel.generateSecret(); UserCredentialModel cred = UserCredentialModel.generateSecret();
realm.updateCredential(oauthClient.getAgent(), cred); oauthClient.setSecret(cred.getValue());
CredentialRepresentation rep = ModelToRepresentation.toRepresentation(cred); CredentialRepresentation rep = ModelToRepresentation.toRepresentation(cred);
return rep; return rep;
} }

View file

@ -58,7 +58,7 @@ public class OAuthClientsResource {
rep.add(OAuthClientManager.toRepresentation(oauth)); rep.add(OAuthClientManager.toRepresentation(oauth));
} else { } else {
OAuthClientRepresentation client = new OAuthClientRepresentation(); OAuthClientRepresentation client = new OAuthClientRepresentation();
client.setName(oauth.getAgent().getLoginName()); client.setName(oauth.getClientId());
rep.add(client); rep.add(client);
} }
} }

View file

@ -199,7 +199,7 @@ public class UsersResource {
} }
private boolean isUser(UserModel user) { private boolean isUser(UserModel user) {
return !realm.hasRole(user, realm.getRole(Constants.IDENTITY_REQUESTER_ROLE)) && !realm.hasRole(user, realm.getRole(Constants.APPLICATION_ROLE)); return true;
} }
@Path("{username}/role-mappings") @Path("{username}/role-mappings")

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.ApplicationModel;
import org.keycloak.models.ClientModel; 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;
@ -107,12 +108,7 @@ public class OAuthFlows {
isTotpConfigurationRequired(user); isTotpConfigurationRequired(user);
isEmailVerificationRequired(user); isEmailVerificationRequired(user);
RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE); boolean isResource = client instanceof ApplicationModel;
RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client.getAgent(), resourceRole);
if (!isResource && !realm.hasRole(client.getAgent(), identityRequestRole)) {
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);
log.debug("processAccessCode: isResource: {0}", isResource); log.debug("processAccessCode: isResource: {0}", isResource);
log.debug("processAccessCode: go to oauth page?: {0}", log.debug("processAccessCode: go to oauth page?: {0}",
@ -129,7 +125,6 @@ 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.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

@ -78,14 +78,8 @@ public class CreateRealmsWorker implements Worker {
// Add required credentials // Add required credentials
if (createRequiredCredentials) { if (createRequiredCredentials) {
realmManager.addRequiredCredential(realm, CredentialRepresentation.PASSWORD); realmManager.addRequiredCredential(realm, CredentialRepresentation.PASSWORD);
realmManager.addResourceRequiredCredential(realm, CredentialRepresentation.PASSWORD);
realmManager.addOAuthClientRequiredCredential(realm, CredentialRepresentation.PASSWORD);
realmManager.addRequiredCredential(realm, CredentialRepresentation.TOTP); realmManager.addRequiredCredential(realm, CredentialRepresentation.TOTP);
realmManager.addResourceRequiredCredential(realm, CredentialRepresentation.TOTP);
realmManager.addOAuthClientRequiredCredential(realm, CredentialRepresentation.TOTP);
realmManager.addRequiredCredential(realm, CredentialRepresentation.CLIENT_CERT); realmManager.addRequiredCredential(realm, CredentialRepresentation.CLIENT_CERT);
realmManager.addResourceRequiredCredential(realm, CredentialRepresentation.CLIENT_CERT);
realmManager.addOAuthClientRequiredCredential(realm, CredentialRepresentation.CLIENT_CERT);
} }
log.info("Finished creation of realm " + realmName); log.info("Finished creation of realm " + realmName);