Merge pull request #13 from patriot1burke/master

refactor out picketlink
This commit is contained in:
Bill Burke 2013-07-30 18:48:25 -07:00
commit d19466db4b
15 changed files with 159 additions and 72 deletions

View file

@ -66,7 +66,7 @@ public class DemoApplication extends KeycloakApplication {
manager.generateRealmKeys(defaultRealm);
defaultRealm.updateRealm();
defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
defaultRealm.addRole(RegistrationService.REALM_CREATOR_ROLE);
RealmRepresentation rep = loadJson("META-INF/testrealm.json");
RealmModel realm = manager.createRealm("demo", rep.getRealm());

View file

@ -72,7 +72,7 @@ public class AuthenticationManager {
expireIdentityCookie(realm, uriInfo);
return null;
}
User user = realm.getIdm().getUser(token.getPrincipal());
User user = realm.getUser(token.getPrincipal());
if (user == null || !user.isEnabled()) {
logger.info("Unknown user in identity cookie");
expireIdentityCookie(realm, uriInfo);
@ -104,7 +104,7 @@ public class AuthenticationManager {
if (!token.isActive()) {
throw new NotAuthorizedException("token_expired");
}
User user = realm.getIdm().getUser(token.getPrincipal());
User user = realm.getUser(token.getPrincipal());
if (user == null || !user.isEnabled()) {
throw new NotAuthorizedException("invalid_user");
}
@ -136,25 +136,13 @@ public class AuthenticationManager {
logger.warn("TOTP token not provided");
return false;
}
TOTPCredentials creds = new TOTPCredentials();
creds.setToken(token);
creds.setUsername(username);
creds.setPassword(new Password(password));
realm.getIdm().validateCredentials(creds);
if (creds.getStatus() != Credentials.Status.VALID) {
return false;
}
return realm.validateTOTP(user, password, token);
} else {
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, new Password(password));
realm.getIdm().validateCredentials(creds);
if (creds.getStatus() != Credentials.Status.VALID) {
return false;
}
return realm.validatePassword(user, password);
}
} else {
logger.warn("Do not know how to authenticate user");
return false;
}
return true;
}
}

View file

@ -23,7 +23,7 @@ public class InstallationManager {
manager.generateRealmKeys(defaultRealm);
defaultRealm.updateRealm();
defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
defaultRealm.addRole(RegistrationService.REALM_CREATOR_ROLE);
}
public boolean isInstalled(RealmManager manager) {

View file

@ -139,7 +139,7 @@ public class RealmManager {
user.setAttribute(new Attribute<String>(entry.getKey(), entry.getValue()));
}
}
newRealm.getIdm().add(user);
newRealm.addUser(user);
if (userRep.getCredentials() != null) {
for (CredentialRepresentation cred : userRep.getCredentials()) {
UserCredentialModel credential = new UserCredentialModel();
@ -155,7 +155,7 @@ public class RealmManager {
for (RoleRepresentation roleRep : rep.getRoles()) {
SimpleRole role = new SimpleRole(roleRep.getName());
if (roleRep.getDescription() != null) role.setAttribute(new Attribute<String>("description", roleRep.getDescription()));
newRealm.getIdm().add(role);
newRealm.addRole(role);
}
}
@ -167,12 +167,12 @@ public class RealmManager {
for (RoleMappingRepresentation mapping : rep.getRoleMappings()) {
User user = userMap.get(mapping.getUsername());
for (String roleString : mapping.getRoles()) {
Role role = newRealm.getIdm().getRole(roleString.trim());
Role role = newRealm.getRole(roleString.trim());
if (role == null) {
role = new SimpleRole(roleString.trim());
newRealm.getIdm().add(role);
newRealm.addRole(role);
}
newRealm.getIdm().grantRole(user, role);
newRealm.grantRole(user, role);
}
}
}
@ -180,10 +180,10 @@ public class RealmManager {
if (rep.getScopeMappings() != null) {
for (ScopeMappingRepresentation scope : rep.getScopeMappings()) {
for (String roleString : scope.getRoles()) {
Role role = newRealm.getIdm().getRole(roleString.trim());
Role role = newRealm.getRole(roleString.trim());
if (role == null) {
role = new SimpleRole(roleString.trim());
newRealm.getIdm().add(role);
newRealm.addRole(role);
}
User user = userMap.get(scope.getUsername());
newRealm.addScope(user, role.getName());
@ -194,7 +194,7 @@ public class RealmManager {
}
protected void createResources(RealmRepresentation rep, RealmModel realm, Map<String, User> userMap) {
Role loginRole = realm.getIdm().getRole(RealmManager.RESOURCE_ROLE);
Role loginRole = realm.getRole(RealmManager.RESOURCE_ROLE);
for (ResourceRepresentation resourceRep : rep.getResources()) {
ResourceModel resource = realm.addResource(resourceRep.getName());
resource.setManagementUrl(resourceRep.getAdminUrl());
@ -211,26 +211,26 @@ public class RealmManager {
}
}
userMap.put(resourceUser.getLoginName(), resourceUser);
realm.getIdm().grantRole(resourceUser, loginRole);
realm.grantRole(resourceUser, loginRole);
if (resourceRep.getRoles() != null) {
for (RoleRepresentation roleRep : resourceRep.getRoles()) {
SimpleRole role = new SimpleRole(roleRep.getName());
if (roleRep.getDescription() != null) role.setAttribute(new Attribute<String>("description", roleRep.getDescription()));
resource.getIdm().add(role);
resource.addRole(role);
}
}
if (resourceRep.getRoleMappings() != null) {
for (RoleMappingRepresentation mapping : resourceRep.getRoleMappings()) {
User user = userMap.get(mapping.getUsername());
for (String roleString : mapping.getRoles()) {
Role role = resource.getIdm().getRole(roleString.trim());
Role role = resource.getRole(roleString.trim());
if (role == null) {
role = new SimpleRole(roleString.trim());
resource.getIdm().add(role);
resource.addRole(role);
}
realm.getIdm().grantRole(user, role);
realm.grantRole(user, role);
}
}
}
@ -238,10 +238,10 @@ public class RealmManager {
for (ScopeMappingRepresentation mapping : resourceRep.getScopeMappings()) {
User user = userMap.get(mapping.getUsername());
for (String roleString : mapping.getRoles()) {
Role role = resource.getIdm().getRole(roleString.trim());
Role role = resource.getRole(roleString.trim());
if (role == null) {
role = new SimpleRole(roleString.trim());
resource.getIdm().add(role);
resource.addRole(role);
}
resource.addScope(user, role.getName());
}

View file

@ -75,7 +75,7 @@ public class TokenManager {
(scopeRequest == null || scopeRequest.contains(role)) &&
(scope.contains("*") || scope.contains(role))
)
realmRolesRequested.add(realm.getIdm().getRole(role));
realmRolesRequested.add(realm.getRole(role));
}
}
}
@ -94,7 +94,7 @@ public class TokenManager {
(scopeRequest == null || scopeRequest.contains(role)) &&
(scope.contains("*") || scope.contains(role))
)
resourceRolesRequested.add(resource.getName(), resource.getIdm().getRole(role));
resourceRolesRequested.add(resource.getName(), resource.getRole(role));
}
}
}

View file

@ -0,0 +1,11 @@
package org.keycloak.services.models;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface KeycloakSession {
KeycloakTransaction getTransaction();
void close();
}

View file

@ -0,0 +1,8 @@
package org.keycloak.services.models;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface KeycloakSessionFactory {
}

View file

@ -0,0 +1,13 @@
package org.keycloak.services.models;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface KeycloakTransaction {
void begin();
void commit();
void rollback();
void setRollbackOnly();
boolean getRollbackOnly();
boolean isActive();}

View file

@ -10,8 +10,11 @@ import org.keycloak.services.models.relationships.RequiredCredentialRelationship
import org.keycloak.services.models.relationships.ScopeRelationship;
import org.picketlink.idm.IdentitySession;
import org.picketlink.idm.IdentityManager;
import org.picketlink.idm.credential.Credentials;
import org.picketlink.idm.credential.Password;
import org.picketlink.idm.credential.TOTPCredential;
import org.picketlink.idm.credential.TOTPCredentials;
import org.picketlink.idm.credential.UsernamePasswordCredentials;
import org.picketlink.idm.credential.X509CertificateCredentials;
import org.picketlink.idm.model.Agent;
import org.picketlink.idm.model.Attribute;
@ -67,7 +70,7 @@ public class RealmModel {
realmAgent = getIdm().getAgent(REALM_AGENT_ID);
}
public IdentityManager getIdm() {
protected IdentityManager getIdm() {
if (idm == null) idm = identitySession.createIdentityManager(realm);
return idm;
}
@ -236,6 +239,21 @@ public class RealmModel {
idm.add(relationship);
}
public boolean validatePassword(User user, String password) {
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getLoginName(), new Password(password));
getIdm().validateCredentials(creds);
return creds.getStatus() == Credentials.Status.VALID;
}
public boolean validateTOTP(User user, String password, String token) {
TOTPCredentials creds = new TOTPCredentials();
creds.setToken(token);
creds.setUsername(user.getLoginName());
creds.setPassword(new Password(password));
getIdm().validateCredentials(creds);
return creds.getStatus() == Credentials.Status.VALID;
}
public void updateCredential(User user, UserCredentialModel cred) {
IdentityManager idm = getIdm();
if (cred.getType().equals(RequiredCredentialRepresentation.PASSWORD)) {
@ -256,6 +274,28 @@ public class RealmModel {
}
}
public User getUser(String name) {
return getIdm().getUser(name);
}
public void addUser(User user) {
getIdm().add(user);
}
public Role getRole(String name) {
return getIdm().getRole(name);
}
public Role addRole(String name) {
Role role = new SimpleRole(name);
getIdm().add(role);
return role;
}
public void addRole(Role role) {
getIdm().add(role);
}
public List<Role> getRoles() {
IdentityManager idm = getIdm();
IdentityQuery<Role> query = idm.createIdentityQuery(Role.class);
@ -305,11 +345,19 @@ public class RealmModel {
relationship.setResourceUser(resourceUser);
idm.add(relationship);
ResourceModel resource = new ResourceModel(newTier, relationship, this, identitySession);
resource.getIdm().add(new SimpleRole("*"));
resource.addRole(new SimpleRole("*"));
resource.addScope(resourceUser, "*");
return resource;
}
public boolean hasRole(User user, Role role) {
return getIdm().hasRole(user, role);
}
public void grantRole(User user, Role role) {
getIdm().grantRole(user, role);
}
public Set<String> getRoleMappings(User user) {
RelationshipQuery<Grant> query = getIdm().createRelationshipQuery(Grant.class);
query.setParameter(Grant.ASSIGNEE, user);

View file

@ -7,6 +7,7 @@ import org.picketlink.idm.IdentityManager;
import org.picketlink.idm.model.Agent;
import org.picketlink.idm.model.Grant;
import org.picketlink.idm.model.Role;
import org.picketlink.idm.model.SimpleRole;
import org.picketlink.idm.model.Tier;
import org.picketlink.idm.model.User;
import org.picketlink.idm.query.IdentityQuery;
@ -34,7 +35,7 @@ public class ResourceModel {
this.identitySession = session;
}
public IdentityManager getIdm() {
protected IdentityManager getIdm() {
if (idm == null) idm = identitySession.createIdentityManager(tier);
return idm;
}
@ -83,6 +84,28 @@ public class ResourceModel {
agent.setManagementUrl(url);
}
public User getUser(String name) {
return getIdm().getUser(name);
}
public void addUser(User user) {
getIdm().add(user);
}
public Role getRole(String name) {
return getIdm().getRole(name);
}
public Role addRole(String name) {
Role role = new SimpleRole(name);
getIdm().add(role);
return role;
}
public void addRole(Role role) {
getIdm().add(role);
}
public List<Role> getRoles() {
IdentityQuery<Role> query = getIdm().createIdentityQuery(Role.class);
query.setParameter(Role.PARTITION, tier);

View file

@ -94,8 +94,8 @@ public class RealmsResource {
RealmManager realmManager = new RealmManager(identitySession);
RealmModel defaultRealm = realmManager.getRealm(Realm.DEFAULT_REALM);
User realmCreator = new AuthenticationManager().authenticateBearerToken(defaultRealm, headers);
Role creatorRole = defaultRealm.getIdm().getRole(RegistrationService.REALM_CREATOR_ROLE);
if (!defaultRealm.getIdm().hasRole(realmCreator, creatorRole)) {
Role creatorRole = defaultRealm.getRole(RegistrationService.REALM_CREATOR_ROLE);
if (!defaultRealm.hasRole(realmCreator, creatorRole)) {
logger.warn("not a realm creator");
throw new NotAuthorizedException("Bearer");
}

View file

@ -49,21 +49,21 @@ public class RegistrationService {
if (!defaultRealm.isRegistrationAllowed()) {
throw new ForbiddenException();
}
User user = defaultRealm.getIdm().getUser(newUser.getUsername());
User user = defaultRealm.getUser(newUser.getUsername());
if (user != null) {
return Response.status(400).type("text/plain").entity("user exists").build();
}
user = new SimpleUser(newUser.getUsername());
defaultRealm.getIdm().add(user);
defaultRealm.addUser(user);
for (CredentialRepresentation cred : newUser.getCredentials()) {
UserCredentialModel credModel = new UserCredentialModel();
credModel.setType(cred.getType());
credModel.setValue(cred.getValue());
defaultRealm.updateCredential(user, credModel);
}
Role realmCreator = defaultRealm.getIdm().getRole(REALM_CREATOR_ROLE);
defaultRealm.getIdm().grantRole(user, realmCreator);
Role realmCreator = defaultRealm.getRole(REALM_CREATOR_ROLE);
defaultRealm.grantRole(user, realmCreator);
identitySession.getTransaction().commit();
URI uri = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(user.getLoginName()).build();
return Response.created(uri).build();

View file

@ -125,7 +125,7 @@ public class TokenService {
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Disabled realm");
}
User user = realm.getIdm().getUser(username);
User user = realm.getUser(username);
if (user == null) {
throw new NotAuthorizedException("No user");
}
@ -154,7 +154,7 @@ public class TokenService {
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Disabled realm");
}
User user = realm.getIdm().getUser(username);
User user = realm.getUser(username);
if (user == null) {
throw new NotAuthorizedException("No user");
}
@ -183,7 +183,7 @@ public class TokenService {
securityFailureForward("Realm not enabled.");
return null;
}
User client = realm.getIdm().getUser(clientId);
User client = realm.getUser(clientId);
if (client == null) {
securityFailureForward("Unknown login requester.");
return null;
@ -193,7 +193,7 @@ public class TokenService {
return null;
}
String username = formData.getFirst("username");
User user = realm.getIdm().getUser(username);
User user = realm.getUser(username);
if (user == null) {
logger.error("Incorrect user name.");
request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Incorrect user name.");
@ -217,10 +217,10 @@ public class TokenService {
}
protected Response processAccessCode(String scopeParam, String state, String redirect, User client, User user) {
Role resourceRole = realm.getIdm().getRole(RealmManager.RESOURCE_ROLE);
Role identityRequestRole = realm.getIdm().getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.getIdm().hasRole(client, resourceRole);
if (!isResource && !realm.getIdm().hasRole(client, identityRequestRole)) {
Role resourceRole = realm.getRole(RealmManager.RESOURCE_ROLE);
Role identityRequestRole = realm.getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client, resourceRole);
if (!isResource && !realm.hasRole(client, identityRequestRole)) {
securityFailureForward("Login requester not allowed to request login.");
identitySession.close();
return null;
@ -274,7 +274,7 @@ public class TokenService {
error.put("error_description", "client_id not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
User client = realm.getIdm().getUser(client_id);
User client = realm.getUser(client_id);
if (client == null) {
logger.debug("Could not find user");
Map<String, String> error = new HashMap<String, String>();
@ -403,7 +403,7 @@ public class TokenService {
securityFailureForward("Realm not enabled");
return null;
}
User client = realm.getIdm().getUser(clientId);
User client = realm.getUser(clientId);
if (client == null) {
securityFailureForward("Unknown login requester.");
return null;
@ -415,10 +415,10 @@ public class TokenService {
return null;
}
Role resourceRole = realm.getIdm().getRole(RealmManager.RESOURCE_ROLE);
Role identityRequestRole = realm.getIdm().getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.getIdm().hasRole(client, resourceRole);
if (!isResource && !realm.getIdm().hasRole(client, identityRequestRole)) {
Role resourceRole = realm.getRole(RealmManager.RESOURCE_ROLE);
Role identityRequestRole = realm.getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client, resourceRole);
if (!isResource && !realm.hasRole(client, identityRequestRole)) {
securityFailureForward("Login requester not allowed to request login.");
identitySession.close();
return null;

View file

@ -148,30 +148,26 @@ public class AdapterTest {
public void testCredentialValidation() throws Exception {
test1CreateRealm();
User user = new SimpleUser("bburke");
realmModel.getIdm().add(user);
realmModel.addUser(user);
UserCredentialModel cred = new UserCredentialModel();
cred.setType(RequiredCredentialRepresentation.PASSWORD);
cred.setValue("geheim");
realmModel.updateCredential(user, cred);
IdentityManager idm = realmModel.getIdm();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getLoginName(), new Password("geheim"));
idm.validateCredentials(creds);
Assert.assertEquals(creds.getStatus(), Credentials.Status.VALID);
Assert.assertTrue(realmModel.validatePassword(user, "geheim"));
}
@Test
public void testRoles() throws Exception {
test1CreateRealm();
IdentityManager idm = realmModel.getIdm();
idm.add(new SimpleRole("admin"));
idm.add(new SimpleRole("user"));
realmModel.addRole(new SimpleRole("admin"));
realmModel.addRole(new SimpleRole("user"));
List<Role> roles = realmModel.getRoles();
Assert.assertEquals(5, roles.size());
SimpleUser user = new SimpleUser("bburke");
idm.add(user);
Role role = idm.getRole("user");
idm.grantRole(user, role);
Assert.assertTrue(idm.hasRole(user, role));
realmModel.addUser(user);
Role role = realmModel.getRole("user");
realmModel.grantRole(user, role);
Assert.assertTrue(realmModel.hasRole(user, role));
}

View file

@ -96,13 +96,13 @@ public class ImportTest {
manager.generateRealmKeys(defaultRealm);
defaultRealm.updateRealm();
defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
defaultRealm.addRole(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
RealmRepresentation rep = KeycloakTestBase.loadJson("testrealm.json");
RealmModel realm = manager.createRealm("demo", rep.getRealm());
manager.importRealm(rep, realm);
User user = realm.getIdm().getUser("loginclient");
User user = realm.getUser("loginclient");
Assert.assertNotNull(user);
Set<String> scopes = realm.getScope(user);
System.out.println("Scopes size: " + scopes.size());