keycloak-memoizeit

more stuff

7/11/2013 6:56:15 PM

Changes

pom.xml 11(+11 -0)

services/pom.xml 36(+36 -0)

services/src/main/java/org/keycloak/services/resources/SkeletonKeyApplication.java 55(+0 -55)

Details

diff --git a/core/src/main/java/org/keycloak/SkeletonKeyContextResolver.java b/core/src/main/java/org/keycloak/SkeletonKeyContextResolver.java
index 3bca480..9b83907 100755
--- a/core/src/main/java/org/keycloak/SkeletonKeyContextResolver.java
+++ b/core/src/main/java/org/keycloak/SkeletonKeyContextResolver.java
@@ -36,7 +36,7 @@ public class SkeletonKeyContextResolver implements ContextResolver<ObjectMapper>
    @Override
    public ObjectMapper getContext(Class<?> type)
    {
-      if (type.getPackage().getName().startsWith("org.jboss.resteasy.skeleton.key")) return mapper;
+      if (type.getPackage().getName().startsWith(getClass().getPackage().getName())) return mapper;
       return null;
    }
 }

pom.xml 11(+11 -0)

diff --git a/pom.xml b/pom.xml
index 2225e9b..53b9656 100755
--- a/pom.xml
+++ b/pom.xml
@@ -109,6 +109,12 @@
                 <version>${resteasy.version}</version>
             </dependency>
             <dependency>
+                <groupId>org.jboss.resteasy</groupId>
+                <artifactId>tjws</artifactId>
+                <version>${resteasy.version}</version>
+                <scope>provided</scope>
+            </dependency>
+            <dependency>
                 <groupId>org.codehaus.jackson</groupId>
                 <artifactId>jackson-core-asl</artifactId>
                 <version>1.9.12</version>
@@ -163,6 +169,11 @@
                 <artifactId>junit</artifactId>
                 <version>4.11</version>
             </dependency>
+            <dependency>
+                <groupId>org.hibernate.javax.persistence</groupId>
+                <artifactId>hibernate-jpa-2.0-api</artifactId>
+                <version>1.0.1.Final</version>
+            </dependency>
         </dependencies>
     </dependencyManagement>
 

services/pom.xml 36(+36 -0)

diff --git a/services/pom.xml b/services/pom.xml
index 8c097ae..5daecdd 100755
--- a/services/pom.xml
+++ b/services/pom.xml
@@ -43,6 +43,25 @@
             <groupId>org.jboss.resteasy</groupId>
             <artifactId>resteasy-jaxrs</artifactId>
             <scope>provided</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>log4j</groupId>
+                    <artifactId>log4j</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>slf4j-api</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>slf4j-simple</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.resteasy</groupId>
+            <artifactId>tjws</artifactId>
+            <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>org.jboss.resteasy</groupId>
@@ -94,6 +113,23 @@
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.hibernate.javax.persistence</groupId>
+            <artifactId>hibernate-jpa-2.0-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <version>1.3.161</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-entitymanager</artifactId>
+            <version>3.6.6.Final</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
     <build>
         <plugins>
diff --git a/services/src/main/java/org/keycloak/services/filters/IdentitySessionFilter.java b/services/src/main/java/org/keycloak/services/filters/IdentitySessionFilter.java
new file mode 100755
index 0000000..dbe8461
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/filters/IdentitySessionFilter.java
@@ -0,0 +1,38 @@
+package org.keycloak.services.filters;
+
+import org.jboss.resteasy.spi.ResteasyProviderFactory;
+import org.picketlink.idm.IdentitySession;
+import org.picketlink.idm.IdentitySessionFactory;
+
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+import javax.ws.rs.container.PreMatching;
+import java.io.IOException;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+@PreMatching
+public class IdentitySessionFilter implements ContainerRequestFilter, ContainerResponseFilter {
+    protected IdentitySessionFactory factory;
+
+    public IdentitySessionFilter(IdentitySessionFactory factory) {
+        this.factory = factory;
+    }
+
+    @Override
+    public void filter(ContainerRequestContext requestContext) throws IOException {
+        IdentitySession ctx = factory.createIdentitySession();
+        requestContext.setProperty(IdentitySession.class.getName(), ctx);
+        ResteasyProviderFactory.pushContext(IdentitySession.class, ctx);
+    }
+
+    @Override
+    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
+        IdentitySession ctx = (IdentitySession)requestContext.getProperty(IdentitySession.class.getName());
+        if (ctx != null) ctx.close();
+    }
+}
diff --git a/services/src/main/java/org/keycloak/services/managers/AccessCodeEntry.java b/services/src/main/java/org/keycloak/services/managers/AccessCodeEntry.java
new file mode 100755
index 0000000..d96b32b
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/managers/AccessCodeEntry.java
@@ -0,0 +1,49 @@
+package org.keycloak.services.managers;
+
+import org.keycloak.representations.SkeletonKeyToken;
+import org.picketlink.idm.model.User;
+
+import java.util.UUID;
+
+/**
+* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+* @version $Revision: 1 $
+*/
+public class AccessCodeEntry {
+    protected String id = UUID.randomUUID().toString() + System.currentTimeMillis();
+    protected long expiration;
+    protected SkeletonKeyToken token;
+    protected User client;
+
+    public boolean isExpired() {
+        return expiration != 0 && (System.currentTimeMillis() / 1000) > expiration;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public long getExpiration() {
+        return expiration;
+    }
+
+    public void setExpiration(long expiration) {
+        this.expiration = expiration;
+    }
+
+    public SkeletonKeyToken getToken() {
+        return token;
+    }
+
+    public void setToken(SkeletonKeyToken token) {
+        this.token = token;
+    }
+
+    public User getClient() {
+        return client;
+    }
+
+    public void setClient(User client) {
+        this.client = client;
+    }
+}
diff --git a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java
index 74fc03f..7b725da 100755
--- a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java
+++ b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java
@@ -24,107 +24,91 @@ import java.util.Set;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class AuthenticationManager
-{
-   protected Logger logger = Logger.getLogger(AuthenticationManager.class);
-   public static final String FORM_USERNAME = "username";
-   protected RealmManager adapter;
+public class AuthenticationManager {
+    protected Logger logger = Logger.getLogger(AuthenticationManager.class);
+    public static final String FORM_USERNAME = "username";
 
-   public AuthenticationManager(RealmManager adapter)
-   {
-      this.adapter = adapter;
-   }
+    /**
+     * Grabs token from headers, authenticates, authorizes
+     *
+     * @param realm
+     * @param headers
+     * @return
+     */
+    public boolean isRealmAdmin(RealmModel realm, HttpHeaders headers) {
+        User user = authenticateToken(realm, headers);
+        return realm.isRealmAdmin(user);
+    }
 
-   public User authenticateToken(RealmModel realm, HttpHeaders headers)
-   {
-      String tokenString = null;
-      String authHeader = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
-      if (authHeader == null)
-      {
-         throw new NotAuthorizedException("Bearer");
-      }
-      else
-      {
-         String[] split = authHeader.trim().split("\\s+");
-         if (split == null || split.length != 2) throw new NotAuthorizedException("Bearer");
-         if (!split[0].equalsIgnoreCase("Bearer")) throw new NotAuthorizedException("Bearer");
-         tokenString = split[1];
-      }
+    public User authenticateToken(RealmModel realm, HttpHeaders headers) {
+        String tokenString = null;
+        String authHeader = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
+        if (authHeader == null) {
+            throw new NotAuthorizedException("Bearer");
+        } else {
+            String[] split = authHeader.trim().split("\\s+");
+            if (split == null || split.length != 2) throw new NotAuthorizedException("Bearer");
+            if (!split[0].equalsIgnoreCase("Bearer")) throw new NotAuthorizedException("Bearer");
+            tokenString = split[1];
+        }
 
 
-      try
-      {
-         SkeletonKeyToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getId());
-         if (!token.isActive())
-         {
-            throw new NotAuthorizedException("token_expired");
-         }
-         User user = realm.getIdm().getUser(token.getPrincipal());
-         if (user == null || !user.isEnabled())
-         {
-            throw new NotAuthorizedException("invalid_user");
-         }
-         return user;
-      }
-      catch (VerificationException e)
-      {
-         logger.error("Failed to verify token", e);
-         throw new NotAuthorizedException("invalid_token");
-      }
-   }
-
-   public boolean authenticateForm(RealmModel realm, User user, MultivaluedMap<String, String> formData)
-   {
-      String username = user.getLoginName();
-      Set<String> types = new HashSet<String>();
+        try {
+            SkeletonKeyToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getId());
+            if (!token.isActive()) {
+                throw new NotAuthorizedException("token_expired");
+            }
+            User user = realm.getIdm().getUser(token.getPrincipal());
+            if (user == null || !user.isEnabled()) {
+                throw new NotAuthorizedException("invalid_user");
+            }
+            return user;
+        } catch (VerificationException e) {
+            logger.error("Failed to verify token", e);
+            throw new NotAuthorizedException("invalid_token");
+        }
+    }
 
-      for (RequiredCredentialModel credential : realm.getRequiredCredentials())
-      {
-         types.add(credential.getType());
-      }
+    public boolean authenticateForm(RealmModel realm, User user, MultivaluedMap<String, String> formData) {
+        String username = user.getLoginName();
+        Set<String> types = new HashSet<String>();
 
-      if (types.contains(RequiredCredentialRepresentation.PASSWORD))
-      {
-         String password = formData.getFirst(RequiredCredentialRepresentation.PASSWORD);
-         if (password == null)
-         {
-            logger.warn("Password not provided");
-            return false;
-         }
+        for (RequiredCredentialModel credential : realm.getRequiredCredentials()) {
+            types.add(credential.getType());
+        }
 
-         if (types.contains(RequiredCredentialRepresentation.TOTP))
-         {
-            String token = formData.getFirst(RequiredCredentialRepresentation.TOTP);
-            if (token == null)
-            {
-               logger.warn("TOTP token not provided");
-               return false;
+        if (types.contains(RequiredCredentialRepresentation.PASSWORD)) {
+            String password = formData.getFirst(RequiredCredentialRepresentation.PASSWORD);
+            if (password == null) {
+                logger.warn("Password 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;
-            }
-         }
-         else
-         {
-            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, new Password(password));
-            realm.getIdm().validateCredentials(creds);
-            if (creds.getStatus() != Credentials.Status.VALID)
-            {
-               return false;
+
+            if (types.contains(RequiredCredentialRepresentation.TOTP)) {
+                String token = formData.getFirst(RequiredCredentialRepresentation.TOTP);
+                if (token == null) {
+                    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;
+                }
+            } else {
+                UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, new Password(password));
+                realm.getIdm().validateCredentials(creds);
+                if (creds.getStatus() != Credentials.Status.VALID) {
+                    return false;
+                }
             }
-         }
-      }
-      else
-      {
-         logger.warn("Do not know how to authenticate user");
-         return false;
-      }
-      return true;
-   }
+        } else {
+            logger.warn("Do not know how to authenticate user");
+            return false;
+        }
+        return true;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/managers/InstallationManager.java b/services/src/main/java/org/keycloak/services/managers/InstallationManager.java
new file mode 100755
index 0000000..4550ce6
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/managers/InstallationManager.java
@@ -0,0 +1,29 @@
+package org.keycloak.services.managers;
+
+import org.keycloak.services.models.RealmManager;
+import org.keycloak.services.models.RealmModel;
+import org.keycloak.services.models.RequiredCredentialModel;
+import org.keycloak.services.resources.RegistrationService;
+import org.picketlink.idm.model.Realm;
+import org.picketlink.idm.model.SimpleRole;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class InstallationManager {
+    public void install(RealmManager manager) {
+        RealmModel defaultRealm = manager.createRealm(Realm.DEFAULT_REALM, Realm.DEFAULT_REALM);
+        defaultRealm.setName(Realm.DEFAULT_REALM);
+        defaultRealm.setEnabled(true);
+        defaultRealm.setTokenLifespan(300);
+        defaultRealm.setAccessCodeLifespan(60);
+        defaultRealm.setSslNotRequired(false);
+        defaultRealm.setCookieLoginAllowed(true);
+        manager.generateRealmKeys(defaultRealm);
+        defaultRealm.updateRealm();
+        defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
+        defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
+
+    }
+}
diff --git a/services/src/main/java/org/keycloak/services/managers/TokenManager.java b/services/src/main/java/org/keycloak/services/managers/TokenManager.java
index 4d1428c..6c01504 100755
--- a/services/src/main/java/org/keycloak/services/managers/TokenManager.java
+++ b/services/src/main/java/org/keycloak/services/managers/TokenManager.java
@@ -21,156 +21,123 @@ import java.util.Set;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class TokenManager
-{
-   protected RealmManager adapter;
-
-   public TokenManager(RealmManager adapter)
-   {
-      this.adapter = adapter;
-   }
-
-   public SkeletonKeyToken createScopedToken(SkeletonKeyScope scope, RealmModel realm, User client, User user)
-   {
-      SkeletonKeyToken token = new SkeletonKeyToken();
-      token.id(adapter.generateId());
-      token.principal(user.getLoginName());
-      token.audience(realm.getName());
-      token.issuedNow();
-      token.issuedFor(client.getLoginName());
-      if (realm.getTokenLifespan() > 0)
-      {
-         token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
-      }
-      Map<String, ResourceModel> resourceMap = realm.getResourceMap();
-
-      for (String res : scope.keySet())
-      {
-         ResourceModel resource = resourceMap.get(res);
-         Set<String> scopeMapping = resource.getScope(client);
-         Set<String> roleMapping = resource.getRoleMappings(user);
-         SkeletonKeyToken.Access access = token.addAccess(resource.getName());
-         for (String role : scope.get(res))
-         {
-            if (!scopeMapping.contains("*") && !scopeMapping.contains(role))
-            {
-               throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build());
+public class TokenManager {
+
+     public SkeletonKeyToken createScopedToken(SkeletonKeyScope scope, RealmModel realm, User client, User user) {
+        SkeletonKeyToken token = new SkeletonKeyToken();
+        token.id(RealmManager.generateId());
+        token.principal(user.getLoginName());
+        token.audience(realm.getName());
+        token.issuedNow();
+        token.issuedFor(client.getLoginName());
+        if (realm.getTokenLifespan() > 0) {
+            token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
+        }
+        Map<String, ResourceModel> resourceMap = realm.getResourceMap();
+
+        for (String res : scope.keySet()) {
+            ResourceModel resource = resourceMap.get(res);
+            Set<String> scopeMapping = resource.getScope(client);
+            Set<String> roleMapping = resource.getRoleMappings(user);
+            SkeletonKeyToken.Access access = token.addAccess(resource.getName());
+            for (String role : scope.get(res)) {
+                if (!scopeMapping.contains("*") && !scopeMapping.contains(role)) {
+                    throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build());
+                }
+                if (!roleMapping.contains(role)) {
+                    throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build());
+
+                }
+                access.addRole(role);
             }
-            if (!roleMapping.contains(role))
-            {
-               throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build());
-
+        }
+        return token;
+    }
+
+    public SkeletonKeyToken createScopedToken(String scopeParam, RealmModel realm, User client, User user) {
+        SkeletonKeyScope scope = decodeScope(scopeParam);
+        return createScopedToken(scope, realm, client, user);
+    }
+
+    public SkeletonKeyToken createLoginToken(RealmModel realm, User client, User user) {
+        Set<String> mapping = realm.getScope(client);
+        if (!mapping.contains("*")) {
+            throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized to request a user login.</p>").type("text/html").build());
+        }
+        SkeletonKeyToken token = createAccessToken(realm, user);
+        token.issuedFor(client.getLoginName());
+        return token;
+
+    }
+
+    public SkeletonKeyScope decodeScope(String scopeParam) {
+        SkeletonKeyScope scope = null;
+        byte[] bytes = Base64Url.decode(scopeParam);
+        try {
+            scope = JsonSerialization.fromBytes(SkeletonKeyScope.class, bytes);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        return scope;
+    }
+
+
+    public SkeletonKeyToken createAccessToken(RealmModel realm, User user) {
+        List<ResourceModel> resources = realm.getResources();
+        SkeletonKeyToken token = new SkeletonKeyToken();
+        token.id(RealmManager.generateId());
+        token.issuedNow();
+        token.principal(user.getLoginName());
+        token.audience(realm.getId());
+        if (realm.getTokenLifespan() > 0) {
+            token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
+        }
+
+        Set<String> realmMapping = realm.getRoleMappings(user);
+
+        if (realmMapping != null && realmMapping.size() > 0) {
+            SkeletonKeyToken.Access access = new SkeletonKeyToken.Access();
+            for (String role : realmMapping) {
+                access.addRole(role);
             }
-            access.addRole(role);
-         }
-      }
-      return token;
-   }
-
-   public SkeletonKeyToken createScopedToken(String scopeParam, RealmModel realm, User client, User user)
-   {
-      SkeletonKeyScope scope = decodeScope(scopeParam);
-      return createScopedToken(scope, realm, client, user);
-   }
-
-   public SkeletonKeyToken createLoginToken(RealmModel realm, User client, User user)
-   {
-      Set<String> mapping = realm.getScope(client);
-      if (!mapping.contains("*"))
-      {
-         throw new ForbiddenException(Response.status(403).entity("<h1>Security Alert</h1><p>Known client not authorized to request a user login.</p>").type("text/html").build());
-      }
-      SkeletonKeyToken token = createAccessToken(realm, user);
-      token.issuedFor(client.getLoginName());
-      return token;
-
-   }
-
-   public SkeletonKeyScope decodeScope(String scopeParam)
-   {
-      SkeletonKeyScope scope = null;
-      byte[] bytes = Base64Url.decode(scopeParam);
-      try
-      {
-         scope = JsonSerialization.fromBytes(SkeletonKeyScope.class, bytes);
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-      return scope;
-   }
-
-
-   public SkeletonKeyToken createAccessToken(RealmModel realm, User user)
-   {
-      List<ResourceModel> resources = realm.getResources();
-      SkeletonKeyToken token = new SkeletonKeyToken();
-      token.id(adapter.generateId());
-      token.issuedNow();
-      token.principal(user.getLoginName());
-      token.audience(realm.getId());
-      if (realm.getTokenLifespan() > 0)
-      {
-         token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
-      }
-
-      Set<String> realmMapping = realm.getRoleMappings(user);
-
-      if (realmMapping != null && realmMapping.size() > 0)
-      {
-         SkeletonKeyToken.Access access = new SkeletonKeyToken.Access();
-         for (String role : realmMapping)
-         {
-            access.addRole(role);
-         }
-         token.setRealmAccess(access);
-      }
-      if (resources != null)
-      {
-         for (ResourceModel resource : resources)
-         {
-            Set<String> mapping = resource.getRoleMappings(user);
-            if (mapping == null) continue;
-            SkeletonKeyToken.Access access = token.addAccess(resource.getName())
-                    .verifyCaller(resource.isSurrogateAuthRequired());
-            for (String role : mapping)
-            {
-               access.addRole(role);
+            token.setRealmAccess(access);
+        }
+        if (resources != null) {
+            for (ResourceModel resource : resources) {
+                Set<String> mapping = resource.getRoleMappings(user);
+                if (mapping == null) continue;
+                SkeletonKeyToken.Access access = token.addAccess(resource.getName())
+                        .verifyCaller(resource.isSurrogateAuthRequired());
+                for (String role : mapping) {
+                    access.addRole(role);
+                }
             }
-         }
-      }
-      return token;
-   }
-
-   public SkeletonKeyToken createIdentityToken(RealmModel realm, String username)
-   {
-      SkeletonKeyToken token = new SkeletonKeyToken();
-      token.id(adapter.generateId());
-      token.issuedNow();
-      token.principal(username);
-      token.audience(realm.getId());
-      if (realm.getTokenLifespan() > 0)
-      {
-         token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
-      }
-      return token;
-   }
-
-   public String encodeToken(RealmModel realm, SkeletonKeyToken token)
-   {
-      byte[] tokenBytes = null;
-      try
-      {
-         tokenBytes = JsonSerialization.toByteArray(token, false);
-      }
-      catch (Exception e)
-      {
-         throw new RuntimeException(e);
-      }
-      String encodedToken = new JWSBuilder()
-              .content(tokenBytes)
-              .rsa256(realm.getPrivateKey());
-      return encodedToken;
-   }
+        }
+        return token;
+    }
+
+    public SkeletonKeyToken createIdentityToken(RealmModel realm, String username) {
+        SkeletonKeyToken token = new SkeletonKeyToken();
+        token.id(RealmManager.generateId());
+        token.issuedNow();
+        token.principal(username);
+        token.audience(realm.getId());
+        if (realm.getTokenLifespan() > 0) {
+            token.expiration((System.currentTimeMillis() / 1000) + realm.getTokenLifespan());
+        }
+        return token;
+    }
+
+    public String encodeToken(RealmModel realm, SkeletonKeyToken token) {
+        byte[] tokenBytes = null;
+        try {
+            tokenBytes = JsonSerialization.toByteArray(token, false);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+        String encodedToken = new JWSBuilder()
+                .content(tokenBytes)
+                .rsa256(realm.getPrivateKey());
+        return encodedToken;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/RealmManager.java b/services/src/main/java/org/keycloak/services/models/RealmManager.java
index 02485bf..6ee87ce 100755
--- a/services/src/main/java/org/keycloak/services/models/RealmManager.java
+++ b/services/src/main/java/org/keycloak/services/models/RealmManager.java
@@ -1,49 +1,71 @@
 package org.keycloak.services.models;
 
+import org.keycloak.representations.idm.UserRepresentation;
+import org.picketlink.idm.IdentitySession;
 import org.picketlink.idm.IdentityManager;
-import org.picketlink.idm.internal.IdentityManagerFactory;
 import org.picketlink.idm.model.Realm;
+import org.picketlink.idm.model.Role;
 import org.picketlink.idm.model.SimpleAgent;
+import org.picketlink.idm.model.SimpleUser;
+import org.picketlink.idm.model.User;
 
+import javax.ws.rs.core.Response;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
 import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RealmManager
-{
-   private static AtomicLong counter = new AtomicLong(1);
-
-   public static String generateId()
-   {
-      return counter.getAndIncrement() + "-" + System.currentTimeMillis();
-   }
-
-   protected IdentityManagerFactory factory;
-
-   public RealmManager(IdentityManagerFactory factory)
-   {
-      this.factory = factory;
-   }
-
-   public RealmModel getRealm(String id)
-   {
-      Realm existing = factory.findRealm(id);
-      if (existing == null)
-      {
-         return null;
-      }
-      return new RealmModel(existing, factory);
-   }
-
-   public RealmModel create(String name)
-   {
-      Realm newRealm = factory.createRealm(generateId());
-      IdentityManager idm = factory.createIdentityManager(newRealm);
-      SimpleAgent agent = new SimpleAgent(RealmModel.REALM_AGENT_ID);
-      idm.add(agent);
-      return new RealmModel(newRealm, factory);
-   }
-
-}
+public class RealmManager {
+    private static AtomicLong counter = new AtomicLong(1);
+
+    public static String generateId() {
+        return counter.getAndIncrement() + "-" + System.currentTimeMillis();
+    }
+
+    protected IdentitySession IdentitySession;
+
+    public RealmManager(IdentitySession IdentitySession) {
+        this.IdentitySession = IdentitySession;
+    }
+
+    public RealmModel defaultRealm() {
+        return getRealm(Realm.DEFAULT_REALM);
+    }
+
+    public RealmModel getRealm(String id) {
+        Realm existing = IdentitySession.findRealm(id);
+        if (existing == null) {
+            return null;
+        }
+        return new RealmModel(existing, IdentitySession);
+    }
+
+    public RealmModel createRealm(String name) {
+        return createRealm(generateId(), name);
+    }
+
+    public RealmModel createRealm(String id, String name) {
+        Realm newRealm = IdentitySession.createRealm(id);
+        IdentityManager idm = IdentitySession.createIdentityManager(newRealm);
+        SimpleAgent agent = new SimpleAgent(RealmModel.REALM_AGENT_ID);
+        idm.add(agent);
+        RealmModel realm = new RealmModel(newRealm, IdentitySession);
+        return realm;
+    }
+
+    public void generateRealmKeys(RealmModel realm) {
+        KeyPair keyPair = null;
+        try {
+            keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException(e);
+        }
+        realm.setPrivateKey(keyPair.getPrivate());
+        realm.setPublicKey(keyPair.getPublic());
+        realm.updateRealm();
+    }
+    }
diff --git a/services/src/main/java/org/keycloak/services/models/RealmModel.java b/services/src/main/java/org/keycloak/services/models/RealmModel.java
index 6028bbf..235bba1 100755
--- a/services/src/main/java/org/keycloak/services/models/RealmModel.java
+++ b/services/src/main/java/org/keycloak/services/models/RealmModel.java
@@ -4,14 +4,14 @@ import org.bouncycastle.openssl.PEMWriter;
 import org.jboss.resteasy.security.PemUtils;
 import org.keycloak.representations.idm.RequiredCredentialRepresentation;
 import org.keycloak.services.models.relationships.RealmAdminRelationship;
-import org.keycloak.services.models.relationships.RealmResourceRelationship;
+import org.keycloak.services.models.relationships.ResourceRelationship;
 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.Password;
 import org.picketlink.idm.credential.TOTPCredential;
 import org.picketlink.idm.credential.X509CertificateCredentials;
-import org.picketlink.idm.internal.IdentityManagerFactory;
 import org.picketlink.idm.model.Agent;
 import org.picketlink.idm.model.Attribute;
 import org.picketlink.idm.model.Grant;
@@ -39,374 +39,302 @@ import java.util.Set;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RealmModel
-{
-   public static final String REALM_AGENT_ID = "_realm_";
-   public static final String REALM_NAME = "name";
-   public static final String REALM_ACCESS_CODE_LIFESPAN = "accessCodeLifespan";
-   public static final String REALM_TOKEN_LIFESPAN = "tokenLifespan";
-   public static final String REALM_PRIVATE_KEY = "privateKey";
-   public static final String REALM_PUBLIC_KEY = "publicKey";
-   public static final String REALM_IS_SSL_NOT_REQUIRED = "isSSLNotRequired";
-   public static final String REALM_IS_COOKIE_LOGIN_ALLOWED = "isCookieLoginAllowed";
-
-   protected Realm realm;
-   protected Agent realmAgent;
-   protected IdentityManagerFactory factory;
-   protected volatile transient PublicKey publicKey;
-   protected volatile transient PrivateKey privateKey;
-
-   public RealmModel(Realm realm, IdentityManagerFactory factory)
-   {
-      this.realm = realm;
-      this.factory = factory;
-      realmAgent = getIdm().getAgent(REALM_AGENT_ID);
-   }
-
-   public IdentityManager getIdm()
-   {
-      return factory.createIdentityManager(realm);
-   }
-
-   public void updateRealm()
-   {
-      getIdm().update(realmAgent);
-   }
-
-   public String getId()
-   {
-      return realm.getId();
-   }
-
-   public String getName()
-   {
-      return (String)realmAgent.getAttribute(REALM_NAME).getValue();
-   }
-
-   public void setName(String name)
-   {
-      realmAgent.setAttribute(new Attribute<String>(REALM_NAME, name));
-   }
-
-   public boolean isEnabled()
-   {
-      return realmAgent.isEnabled();
-   }
-
-   public void setEnabled(boolean enabled)
-   {
-      realmAgent.setEnabled(enabled);
-   }
-
-   public boolean isSslNotRequired()
-   {
-      return (Boolean)realmAgent.getAttribute(REALM_IS_SSL_NOT_REQUIRED).getValue();
-   }
-
-   public void setSslNotRequired(boolean sslNotRequired)
-   {
-      realmAgent.setAttribute(new Attribute<Boolean>(REALM_IS_SSL_NOT_REQUIRED, sslNotRequired));
-   }
-
-   public boolean isCookieLoginAllowed()
-   {
-      return (Boolean)realmAgent.getAttribute(REALM_IS_COOKIE_LOGIN_ALLOWED).getValue();
-   }
-
-   public void setCookieLoginAllowed(boolean cookieLoginAllowed)
-   {
-      realmAgent.setAttribute(new Attribute<Boolean>(REALM_IS_COOKIE_LOGIN_ALLOWED, cookieLoginAllowed));
-   }
-
-   public long getTokenLifespan()
-   {
-      return (Long) realmAgent.getAttribute(REALM_TOKEN_LIFESPAN).getValue();
-   }
-
-   public void setTokenLifespan(long tokenLifespan)
-   {
-      realmAgent.setAttribute(new Attribute<Long>(REALM_TOKEN_LIFESPAN,tokenLifespan));
-   }
-
-   public long getAccessCodeLifespan()
-   {
-      return (Long) realmAgent.getAttribute(REALM_ACCESS_CODE_LIFESPAN).getValue();
-   }
-
-   public void setAccessCodeLifespan(long accessCodeLifespan)
-   {
-      realmAgent.setAttribute(new Attribute<Long>(REALM_ACCESS_CODE_LIFESPAN, accessCodeLifespan));
-   }
-
-   public String getPublicKeyPem()
-   {
-      return (String) realmAgent.getAttribute(REALM_PUBLIC_KEY).getValue();
-   }
-
-   public void setPublicKeyPem(String publicKeyPem)
-   {
-      realmAgent.setAttribute(new Attribute<String>(REALM_PUBLIC_KEY, publicKeyPem));
-      this.publicKey = null;
-   }
-
-   public String getPrivateKeyPem()
-   {
-      return (String) realmAgent.getAttribute(REALM_PRIVATE_KEY).getValue();
-   }
-
-   public void setPrivateKeyPem(String privateKeyPem)
-   {
-      realmAgent.setAttribute(new Attribute<String>(REALM_PRIVATE_KEY, privateKeyPem));
-      this.privateKey = null;
-   }
-
-   public PublicKey getPublicKey()
-   {
-      if (publicKey != null) return publicKey;
-      String pem = getPublicKeyPem();
-      if (pem != null)
-      {
-         try
-         {
-            publicKey = PemUtils.decodePublicKey(pem);
-         }
-         catch (Exception e)
-         {
+public class RealmModel {
+    public static final String REALM_AGENT_ID = "_realm_";
+    public static final String REALM_NAME = "name";
+    public static final String REALM_ACCESS_CODE_LIFESPAN = "accessCodeLifespan";
+    public static final String REALM_TOKEN_LIFESPAN = "tokenLifespan";
+    public static final String REALM_PRIVATE_KEY = "privateKey";
+    public static final String REALM_PUBLIC_KEY = "publicKey";
+    public static final String REALM_IS_SSL_NOT_REQUIRED = "isSSLNotRequired";
+    public static final String REALM_IS_COOKIE_LOGIN_ALLOWED = "isCookieLoginAllowed";
+
+    protected Realm realm;
+    protected Agent realmAgent;
+    protected IdentitySession IdentitySession;
+    protected volatile transient PublicKey publicKey;
+    protected volatile transient PrivateKey privateKey;
+
+    public RealmModel(Realm realm, IdentitySession factory) {
+        this.realm = realm;
+        this.IdentitySession = factory;
+        realmAgent = getIdm().getAgent(REALM_AGENT_ID);
+    }
+
+    public IdentityManager getIdm() {
+        return IdentitySession.createIdentityManager(realm);
+    }
+
+    public void updateRealm() {
+        getIdm().update(realmAgent);
+    }
+
+    public String getId() {
+        return realm.getId();
+    }
+
+    public String getName() {
+        return (String) realmAgent.getAttribute(REALM_NAME).getValue();
+    }
+
+    public void setName(String name) {
+        realmAgent.setAttribute(new Attribute<String>(REALM_NAME, name));
+    }
+
+    public boolean isEnabled() {
+        return realmAgent.isEnabled();
+    }
+
+    public void setEnabled(boolean enabled) {
+        realmAgent.setEnabled(enabled);
+    }
+
+    public boolean isSslNotRequired() {
+        return (Boolean) realmAgent.getAttribute(REALM_IS_SSL_NOT_REQUIRED).getValue();
+    }
+
+    public void setSslNotRequired(boolean sslNotRequired) {
+        realmAgent.setAttribute(new Attribute<Boolean>(REALM_IS_SSL_NOT_REQUIRED, sslNotRequired));
+    }
+
+    public boolean isCookieLoginAllowed() {
+        return (Boolean) realmAgent.getAttribute(REALM_IS_COOKIE_LOGIN_ALLOWED).getValue();
+    }
+
+    public void setCookieLoginAllowed(boolean cookieLoginAllowed) {
+        realmAgent.setAttribute(new Attribute<Boolean>(REALM_IS_COOKIE_LOGIN_ALLOWED, cookieLoginAllowed));
+    }
+
+    public long getTokenLifespan() {
+        return (Long) realmAgent.getAttribute(REALM_TOKEN_LIFESPAN).getValue();
+    }
+
+    public void setTokenLifespan(long tokenLifespan) {
+        realmAgent.setAttribute(new Attribute<Long>(REALM_TOKEN_LIFESPAN, tokenLifespan));
+    }
+
+    public long getAccessCodeLifespan() {
+        return (Long) realmAgent.getAttribute(REALM_ACCESS_CODE_LIFESPAN).getValue();
+    }
+
+    public void setAccessCodeLifespan(long accessCodeLifespan) {
+        realmAgent.setAttribute(new Attribute<Long>(REALM_ACCESS_CODE_LIFESPAN, accessCodeLifespan));
+    }
+
+    public String getPublicKeyPem() {
+        return (String) realmAgent.getAttribute(REALM_PUBLIC_KEY).getValue();
+    }
+
+    public void setPublicKeyPem(String publicKeyPem) {
+        realmAgent.setAttribute(new Attribute<String>(REALM_PUBLIC_KEY, publicKeyPem));
+        this.publicKey = null;
+    }
+
+    public String getPrivateKeyPem() {
+        return (String) realmAgent.getAttribute(REALM_PRIVATE_KEY).getValue();
+    }
+
+    public void setPrivateKeyPem(String privateKeyPem) {
+        realmAgent.setAttribute(new Attribute<String>(REALM_PRIVATE_KEY, privateKeyPem));
+        this.privateKey = null;
+    }
+
+    public PublicKey getPublicKey() {
+        if (publicKey != null) return publicKey;
+        String pem = getPublicKeyPem();
+        if (pem != null) {
+            try {
+                publicKey = PemUtils.decodePublicKey(pem);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return publicKey;
+    }
+
+    public void setPublicKey(PublicKey publicKey) {
+        this.publicKey = publicKey;
+        StringWriter writer = new StringWriter();
+        PEMWriter pemWriter = new PEMWriter(writer);
+        try {
+            pemWriter.writeObject(publicKey);
+            pemWriter.flush();
+        } catch (IOException e) {
             throw new RuntimeException(e);
-         }
-      }
-      return publicKey;
-   }
-
-   public void setPublicKey(PublicKey publicKey)
-   {
-      this.publicKey = publicKey;
-      StringWriter writer = new StringWriter();
-      PEMWriter pemWriter = new PEMWriter(writer);
-      try
-      {
-         pemWriter.writeObject(publicKey);
-         pemWriter.flush();
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-      String s = writer.toString();
-      setPublicKeyPem(PemUtils.removeBeginEnd(s));
-   }
-
-   public PrivateKey getPrivateKey()
-   {
-      if (privateKey != null) return privateKey;
-      String pem = getPrivateKeyPem();
-      if (pem != null)
-      {
-         try
-         {
-            privateKey = PemUtils.decodePrivateKey(pem);
-         }
-         catch (Exception e)
-         {
+        }
+        String s = writer.toString();
+        setPublicKeyPem(PemUtils.removeBeginEnd(s));
+    }
+
+    public PrivateKey getPrivateKey() {
+        if (privateKey != null) return privateKey;
+        String pem = getPrivateKeyPem();
+        if (pem != null) {
+            try {
+                privateKey = PemUtils.decodePrivateKey(pem);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return privateKey;
+    }
+
+    public void setPrivateKey(PrivateKey privateKey) {
+        this.privateKey = privateKey;
+        StringWriter writer = new StringWriter();
+        PEMWriter pemWriter = new PEMWriter(writer);
+        try {
+            pemWriter.writeObject(privateKey);
+            pemWriter.flush();
+        } catch (IOException e) {
             throw new RuntimeException(e);
-         }
-      }
-      return privateKey;
-   }
-
-   public void setPrivateKey(PrivateKey privateKey)
-   {
-      this.privateKey = privateKey;
-      StringWriter writer = new StringWriter();
-      PEMWriter pemWriter = new PEMWriter(writer);
-      try
-      {
-         pemWriter.writeObject(privateKey);
-         pemWriter.flush();
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-      String s = writer.toString();
-      setPrivateKeyPem(PemUtils.removeBeginEnd(s));
-   }
-
-   public List<RequiredCredentialModel> getRequiredCredentials()
-   {
-      IdentityManager idm = getIdm();
-      Agent realmAgent = idm.getAgent(REALM_AGENT_ID);
-      RelationshipQuery<RequiredCredentialRelationship> query = idm.createRelationshipQuery(RequiredCredentialRelationship.class);
-      query.setParameter(RequiredCredentialRelationship.REALM_AGENT, realmAgent);
-      List<RequiredCredentialRelationship> results = query.getResultList();
-      List<RequiredCredentialModel> rtn = new ArrayList<RequiredCredentialModel>();
-      for (RequiredCredentialRelationship relationship : results)
-      {
-         RequiredCredentialModel model = new RequiredCredentialModel();
-         model.setInput(relationship.isInput());
-         model.setSecret(relationship.isSecret());
-         model.setType(relationship.getCredentialType());
-         rtn.add(model);
-      }
-      return rtn;
-   }
-
-   public void addRequiredCredential(RequiredCredentialModel cred)
-   {
-      IdentityManager idm = getIdm();
-      Agent realmAgent = idm.getAgent(REALM_AGENT_ID);
-      RequiredCredentialRelationship relationship = new RequiredCredentialRelationship();
-      relationship.setCredentialType(cred.getType());
-      relationship.setInput(cred.isInput());
-      relationship.setSecret(cred.isSecret());
-      relationship.setRealmAgent(realmAgent);
-      idm.add(relationship);
-   }
-
-   public void updateCredential(User user, UserCredentialModel cred)
-   {
-      IdentityManager idm = getIdm();
-      if (cred.getType().equals(RequiredCredentialRepresentation.PASSWORD))
-      {
-         Password password = new Password(cred.getValue());
-         idm.updateCredential(user, password);
-      }
-      else if (cred.getType().equals(RequiredCredentialRepresentation.TOTP))
-      {
-         TOTPCredential totp = new TOTPCredential(cred.getValue());
-         idm.updateCredential(user, totp);
-      }
-      else if (cred.getType().equals(RequiredCredentialRepresentation.CLIENT_CERT))
-      {
-         X509Certificate cert = null;
-         try
-         {
-            cert = org.keycloak.PemUtils.decodeCertificate(cred.getValue());
-         }
-         catch (Exception e)
-         {
-            throw new RuntimeException(e);
-         }
-         X509CertificateCredentials creds = new X509CertificateCredentials(cert);
-         idm.updateCredential(user, creds);
-      }
-   }
-
-   public List<Role> getRoles()
-   {
-      IdentityManager idm = getIdm();
-      IdentityQuery<Role> query = idm.createIdentityQuery(Role.class);
-      query.setParameter(Role.PARTITION, realm);
-      return query.getResultList();
-   }
-
-
-   protected ResourceModel loadResource(Agent resource)
-   {
-      Tier tier = factory.findTier(resource.getPartition().getId());
-      return new ResourceModel(tier, resource, this, factory);
-   }
-
-   /**
-    * Key name, value resource
-    *
-    * @return
-    */
-   public Map<String, ResourceModel> getResourceMap()
-   {
-      Map<String, ResourceModel> resourceMap = new HashMap<String, ResourceModel>();
-      for (ResourceModel resource : getResources())
-      {
-         resourceMap.put(resource.getName(), resource);
-      }
-      return resourceMap;
-   }
-
-   public List<ResourceModel> getResources()
-   {
-      IdentityManager idm = getIdm();
-      RelationshipQuery<RealmResourceRelationship> query = idm.createRelationshipQuery(RealmResourceRelationship.class);
-      query.setParameter(RealmResourceRelationship.REALM_AGENT, realmAgent);
-      List<RealmResourceRelationship> results = query.getResultList();
-      List<ResourceModel> resources = new ArrayList<ResourceModel>();
-      for (RealmResourceRelationship relationship : results)
-      {
-         ResourceModel model = loadResource(relationship.getResourceAgent());
-         resources.add(model);
-      }
-
-      return resources;
-   }
-
-   public ResourceModel addResource(String name)
-   {
-      Tier newTier = factory.createTier(RealmManager.generateId());
-      IdentityManager idm = factory.createIdentityManager(newTier);
-      SimpleAgent resourceAgent = new SimpleAgent(ResourceModel.RESOURCE_AGENT_ID);
-      resourceAgent.setAttribute(new Attribute<String>(ResourceModel.RESOURCE_NAME, name));
-      idm.add(resourceAgent);
-      idm = getIdm();
-      RealmResourceRelationship relationship = new RealmResourceRelationship();
-      relationship.setRealmAgent(realmAgent);
-      relationship.setResourceAgent(resourceAgent);
-      idm.add(relationship);
-      return new ResourceModel(newTier, resourceAgent, this, factory);
-   }
-
-   public Set<String> getRoleMappings(User user)
-   {
-      RelationshipQuery<Grant> query = getIdm().createRelationshipQuery(Grant.class);
-      query.setParameter(Grant.ASSIGNEE, user);
-      List<Grant> grants = query.getResultList();
-      HashSet<String> set = new HashSet<String>();
-      for (Grant grant : grants)
-      {
-         if (grant.getRole().getPartition().getId().equals(realm.getId()))set.add(grant.getRole().getName());
-      }
-      return set;
-   }
-
-   public void addScope(Agent agent, String roleName)
-   {
-      IdentityManager idm = getIdm();
-      Role role = idm.getRole(roleName);
-      if (role == null) throw new RuntimeException("role not found");
-      ScopeRelationship scope = new ScopeRelationship();
-      scope.setClient(agent);
-      scope.setScope(role);
-
-   }
-
-
-   public Set<String> getScope(Agent agent)
-   {
-      RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class);
-      query.setParameter(ScopeRelationship.CLIENT, agent);
-      List<ScopeRelationship> scope = query.getResultList();
-      HashSet<String> set = new HashSet<String>();
-      for (ScopeRelationship rel : scope)
-      {
-         if (rel.getScope().getPartition().getId().equals(realm.getId())) set.add(rel.getScope().getName());
-      }
-      return set;
-   }
-
-   public boolean isRealmAdmin(Agent agent)
-   {
-      IdentityManager idm = getIdm();
-      RelationshipQuery<RealmAdminRelationship> query = idm.createRelationshipQuery(RealmAdminRelationship.class);
-      query.setParameter(RealmAdminRelationship.REALM, realm);
-      query.setParameter(RealmAdminRelationship.ADMIN, agent);
-      List<RealmAdminRelationship> results = query.getResultList();
-      return results.size() > 0;
-   }
-
-   public void addRealmAdmin(Agent agent)
-   {
-      IdentityManager idm = getIdm();
-      RealmAdminRelationship relationship = new RealmAdminRelationship();
-      relationship.setAdmin(agent);
-      relationship.setRealm(realm);
-      idm.add(relationship);
-   }
+        }
+        String s = writer.toString();
+        setPrivateKeyPem(PemUtils.removeBeginEnd(s));
+    }
+
+    public List<RequiredCredentialModel> getRequiredCredentials() {
+        IdentityManager idm = getIdm();
+        Agent realmAgent = idm.getAgent(REALM_AGENT_ID);
+        RelationshipQuery<RequiredCredentialRelationship> query = idm.createRelationshipQuery(RequiredCredentialRelationship.class);
+        query.setParameter(RequiredCredentialRelationship.REALM_AGENT, realmAgent);
+        List<RequiredCredentialRelationship> results = query.getResultList();
+        List<RequiredCredentialModel> rtn = new ArrayList<RequiredCredentialModel>();
+        for (RequiredCredentialRelationship relationship : results) {
+            RequiredCredentialModel model = new RequiredCredentialModel();
+            model.setInput(relationship.isInput());
+            model.setSecret(relationship.isSecret());
+            model.setType(relationship.getCredentialType());
+            rtn.add(model);
+        }
+        return rtn;
+    }
+
+    public void addRequiredCredential(RequiredCredentialModel cred) {
+        IdentityManager idm = getIdm();
+        Agent realmAgent = idm.getAgent(REALM_AGENT_ID);
+        RequiredCredentialRelationship relationship = new RequiredCredentialRelationship();
+        relationship.setCredentialType(cred.getType());
+        relationship.setInput(cred.isInput());
+        relationship.setSecret(cred.isSecret());
+        relationship.setRealmAgent(realmAgent);
+        idm.add(relationship);
+    }
+
+    public void updateCredential(User user, UserCredentialModel cred) {
+        IdentityManager idm = getIdm();
+        if (cred.getType().equals(RequiredCredentialRepresentation.PASSWORD)) {
+            Password password = new Password(cred.getValue());
+            idm.updateCredential(user, password);
+        } else if (cred.getType().equals(RequiredCredentialRepresentation.TOTP)) {
+            TOTPCredential totp = new TOTPCredential(cred.getValue());
+            idm.updateCredential(user, totp);
+        } else if (cred.getType().equals(RequiredCredentialRepresentation.CLIENT_CERT)) {
+            X509Certificate cert = null;
+            try {
+                cert = org.keycloak.PemUtils.decodeCertificate(cred.getValue());
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+            X509CertificateCredentials creds = new X509CertificateCredentials(cert);
+            idm.updateCredential(user, creds);
+        }
+    }
+
+    public List<Role> getRoles() {
+        IdentityManager idm = getIdm();
+        IdentityQuery<Role> query = idm.createIdentityQuery(Role.class);
+        query.setParameter(Role.PARTITION, realm);
+        return query.getResultList();
+    }
+
+
+    /**
+     * Key name, value resource
+     *
+     * @return
+     */
+    public Map<String, ResourceModel> getResourceMap() {
+        Map<String, ResourceModel> resourceMap = new HashMap<String, ResourceModel>();
+        for (ResourceModel resource : getResources()) {
+            resourceMap.put(resource.getName(), resource);
+        }
+        return resourceMap;
+    }
+
+    public List<ResourceModel> getResources() {
+        IdentityManager idm = getIdm();
+        RelationshipQuery<ResourceRelationship> query = idm.createRelationshipQuery(ResourceRelationship.class);
+        query.setParameter(ResourceRelationship.REALM_AGENT, realmAgent);
+        List<ResourceRelationship> results = query.getResultList();
+        List<ResourceModel> resources = new ArrayList<ResourceModel>();
+        for (ResourceRelationship relationship : results) {
+            Tier resourceTier = IdentitySession.findTier(relationship.getResourceId());
+            ResourceModel model = new ResourceModel(resourceTier,relationship, this, IdentitySession);
+            resources.add(model);
+        }
+
+        return resources;
+    }
+
+    public ResourceModel addResource(String name) {
+        Tier newTier = IdentitySession.createTier(RealmManager.generateId());
+        IdentityManager idm = getIdm();
+        ResourceRelationship relationship = new ResourceRelationship();
+        relationship.setResourceName(name);
+        relationship.setRealmAgent(realmAgent);
+        relationship.setResourceId(newTier.getId());
+        idm.add(relationship);
+        return new ResourceModel(newTier, relationship, this, IdentitySession);
+    }
+
+    public Set<String> getRoleMappings(User user) {
+        RelationshipQuery<Grant> query = getIdm().createRelationshipQuery(Grant.class);
+        query.setParameter(Grant.ASSIGNEE, user);
+        List<Grant> grants = query.getResultList();
+        HashSet<String> set = new HashSet<String>();
+        for (Grant grant : grants) {
+            if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(grant.getRole().getName());
+        }
+        return set;
+    }
+
+    public void addScope(Agent agent, String roleName) {
+        IdentityManager idm = getIdm();
+        Role role = idm.getRole(roleName);
+        if (role == null) throw new RuntimeException("role not found");
+        ScopeRelationship scope = new ScopeRelationship();
+        scope.setClient(agent);
+        scope.setScope(role);
+
+    }
+
+
+    public Set<String> getScope(Agent agent) {
+        RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class);
+        query.setParameter(ScopeRelationship.CLIENT, agent);
+        List<ScopeRelationship> scope = query.getResultList();
+        HashSet<String> set = new HashSet<String>();
+        for (ScopeRelationship rel : scope) {
+            if (rel.getScope().getPartition().getId().equals(realm.getId())) set.add(rel.getScope().getName());
+        }
+        return set;
+    }
+
+    public boolean isRealmAdmin(Agent agent) {
+        IdentityManager idm = new RealmManager(IdentitySession).defaultRealm().getIdm();
+        RelationshipQuery<RealmAdminRelationship> query = idm.createRelationshipQuery(RealmAdminRelationship.class);
+        query.setParameter(RealmAdminRelationship.REALM, realm.getId());
+        query.setParameter(RealmAdminRelationship.ADMIN, agent);
+        List<RealmAdminRelationship> results = query.getResultList();
+        return results.size() > 0;
+    }
+
+    public void addRealmAdmin(Agent agent) {
+        IdentityManager idm = new RealmManager(IdentitySession).defaultRealm().getIdm();
+        RealmAdminRelationship relationship = new RealmAdminRelationship();
+        relationship.setAdmin(agent);
+        relationship.setRealm(realm.getId());
+        idm.add(relationship);
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/relationships/RealmAdminRelationship.java b/services/src/main/java/org/keycloak/services/models/relationships/RealmAdminRelationship.java
index cb24a98..cf68d46 100755
--- a/services/src/main/java/org/keycloak/services/models/relationships/RealmAdminRelationship.java
+++ b/services/src/main/java/org/keycloak/services/models/relationships/RealmAdminRelationship.java
@@ -4,6 +4,7 @@ import org.picketlink.idm.model.AbstractAttributedType;
 import org.picketlink.idm.model.Agent;
 import org.picketlink.idm.model.Realm;
 import org.picketlink.idm.model.Relationship;
+import org.picketlink.idm.model.annotation.AttributeProperty;
 import org.picketlink.idm.model.annotation.IdentityProperty;
 import org.picketlink.idm.query.RelationshipQueryParameter;
 
@@ -11,48 +12,43 @@ import org.picketlink.idm.query.RelationshipQueryParameter;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RealmAdminRelationship extends AbstractAttributedType implements Relationship
-{
-   private static final long serialVersionUID = 1L;
-
-   public static final RelationshipQueryParameter REALM = new RelationshipQueryParameter() {
-
-      @Override
-      public String getName() {
-         return "realm";
-      }
-   };
-
-   public static final RelationshipQueryParameter ADMIN = new RelationshipQueryParameter() {
-
-      @Override
-      public String getName() {
-         return "admin";
-      }
-   };
-
-   protected Realm realm;
-   protected Agent admin;
-
-   @IdentityProperty
-   public Realm getRealm()
-   {
-      return realm;
-   }
-
-   public void setRealm(Realm realm)
-   {
-      this.realm = realm;
-   }
-
-   @IdentityProperty
-   public Agent getAdmin()
-   {
-      return admin;
-   }
-
-   public void setAdmin(Agent admin)
-   {
-      this.admin = admin;
-   }
+public class RealmAdminRelationship extends AbstractAttributedType implements Relationship {
+    private static final long serialVersionUID = 1L;
+
+    public static final RelationshipQueryParameter REALM = new RelationshipQueryParameter() {
+
+        @Override
+        public String getName() {
+            return "realm";
+        }
+    };
+
+    public static final RelationshipQueryParameter ADMIN = new RelationshipQueryParameter() {
+
+        @Override
+        public String getName() {
+            return "admin";
+        }
+    };
+
+    protected String realm;
+    protected Agent admin;
+
+    @AttributeProperty
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    @IdentityProperty
+    public Agent getAdmin() {
+        return admin;
+    }
+
+    public void setAdmin(Agent admin) {
+        this.admin = admin;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/relationships/RequiredCredentialRelationship.java b/services/src/main/java/org/keycloak/services/models/relationships/RequiredCredentialRelationship.java
index 48a1c90..59ce02d 100755
--- a/services/src/main/java/org/keycloak/services/models/relationships/RequiredCredentialRelationship.java
+++ b/services/src/main/java/org/keycloak/services/models/relationships/RequiredCredentialRelationship.java
@@ -11,69 +11,59 @@ import org.picketlink.idm.query.RelationshipQueryParameter;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RequiredCredentialRelationship extends AbstractAttributedType implements Relationship
-{
-   private static final long serialVersionUID = 1L;
+public class RequiredCredentialRelationship extends AbstractAttributedType implements Relationship {
+    private static final long serialVersionUID = 1L;
 
-   public static final RelationshipQueryParameter REALM_AGENT = new RelationshipQueryParameter() {
+    public static final RelationshipQueryParameter REALM_AGENT = new RelationshipQueryParameter() {
 
-      @Override
-      public String getName() {
-         return "realmAgent";
-      }
-   };
+        @Override
+        public String getName() {
+            return "realmAgent";
+        }
+    };
 
 
-   protected Agent realmAgent;
-   protected String credentialType;
-   protected boolean input;
-   protected boolean secret;
+    protected Agent realmAgent;
+    protected String credentialType;
+    protected boolean input;
+    protected boolean secret;
 
-   public RequiredCredentialRelationship()
-   {
-   }
+    public RequiredCredentialRelationship() {
+    }
 
-   @IdentityProperty
-   public Agent getRealmAgent()
-   {
-      return realmAgent;
-   }
+    @IdentityProperty
+    public Agent getRealmAgent() {
+        return realmAgent;
+    }
 
-   public void setRealmAgent(Agent realmAgent)
-   {
-      this.realmAgent = realmAgent;
-   }
+    public void setRealmAgent(Agent realmAgent) {
+        this.realmAgent = realmAgent;
+    }
 
-   @AttributeProperty
-   public String getCredentialType()
-   {
-      return credentialType;
-   }
+    @AttributeProperty
+    public String getCredentialType() {
+        return credentialType;
+    }
 
-   public void setCredentialType(String credentialType)
-   {
-      this.credentialType = credentialType;
-   }
+    public void setCredentialType(String credentialType) {
+        this.credentialType = credentialType;
+    }
 
-   @AttributeProperty
-   public boolean isInput()
-   {
-      return input;
-   }
+    @AttributeProperty
+    public boolean isInput() {
+        return input;
+    }
 
-   public void setInput(boolean input)
-   {
-      this.input = input;
-   }
+    public void setInput(boolean input) {
+        this.input = input;
+    }
 
-   @AttributeProperty
-   public boolean isSecret()
-   {
-      return secret;
-   }
+    @AttributeProperty
+    public boolean isSecret() {
+        return secret;
+    }
 
-   public void setSecret(boolean secret)
-   {
-      this.secret = secret;
-   }
+    public void setSecret(boolean secret) {
+        this.secret = secret;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/relationships/ScopeRelationship.java b/services/src/main/java/org/keycloak/services/models/relationships/ScopeRelationship.java
index b8bea48..7221c72 100755
--- a/services/src/main/java/org/keycloak/services/models/relationships/ScopeRelationship.java
+++ b/services/src/main/java/org/keycloak/services/models/relationships/ScopeRelationship.java
@@ -11,40 +11,35 @@ import org.picketlink.idm.query.RelationshipQueryParameter;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class ScopeRelationship extends AbstractAttributedType implements Relationship
-{
-   private static final long serialVersionUID = 1L;
-
-   public static final RelationshipQueryParameter CLIENT = new RelationshipQueryParameter() {
-
-      @Override
-      public String getName() {
-         return "client";
-      }
-   };
-
-   protected Agent client;
-   protected Role scope;
-
-   @IdentityProperty
-   public Agent getClient()
-   {
-      return client;
-   }
-
-   public void setClient(Agent client)
-   {
-      this.client = client;
-   }
-
-   @IdentityProperty
-   public Role getScope()
-   {
-      return scope;
-   }
-
-   public void setScope(Role scope)
-   {
-      this.scope = scope;
-   }
+public class ScopeRelationship extends AbstractAttributedType implements Relationship {
+    private static final long serialVersionUID = 1L;
+
+    public static final RelationshipQueryParameter CLIENT = new RelationshipQueryParameter() {
+
+        @Override
+        public String getName() {
+            return "client";
+        }
+    };
+
+    protected Agent client;
+    protected Role scope;
+
+    @IdentityProperty
+    public Agent getClient() {
+        return client;
+    }
+
+    public void setClient(Agent client) {
+        this.client = client;
+    }
+
+    @IdentityProperty
+    public Role getScope() {
+        return scope;
+    }
+
+    public void setScope(Role scope) {
+        this.scope = scope;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java b/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
index 6476ef7..c8ca584 100755
--- a/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
+++ b/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
@@ -1,42 +1,48 @@
 package org.keycloak.services.models;
 
+import org.keycloak.representations.idm.RequiredCredentialRepresentation;
+
 /**
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RequiredCredentialModel
-{
-   protected String type;
-   protected boolean input;
-   protected boolean secret;
-
-   public String getType()
-   {
-      return type;
-   }
-
-   public void setType(String type)
-   {
-      this.type = type;
-   }
-
-   public boolean isInput()
-   {
-      return input;
-   }
-
-   public void setInput(boolean input)
-   {
-      this.input = input;
-   }
-
-   public boolean isSecret()
-   {
-      return secret;
-   }
-
-   public void setSecret(boolean secret)
-   {
-      this.secret = secret;
-   }
+public class RequiredCredentialModel {
+    protected String type;
+    protected boolean input;
+    protected boolean secret;
+
+    public RequiredCredentialModel() {
+    }
+
+    public RequiredCredentialModel(String type, boolean input, boolean secret) {
+        this.type = type;
+        this.input = input;
+        this.secret = secret;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public boolean isInput() {
+        return input;
+    }
+
+    public void setInput(boolean input) {
+        this.input = input;
+    }
+
+    public boolean isSecret() {
+        return secret;
+    }
+
+    public void setSecret(boolean secret) {
+        this.secret = secret;
+    }
+
+    public static final RequiredCredentialModel PASSWORD = new RequiredCredentialModel(RequiredCredentialRepresentation.PASSWORD, true, true);
 }
diff --git a/services/src/main/java/org/keycloak/services/models/ResourceModel.java b/services/src/main/java/org/keycloak/services/models/ResourceModel.java
index b41edd6..cb343b0 100755
--- a/services/src/main/java/org/keycloak/services/models/ResourceModel.java
+++ b/services/src/main/java/org/keycloak/services/models/ResourceModel.java
@@ -1,8 +1,9 @@
 package org.keycloak.services.models;
 
+import org.keycloak.services.models.relationships.ResourceRelationship;
 import org.keycloak.services.models.relationships.ScopeRelationship;
+import org.picketlink.idm.IdentitySession;
 import org.picketlink.idm.IdentityManager;
-import org.picketlink.idm.internal.IdentityManagerFactory;
 import org.picketlink.idm.model.Agent;
 import org.picketlink.idm.model.Attribute;
 import org.picketlink.idm.model.Grant;
@@ -20,112 +21,94 @@ import java.util.Set;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class ResourceModel
-{
-   public static final String RESOURCE_AGENT_ID = "_resource_";
-   public static final String RESOURCE_NAME = "name";
-   public static final String RESOURCE_SURROGATE_AUTH = "surrogate_auth";
-
-   protected Tier tier;
-   protected Agent agent;
-   protected RealmModel realm;
-   protected IdentityManagerFactory factory;
-
-   public ResourceModel(Tier tier, Agent agent, RealmModel realm, IdentityManagerFactory factory)
-   {
-      this.tier = tier;
-      this.agent = agent;
-      this.realm = realm;
-      this.factory = factory;
-   }
-
-   public IdentityManager getIdm()
-   {
-      return factory.createIdentityManager(tier);
-   }
-
-   public void updateResource()
-   {
-      getIdm().update(agent);
-   }
-
-   public String getId()
-   {
-      return tier.getId();
-   }
-
-   public String getName()
-   {
-      return (String)agent.getAttribute(RESOURCE_NAME).getValue();
-   }
-
-   public void setName(String name)
-   {
-      agent.setAttribute(new Attribute<String>(RESOURCE_NAME, name));
-      getIdm().update(agent);
-   }
-
-   public boolean isEnabled()
-   {
-      return agent.isEnabled();
-   }
-
-   public void setEnabled(boolean enabled)
-   {
-      agent.setEnabled(enabled);
-   }
-
-   public boolean isSurrogateAuthRequired()
-   {
-      return (Boolean)agent.getAttribute(RESOURCE_SURROGATE_AUTH).getValue();
-   }
-
-   public void setSurrogateAuthRequired(boolean surrogateAuthRequired)
-   {
-      agent.setAttribute(new Attribute<Boolean>(RESOURCE_SURROGATE_AUTH, surrogateAuthRequired));
-   }
-
-   public List<Role> getRoles()
-   {
-      IdentityQuery<Role> query = getIdm().createIdentityQuery(Role.class);
-      query.setParameter(Role.PARTITION, tier);
-      return query.getResultList();
-   }
-
-   public Set<String> getRoleMappings(User user)
-   {
-      RelationshipQuery<Grant> query = getIdm().createRelationshipQuery(Grant.class);
-      query.setParameter(Grant.ASSIGNEE, user);
-      List<Grant> grants = query.getResultList();
-      HashSet<String> set = new HashSet<String>();
-      for (Grant grant : grants)
-      {
-         if (grant.getRole().getPartition().getId().equals(tier.getId()))set.add(grant.getRole().getName());
-      }
-      return set;
-   }
-
-   public void addScope(Agent agent, String roleName)
-   {
-      IdentityManager idm = getIdm();
-      Role role = idm.getRole(roleName);
-      if (role == null) throw new RuntimeException("role not found");
-      ScopeRelationship scope = new ScopeRelationship();
-      scope.setClient(agent);
-      scope.setScope(role);
-
-   }
-
-   public Set<String> getScope(Agent agent)
-   {
-      RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class);
-      query.setParameter(ScopeRelationship.CLIENT, agent);
-      List<ScopeRelationship> scope = query.getResultList();
-      HashSet<String> set = new HashSet<String>();
-      for (ScopeRelationship rel : scope)
-      {
-         if (rel.getScope().getPartition().getId().equals(tier.getId())) set.add(rel.getScope().getName());
-      }
-      return set;
-   }
+public class ResourceModel {
+    public static final String RESOURCE_AGENT_ID = "_resource_";
+    public static final String RESOURCE_NAME = "name";
+    public static final String RESOURCE_SURROGATE_AUTH = "surrogate_auth";
+
+    protected Tier tier;
+    protected ResourceRelationship agent;
+    protected RealmModel realm;
+    protected IdentitySession IdentitySession;
+
+    public ResourceModel(Tier tier, ResourceRelationship agent, RealmModel realm, IdentitySession factory) {
+        this.tier = tier;
+        this.agent = agent;
+        this.realm = realm;
+        this.IdentitySession = factory;
+    }
+
+    public IdentityManager getIdm() {
+        return IdentitySession.createIdentityManager(tier);
+    }
+
+    public void updateResource() {
+        getIdm().update(agent);
+    }
+
+    public String getId() {
+        return tier.getId();
+    }
+
+    public String getName() {
+        return agent.getResourceName();
+    }
+
+    public void setName(String name) {
+        agent.setResourceName(name);
+    }
+
+    public boolean isEnabled() {
+        return agent.getEnabled();
+    }
+
+    public void setEnabled(boolean enabled) {
+        agent.setEnabled(enabled);
+    }
+
+    public boolean isSurrogateAuthRequired() {
+        return agent.getSurrogateAuthRequired();
+    }
+
+    public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
+        agent.setSurrogateAuthRequired(surrogateAuthRequired);
+    }
+
+    public List<Role> getRoles() {
+        IdentityQuery<Role> query = getIdm().createIdentityQuery(Role.class);
+        query.setParameter(Role.PARTITION, tier);
+        return query.getResultList();
+    }
+
+    public Set<String> getRoleMappings(User user) {
+        RelationshipQuery<Grant> query = getIdm().createRelationshipQuery(Grant.class);
+        query.setParameter(Grant.ASSIGNEE, user);
+        List<Grant> grants = query.getResultList();
+        HashSet<String> set = new HashSet<String>();
+        for (Grant grant : grants) {
+            if (grant.getRole().getPartition().getId().equals(tier.getId())) set.add(grant.getRole().getName());
+        }
+        return set;
+    }
+
+    public void addScope(Agent agent, String roleName) {
+        IdentityManager idm = getIdm();
+        Role role = idm.getRole(roleName);
+        if (role == null) throw new RuntimeException("role not found");
+        ScopeRelationship scope = new ScopeRelationship();
+        scope.setClient(agent);
+        scope.setScope(role);
+
+    }
+
+    public Set<String> getScope(Agent agent) {
+        RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class);
+        query.setParameter(ScopeRelationship.CLIENT, agent);
+        List<ScopeRelationship> scope = query.getResultList();
+        HashSet<String> set = new HashSet<String>();
+        for (ScopeRelationship rel : scope) {
+            if (rel.getScope().getPartition().getId().equals(tier.getId())) set.add(rel.getScope().getName());
+        }
+        return set;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/models/UserCredentialModel.java b/services/src/main/java/org/keycloak/services/models/UserCredentialModel.java
index e2a3603..5807319 100755
--- a/services/src/main/java/org/keycloak/services/models/UserCredentialModel.java
+++ b/services/src/main/java/org/keycloak/services/models/UserCredentialModel.java
@@ -4,29 +4,24 @@ package org.keycloak.services.models;
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class UserCredentialModel
-{
+public class UserCredentialModel {
 
-   protected String type;
-   protected String value;
+    protected String type;
+    protected String value;
 
-   public String getType()
-   {
-      return type;
-   }
+    public String getType() {
+        return type;
+    }
 
-   public void setType(String type)
-   {
-      this.type = type;
-   }
+    public void setType(String type) {
+        this.type = type;
+    }
 
-   public String getValue()
-   {
-      return value;
-   }
+    public String getValue() {
+        return value;
+    }
 
-   public void setValue(String value)
-   {
-      this.value = value;
-   }
+    public void setValue(String value) {
+        this.value = value;
+    }
 }
diff --git a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
new file mode 100755
index 0000000..3af3e9c
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
@@ -0,0 +1,90 @@
+package org.keycloak.services.resources;
+
+import org.keycloak.SkeletonKeyContextResolver;
+import org.keycloak.services.filters.IdentitySessionFilter;
+import org.keycloak.services.models.relationships.RealmAdminRelationship;
+import org.keycloak.services.models.relationships.ResourceRelationship;
+import org.keycloak.services.models.relationships.RequiredCredentialRelationship;
+import org.keycloak.services.models.relationships.ScopeRelationship;
+import org.picketlink.idm.IdentitySessionFactory;
+import org.picketlink.idm.config.IdentityConfiguration;
+import org.picketlink.idm.config.IdentityConfigurationBuilder;
+import org.picketlink.idm.internal.DefaultIdentitySessionFactory;
+import org.picketlink.idm.jpa.internal.ResourceLocalJpaIdentitySessionHandler;
+import org.picketlink.idm.jpa.schema.CredentialObject;
+import org.picketlink.idm.jpa.schema.CredentialObjectAttribute;
+import org.picketlink.idm.jpa.schema.IdentityObject;
+import org.picketlink.idm.jpa.schema.IdentityObjectAttribute;
+import org.picketlink.idm.jpa.schema.PartitionObject;
+import org.picketlink.idm.jpa.schema.RelationshipIdentityObject;
+import org.picketlink.idm.jpa.schema.RelationshipObject;
+import org.picketlink.idm.jpa.schema.RelationshipObjectAttribute;
+
+import javax.annotation.PreDestroy;
+import javax.ws.rs.core.Application;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class KeycloakApplication extends Application {
+    protected Set<Object> singletons = new HashSet<Object>();
+    protected Set<Class<?>> classes = new HashSet<Class<?>>();
+
+    protected IdentitySessionFactory factory;
+
+    public KeycloakApplication() {
+        this.factory = createFactory();
+        IdentitySessionFilter filter = new IdentitySessionFilter(factory);
+        singletons.add(new RealmsResource());
+        singletons.add(filter);
+        classes.add(SkeletonKeyContextResolver.class);
+        classes.add(RegistrationService.class);
+    }
+
+    public IdentitySessionFactory getFactory() {
+        return factory;
+    }
+
+    @PreDestroy
+    public void destroy() {
+        factory.close();
+    }
+
+    public static IdentitySessionFactory createFactory() {
+        ResourceLocalJpaIdentitySessionHandler handler = new ResourceLocalJpaIdentitySessionHandler("keycloak-identity-store");
+        IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder();
+
+        builder
+                .stores()
+                .jpa()
+                .identityClass(IdentityObject.class)
+                .attributeClass(IdentityObjectAttribute.class)
+                .relationshipClass(RelationshipObject.class)
+                .relationshipIdentityClass(RelationshipIdentityObject.class)
+                .relationshipAttributeClass(RelationshipObjectAttribute.class)
+                .credentialClass(CredentialObject.class)
+                .credentialAttributeClass(CredentialObjectAttribute.class)
+                .partitionClass(PartitionObject.class)
+                .supportAllFeatures()
+                .supportRelationshipType(RealmAdminRelationship.class, ResourceRelationship.class, RequiredCredentialRelationship.class, ScopeRelationship.class)
+                .setIdentitySessionHandler(handler);
+
+        IdentityConfiguration build = builder.build();
+        return new DefaultIdentitySessionFactory(build);
+    }
+
+
+    @Override
+    public Set<Class<?>> getClasses() {
+        return classes;
+    }
+
+    @Override
+    public Set<Object> getSingletons() {
+        return singletons;
+    }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/RegistrationService.java b/services/src/main/java/org/keycloak/services/resources/RegistrationService.java
index c4c9b05..3718f76 100755
--- a/services/src/main/java/org/keycloak/services/resources/RegistrationService.java
+++ b/services/src/main/java/org/keycloak/services/resources/RegistrationService.java
@@ -1,10 +1,11 @@
 package org.keycloak.services.resources;
 
+import org.jboss.resteasy.logging.Logger;
 import org.keycloak.representations.idm.UserRepresentation;
 import org.keycloak.services.models.RealmManager;
 import org.keycloak.services.models.RealmModel;
 import org.keycloak.services.models.UserCredentialModel;
-import org.picketlink.idm.model.Realm;
+import org.picketlink.idm.IdentitySession;
 import org.picketlink.idm.model.Role;
 import org.picketlink.idm.model.SimpleUser;
 import org.picketlink.idm.model.User;
@@ -23,47 +24,47 @@ import java.net.URI;
  * @version $Revision: 1 $
  */
 @Path("/registrations")
-public class RegistrationService
-{
-   public static final String REALM_CREATOR_ROLE = "realm-creator";
-   protected RealmManager adapter;
-   protected RealmModel defaultRealm;
+public class RegistrationService {
+    protected static final Logger logger = Logger.getLogger(RegistrationService.class);
+    public static final String REALM_CREATOR_ROLE = "realm-creator";
 
-   @Context
-   protected UriInfo uriInfo;
+    @Context
+    protected UriInfo uriInfo;
 
-   public RegistrationService(RealmManager adapter)
-   {
-      this.adapter = adapter;
-      defaultRealm = adapter.getRealm(Realm.DEFAULT_REALM);
-   }
+    @Context
+    protected IdentitySession IdentitySession;
 
+    @POST
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response register(UserRepresentation newUser) {
+        IdentitySession.getTransaction().begin();
+        try {
+            RealmManager realmManager = new RealmManager(IdentitySession);
+            RealmModel defaultRealm = realmManager.defaultRealm();
+            User user = defaultRealm.getIdm().getUser(newUser.getUsername());
+            if (user != null) {
+                return Response.status(400).type("text/plain").entity("user exists").build();
+            }
 
-
-   @POST
-   @Consumes(MediaType.APPLICATION_JSON)
-   public Response register(UserRepresentation newUser)
-   {
-      User user = defaultRealm.getIdm().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);
-      for (UserRepresentation.Credential 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);
-      URI uri = uriInfo.getBaseUriBuilder().path(RealmFactory.class).path(user.getLoginName()).build();
-      return Response.created(uri).build();
-   }
+            user = new SimpleUser(newUser.getUsername());
+            defaultRealm.getIdm().add(user);
+            for (UserRepresentation.Credential 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);
+            IdentitySession.getTransaction().commit();
+            URI uri = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(user.getLoginName()).build();
+            return Response.created(uri).build();
+        } catch (RuntimeException e) {
+            logger.error("Failed to register", e);
+            IdentitySession.getTransaction().rollback();
+            throw e;
+        }
+    }
 
 
 }
diff --git a/services/src/main/java/org/keycloak/services/resources/TokenService.java b/services/src/main/java/org/keycloak/services/resources/TokenService.java
index ebdf2a9..d77339d 100755
--- a/services/src/main/java/org/keycloak/services/resources/TokenService.java
+++ b/services/src/main/java/org/keycloak/services/resources/TokenService.java
@@ -9,21 +9,21 @@ import org.jboss.resteasy.logging.Logger;
 import org.keycloak.representations.AccessTokenResponse;
 import org.keycloak.representations.SkeletonKeyScope;
 import org.keycloak.representations.SkeletonKeyToken;
+import org.keycloak.services.managers.AccessCodeEntry;
 import org.keycloak.services.managers.AuthenticationManager;
 import org.keycloak.services.managers.TokenManager;
 import org.keycloak.services.models.RealmManager;
 import org.keycloak.services.models.RealmModel;
 import org.keycloak.services.models.RequiredCredentialModel;
 import org.keycloak.services.models.ResourceModel;
+import org.picketlink.idm.IdentitySession;
 import org.picketlink.idm.model.User;
 
 import javax.ws.rs.Consumes;
 import javax.ws.rs.GET;
 import javax.ws.rs.NotAuthorizedException;
-import javax.ws.rs.NotFoundException;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
@@ -41,555 +41,400 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-@Path("/realms")
-public class TokenService
-{
-   public static class AccessCode
-   {
-      protected String id = UUID.randomUUID().toString() + System.currentTimeMillis();
-      protected long expiration;
-      protected SkeletonKeyToken token;
-      protected User client;
-
-      public boolean isExpired()
-      {
-         return expiration != 0 && (System.currentTimeMillis() / 1000) > expiration;
-      }
-
-      public String getId()
-      {
-         return id;
-      }
-
-      public long getExpiration()
-      {
-         return expiration;
-      }
-
-      public void setExpiration(long expiration)
-      {
-         this.expiration = expiration;
-      }
-
-      public SkeletonKeyToken getToken()
-      {
-         return token;
-      }
-
-      public void setToken(SkeletonKeyToken token)
-      {
-         this.token = token;
-      }
-
-      public User getClient()
-      {
-         return client;
-      }
-
-      public void setClient(User client)
-      {
-         this.client = client;
-      }
-   }
-
-   protected RealmManager adapter;
-   protected TokenManager tokenManager;
-   protected AuthenticationManager authManager;
-   protected Logger logger = Logger.getLogger(TokenService.class);
-   protected Map<String, AccessCode> accessCodeMap = new HashMap<String, AccessCode>();
-   @Context
-   protected UriInfo uriInfo;
-   @Context
-   protected Providers providers;
-   @Context
-   protected SecurityContext securityContext;
-   @Context
-   protected HttpHeaders headers;
-
-   private static AtomicLong counter = new AtomicLong(1);
-   private static String generateId()
-   {
-      return counter.getAndIncrement() + "." + UUID.randomUUID().toString();
-   }
-
-   public TokenService(RealmManager adapter)
-   {
-      this.adapter = adapter;
-      this.tokenManager = new TokenManager(adapter);
-      this.authManager = new AuthenticationManager(adapter);
-   }
-
-   @Path("{realm}/grants/identity-token")
-   @POST
-   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-   @Produces(MediaType.APPLICATION_JSON)
-   public Response identityTokenGrant(@PathParam("realm") String realmId, MultivaluedMap<String, String> form)
-   {
-      String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
-      if (username == null)
-      {
-         throw new NotAuthorizedException("No user");
-      }
-      RealmModel realm = adapter.getRealm(realmId);
-      if (realm == null)
-      {
-         throw new NotFoundException("Realm not found");
-      }
-      if (!realm.isEnabled())
-      {
-         throw new NotAuthorizedException("Disabled realm");
-      }
-      User user = realm.getIdm().getUser(username);
-      if (user == null)
-      {
-         throw new NotAuthorizedException("No user");
-      }
-      if (!user.isEnabled())
-      {
-         throw new NotAuthorizedException("Disabled user.");
-      }
-      SkeletonKeyToken token = tokenManager.createIdentityToken(realm, username);
-      String encoded = tokenManager.encodeToken(realm, token);
-      AccessTokenResponse res = accessTokenResponse(token, encoded);
-      return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
-   }
-
-   @Path("{realm}/grants/access")
-   @POST
-   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-   @Produces(MediaType.APPLICATION_JSON)
-   public Response accessTokenGrant(@PathParam("realm") String realmId, MultivaluedMap<String, String> form)
-   {
-      String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
-      if (username == null)
-      {
-         throw new NotAuthorizedException("No user");
-      }
-      RealmModel realm = adapter.getRealm(realmId);
-      if (realm == null)
-      {
-         throw new NotFoundException("Realm not found");
-      }
-      if (!realm.isEnabled())
-      {
-         throw new NotAuthorizedException("Disabled realm");
-      }
-      User user = realm.getIdm().getUser(username);
-      if (user == null)
-      {
-         throw new NotAuthorizedException("No user");
-      }
-      if (!user.isEnabled())
-      {
-         throw new NotAuthorizedException("Disabled user.");
-      }
-      if (authManager.authenticateForm(realm, user, form))
-      {
-         throw new NotAuthorizedException("Auth failed");
-      }
-      SkeletonKeyToken token = tokenManager.createAccessToken(realm, user);
-      String encoded = tokenManager.encodeToken(realm, token);
-      AccessTokenResponse res = accessTokenResponse(token, encoded);
-      return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
-   }
-
-   @Path("{realm}/auth/request/login")
-   @POST
-   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-   public Response login(@PathParam("realm") String realmId,
-                         MultivaluedMap<String, String> formData)
-   {
-      String clientId = formData.getFirst("client_id");
-      String scopeParam = formData.getFirst("scope");
-      String state = formData.getFirst("state");
-      String redirect = formData.getFirst("redirect_uri");
-
-      RealmModel realm = adapter.getRealm(realmId);
-      if (realm == null)
-      {
-         throw new NotFoundException("Realm not found");
-      }
-      if (!realm.isEnabled())
-      {
-         return Response.ok("Realm not enabled").type("text/html").build();
-      }
-      User client = realm.getIdm().getUser(clientId);
-      if (client == null)
-      {
-         throw new NotAuthorizedException("No client");
-      }
-      if (!client.isEnabled())
-      {
-         return Response.ok("Requester not enabled").type("text/html").build();
-      }
-      String username = formData.getFirst("username");
-      User user = realm.getIdm().getUser(username);
-      if (user == null)
-      {
-         logger.debug("user not found");
-         return loginForm("Not valid user", redirect, clientId, scopeParam, state, realm, client);
-      }
-      if (!user.isEnabled())
-      {
-         return Response.ok("Your account is not enabled").type("text/html").build();
-
-      }
-      boolean authenticated = authManager.authenticateForm(realm, user, formData);
-      if (!authenticated) return loginForm("Unable to authenticate, try again", redirect, clientId, scopeParam, state, realm, client);
-
-      SkeletonKeyToken token = null;
-      if (scopeParam != null) token = tokenManager.createScopedToken(scopeParam, realm, client, user);
-      else token = tokenManager.createLoginToken(realm, client, user);
-
-      AccessCode code = new AccessCode();
-      code.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan());
-      code.setToken(token);
-      code.setClient(client);
-      synchronized (accessCodeMap)
-      {
-         accessCodeMap.put(code.getId(), code);
-      }
-      String accessCode = null;
-      try
-      {
-         accessCode = new JWSBuilder().content(code.getId().getBytes("UTF-8")).rsa256(realm.getPrivateKey());
-      }
-      catch (UnsupportedEncodingException e)
-      {
-         throw new RuntimeException(e);
-      }
-      UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("code", accessCode);
-      if (state != null) redirectUri.queryParam("state", state);
-      return Response.status(302).location(redirectUri.build()).build();
-   }
-
-   @Path("{realm}/access/codes")
-   @POST
-   @Produces("application/json")
-   public Response accessRequest(@PathParam("realm") String realmId,
-                                 MultivaluedMap<String, String> formData)
-   {
-      RealmModel realm = adapter.getRealm(realmId);
-      if (realm == null)
-      {
-         throw new NotFoundException("Realm not found");
-      }
-      if (!realm.isEnabled())
-      {
-         throw new NotAuthorizedException("Realm not enabled");
-      }
-
-      String code = formData.getFirst("code");
-      if (code == null)
-      {
-         logger.debug("code not specified");
-         Map<String, String> error = new HashMap<String, String>();
-         error.put("error", "invalid_request");
-         error.put("error_description", "code not specified");
-         return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
-
-      }
-      String client_id = formData.getFirst("client_id");
-      if (client_id == null)
-      {
-         logger.debug("client_id not specified");
-         Map<String, String> error = new HashMap<String, String>();
-         error.put("error", "invalid_request");
-         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);
-      if (client == null)
-      {
-         logger.debug("Could not find user");
-         Map<String, String> error = new HashMap<String, String>();
-         error.put("error", "invalid_client");
-         error.put("error_description", "Could not find user");
-         return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
-      }
-
-      if (!client.isEnabled())
-      {
-         logger.debug("user is not enabled");
-         Map<String, String> error = new HashMap<String, String>();
-         error.put("error", "invalid_client");
-         error.put("error_description", "User is not enabled");
-         return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
-      }
-
-      boolean authenticated = authManager.authenticateForm(realm, client, formData);
-      if (!authenticated)
-      {
-         Map<String, String> error = new HashMap<String, String>();
-         error.put("error", "unauthorized_client");
-         return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
-      }
-
-
-
-      JWSInput input = new JWSInput(code, providers);
-      boolean verifiedCode = false;
-      try
-      {
-         verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
-      }
-      catch (Exception ignored)
-      {
-         logger.debug("Failed to verify signature", ignored);
-      }
-      if (!verifiedCode)
-      {
-         Map<String, String> res = new HashMap<String, String>();
-         res.put("error", "invalid_grant");
-         res.put("error_description", "Unable to verify code signature");
-         return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
-      }
-      String key = input.readContent(String.class);
-      AccessCode accessCode = null;
-      synchronized (accessCodeMap)
-      {
-         accessCode = accessCodeMap.remove(key);
-      }
-      if (accessCode == null)
-      {
-         Map<String, String> res = new HashMap<String, String>();
-         res.put("error", "invalid_grant");
-         res.put("error_description", "Code not found");
-         return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
-      }
-      if (accessCode.isExpired())
-      {
-         Map<String, String> res = new HashMap<String, String>();
-         res.put("error", "invalid_grant");
-         res.put("error_description", "Code is expired");
-         return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
-      }
-      if (!accessCode.getToken().isActive())
-      {
-         Map<String, String> res = new HashMap<String, String>();
-         res.put("error", "invalid_grant");
-         res.put("error_description", "Token expired");
-         return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
-      }
-      if (!client.getId().equals(accessCode.getClient().getId()))
-      {
-         Map<String, String> res = new HashMap<String, String>();
-         res.put("error", "invalid_grant");
-         res.put("error_description", "Auth error");
-         return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
-      }
-      AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
-      return Response.ok(res).build();
-
-   }
-
-   protected AccessTokenResponse accessTokenResponse(PrivateKey privateKey, SkeletonKeyToken token)
-   {
-      byte[] tokenBytes = null;
-      try
-      {
-         tokenBytes = JsonSerialization.toByteArray(token, false);
-      }
-      catch (Exception e)
-      {
-         throw new RuntimeException(e);
-      }
-      String encodedToken = new JWSBuilder()
-              .content(tokenBytes)
-              .rsa256(privateKey);
-
-      return accessTokenResponse(token, encodedToken);
-   }
-
-   protected AccessTokenResponse accessTokenResponse(SkeletonKeyToken token, String encodedToken)
-   {
-      AccessTokenResponse res = new AccessTokenResponse();
-      res.setToken(encodedToken);
-      res.setTokenType("bearer");
-      if (token.getExpiration() != 0)
-      {
-         long time = token.getExpiration() - (System.currentTimeMillis() / 1000);
-         res.setExpiresIn(time);
-      }
-      return res;
-   }
-
-   @Path("{realm}/auth/request")
-   @GET
-   public Response requestAccessCode(@PathParam("realm") String realmId,
-                                     @QueryParam("response_type") String responseType,
-                                     @QueryParam("redirect_uri") String redirect,
-                                     @QueryParam("client_id") String clientId,
-                                     @QueryParam("scope") String scopeParam,
-                                     @QueryParam("state") String state)
-   {
-      RealmModel realm = adapter.getRealm(realmId);
-      if (realm == null)
-      {
-         throw new NotFoundException("Realm not found");
-      }
-      if (!realm.isEnabled())
-      {
-         throw new NotAuthorizedException("Realm not enabled");
-      }
-      User client = realm.getIdm().getUser(clientId);
-      if (client == null)
-         return Response.ok("<h1>Security Alert</h1><p>Unknown client trying to get access to your account.</p>").type("text/html").build();
-
-      return loginForm(null, redirect, clientId, scopeParam, state, realm, client);
-   }
-
-   private Response loginForm(String validationError, String redirect, String clientId, String scopeParam, String state, RealmModel realm, User client)
-   {
-      StringBuffer html = new StringBuffer();
-      if (scopeParam != null)
-      {
-         html.append("<h1>Grant Request For ").append(realm.getName()).append(" Realm</h1>");
-         if (validationError != null)
-         {
-            try
-            {
-               Thread.sleep(1000); // put in a delay
-            }
-            catch (InterruptedException e)
-            {
-               throw new RuntimeException(e);
-            }
-            html.append("<p/><p><b>").append(validationError).append("</b></p>");
-         }
-         html.append("<p>A Third Party is requesting access to the following resources</p>");
-         html.append("<table>");
-         SkeletonKeyScope scope = tokenManager.decodeScope(scopeParam);
-         Map<String, ResourceModel> resourceMap = realm.getResourceMap();
-
-         for (String res : scope.keySet())
-         {
-            ResourceModel resource = resourceMap.get(res);
-            html.append("<tr><td><b>Resource: </b>").append(resource.getName()).append("</td><td><b>Roles:</b>");
-            Set<String> scopeMapping = resource.getScope(client);
-            for (String role : scope.get(res))
-            {
-               html.append(" ").append(role);
-               if (!scopeMapping.contains("*") && !scopeMapping.contains(role))
-               {
-                  return Response.ok("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build();
-               }
-            }
-            html.append("</td></tr>");
-         }
-         html.append("</table><p>To Authorize, please login below</p>");
-      }
-      else
-      {
-         Set<String> scopeMapping = realm.getScope(client);
-         if (scopeMapping.contains("*"))
-         {
-            html.append("<h1>Login For ").append(realm.getName()).append(" Realm</h1>");
-            if (validationError != null)
-            {
-               try
-               {
-                  Thread.sleep(1000); // put in a delay
-               }
-               catch (InterruptedException e)
-               {
-                  throw new RuntimeException(e);
-               }
-               html.append("<p/><p><b>").append(validationError).append("</b></p>");
-            }
-         }
-         else
-         {
+public class TokenService {
+
+
+    protected static final Logger logger = Logger.getLogger(TokenService.class);
+    protected Map<String, AccessCodeEntry> accessCodeMap;
+
+    @Context
+    protected UriInfo uriInfo;
+    @Context
+    protected Providers providers;
+    @Context
+    protected SecurityContext securityContext;
+    @Context
+    protected HttpHeaders headers;
+    @Context
+    protected
+    IdentitySession IdentitySession;
+
+    protected RealmModel realm;
+    protected TokenManager tokenManager = new TokenManager();
+    protected AuthenticationManager authManager = new AuthenticationManager();
+
+    public TokenService(RealmModel realm, Map<String, AccessCodeEntry> accessCodeMap) {
+        this.realm = realm;
+        this.accessCodeMap = accessCodeMap;
+    }
+
+    @Path("grants/identity-token")
+    @POST
+    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response identityTokenGrant(MultivaluedMap<String, String> form) {
+        String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
+        if (username == null) {
+            throw new NotAuthorizedException("No user");
+        }
+        if (!realm.isEnabled()) {
+            throw new NotAuthorizedException("Disabled realm");
+        }
+        User user = realm.getIdm().getUser(username);
+        if (user == null) {
+            throw new NotAuthorizedException("No user");
+        }
+        if (!user.isEnabled()) {
+            throw new NotAuthorizedException("Disabled user.");
+        }
+        if (!authManager.authenticateForm(realm, user, form)) {
+            throw new NotAuthorizedException("FORM");
+        }
+        tokenManager = new TokenManager();
+        SkeletonKeyToken token = tokenManager.createIdentityToken(realm, username);
+        String encoded = tokenManager.encodeToken(realm, token);
+        AccessTokenResponse res = accessTokenResponse(token, encoded);
+        return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
+    }
+
+    @Path("grants/access")
+    @POST
+    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response accessTokenGrant(MultivaluedMap<String, String> form) {
+        String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
+        if (username == null) {
+            throw new NotAuthorizedException("No user");
+        }
+        if (!realm.isEnabled()) {
+            throw new NotAuthorizedException("Disabled realm");
+        }
+        User user = realm.getIdm().getUser(username);
+        if (user == null) {
+            throw new NotAuthorizedException("No user");
+        }
+        if (!user.isEnabled()) {
+            throw new NotAuthorizedException("Disabled user.");
+        }
+        if (authManager.authenticateForm(realm, user, form)) {
+            throw new NotAuthorizedException("Auth failed");
+        }
+        SkeletonKeyToken token = tokenManager.createAccessToken(realm, user);
+        String encoded = tokenManager.encodeToken(realm, token);
+        AccessTokenResponse res = accessTokenResponse(token, encoded);
+        return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
+    }
+
+    @Path("auth/request/login")
+    @POST
+    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+    public Response login(MultivaluedMap<String, String> formData) {
+        String clientId = formData.getFirst("client_id");
+        String scopeParam = formData.getFirst("scope");
+        String state = formData.getFirst("state");
+        String redirect = formData.getFirst("redirect_uri");
+
+        if (!realm.isEnabled()) {
+            return Response.ok("Realm not enabled").type("text/html").build();
+        }
+        User client = realm.getIdm().getUser(clientId);
+        if (client == null) {
+            throw new NotAuthorizedException("No client");
+        }
+        if (!client.isEnabled()) {
+            return Response.ok("Requester not enabled").type("text/html").build();
+        }
+        String username = formData.getFirst("username");
+        User user = realm.getIdm().getUser(username);
+        if (user == null) {
+            logger.debug("user not found");
+            return loginForm("Not valid user", redirect, clientId, scopeParam, state, realm, client);
+        }
+        if (!user.isEnabled()) {
+            return Response.ok("Your account is not enabled").type("text/html").build();
+
+        }
+        boolean authenticated = authManager.authenticateForm(realm, user, formData);
+        if (!authenticated)
+            return loginForm("Unable to authenticate, try again", redirect, clientId, scopeParam, state, realm, client);
+
+        SkeletonKeyToken token = null;
+        if (scopeParam != null) token = tokenManager.createScopedToken(scopeParam, realm, client, user);
+        else token = tokenManager.createLoginToken(realm, client, user);
+
+        AccessCodeEntry code = new AccessCodeEntry();
+        code.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan());
+        code.setToken(token);
+        code.setClient(client);
+        synchronized (accessCodeMap) {
+            accessCodeMap.put(code.getId(), code);
+        }
+        String accessCode = null;
+        try {
+            accessCode = new JWSBuilder().content(code.getId().getBytes("UTF-8")).rsa256(realm.getPrivateKey());
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+        UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("code", accessCode);
+        if (state != null) redirectUri.queryParam("state", state);
+        return Response.status(302).location(redirectUri.build()).build();
+    }
+
+    @Path("access/codes")
+    @POST
+    @Produces("application/json")
+    public Response accessRequest(MultivaluedMap<String, String> formData) {
+        if (!realm.isEnabled()) {
+            throw new NotAuthorizedException("Realm not enabled");
+        }
+
+        String code = formData.getFirst("code");
+        if (code == null) {
+            logger.debug("code not specified");
+            Map<String, String> error = new HashMap<String, String>();
+            error.put("error", "invalid_request");
+            error.put("error_description", "code not specified");
+            return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
+
+        }
+        String client_id = formData.getFirst("client_id");
+        if (client_id == null) {
+            logger.debug("client_id not specified");
+            Map<String, String> error = new HashMap<String, String>();
+            error.put("error", "invalid_request");
+            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);
+        if (client == null) {
+            logger.debug("Could not find user");
+            Map<String, String> error = new HashMap<String, String>();
+            error.put("error", "invalid_client");
+            error.put("error_description", "Could not find user");
+            return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
+        }
+
+        if (!client.isEnabled()) {
+            logger.debug("user is not enabled");
+            Map<String, String> error = new HashMap<String, String>();
+            error.put("error", "invalid_client");
+            error.put("error_description", "User is not enabled");
+            return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
+        }
+
+        boolean authenticated = authManager.authenticateForm(realm, client, formData);
+        if (!authenticated) {
+            Map<String, String> error = new HashMap<String, String>();
+            error.put("error", "unauthorized_client");
+            return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
+        }
+
+
+        JWSInput input = new JWSInput(code, providers);
+        boolean verifiedCode = false;
+        try {
+            verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
+        } catch (Exception ignored) {
+            logger.debug("Failed to verify signature", ignored);
+        }
+        if (!verifiedCode) {
+            Map<String, String> res = new HashMap<String, String>();
+            res.put("error", "invalid_grant");
+            res.put("error_description", "Unable to verify code signature");
+            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+        }
+        String key = input.readContent(String.class);
+        AccessCodeEntry accessCode = null;
+        synchronized (accessCodeMap) {
+            accessCode = accessCodeMap.remove(key);
+        }
+        if (accessCode == null) {
+            Map<String, String> res = new HashMap<String, String>();
+            res.put("error", "invalid_grant");
+            res.put("error_description", "Code not found");
+            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+        }
+        if (accessCode.isExpired()) {
+            Map<String, String> res = new HashMap<String, String>();
+            res.put("error", "invalid_grant");
+            res.put("error_description", "Code is expired");
+            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+        }
+        if (!accessCode.getToken().isActive()) {
+            Map<String, String> res = new HashMap<String, String>();
+            res.put("error", "invalid_grant");
+            res.put("error_description", "Token expired");
+            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+        }
+        if (!client.getId().equals(accessCode.getClient().getId())) {
+            Map<String, String> res = new HashMap<String, String>();
+            res.put("error", "invalid_grant");
+            res.put("error_description", "Auth error");
+            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+        }
+        AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
+        return Response.ok(res).build();
+
+    }
+
+    protected AccessTokenResponse accessTokenResponse(PrivateKey privateKey, SkeletonKeyToken token) {
+        byte[] tokenBytes = null;
+        try {
+            tokenBytes = JsonSerialization.toByteArray(token, false);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+        String encodedToken = new JWSBuilder()
+                .content(tokenBytes)
+                .rsa256(privateKey);
+
+        return accessTokenResponse(token, encodedToken);
+    }
+
+    protected AccessTokenResponse accessTokenResponse(SkeletonKeyToken token, String encodedToken) {
+        AccessTokenResponse res = new AccessTokenResponse();
+        res.setToken(encodedToken);
+        res.setTokenType("bearer");
+        if (token.getExpiration() != 0) {
+            long time = token.getExpiration() - (System.currentTimeMillis() / 1000);
+            res.setExpiresIn(time);
+        }
+        return res;
+    }
+
+    @Path("auth/request")
+    @GET
+    public Response requestAccessCode(@QueryParam("response_type") String responseType,
+                                      @QueryParam("redirect_uri") String redirect,
+                                      @QueryParam("client_id") String clientId,
+                                      @QueryParam("scope") String scopeParam,
+                                      @QueryParam("state") String state) {
+        if (!realm.isEnabled()) {
+            throw new NotAuthorizedException("Realm not enabled");
+        }
+        User client = realm.getIdm().getUser(clientId);
+        if (client == null)
+            return Response.ok("<h1>Security Alert</h1><p>Unknown client trying to get access to your account.</p>").type("text/html").build();
+
+        return loginForm(null, redirect, clientId, scopeParam, state, realm, client);
+    }
+
+    private Response loginForm(String validationError, String redirect, String clientId, String scopeParam, String state, RealmModel realm, User client) {
+        StringBuffer html = new StringBuffer();
+        if (scopeParam != null) {
             html.append("<h1>Grant Request For ").append(realm.getName()).append(" Realm</h1>");
-            if (validationError != null)
-            {
-               try
-               {
-                  Thread.sleep(1000); // put in a delay
-               }
-               catch (InterruptedException e)
-               {
-                  throw new RuntimeException(e);
-               }
-               html.append("<p/><p><b>").append(validationError).append("</b></p>");
-            }
-            SkeletonKeyScope scope = new SkeletonKeyScope();
-            List<ResourceModel> resources = realm.getResources();
-            boolean found = false;
-            for (ResourceModel resource : resources)
-            {
-               Set<String> resourceScope = resource.getScope(client);
-               if (resourceScope == null) continue;
-               if (resourceScope.size() == 0) continue;
-               if (!found)
-               {
-                  found = true;
-                  html.append("<p>A Third Party is requesting access to the following resources</p>");
-                  html.append("<table>");
-               }
-               html.append("<tr><td><b>Resource: </b>").append(resource.getName()).append("</td><td><b>Roles:</b>");
-               // todo add description of role
-               for (String role : resourceScope)
-               {
-                  html.append(" ").append(role);
-                  scope.add(resource.getName(), role);
-               }
+            if (validationError != null) {
+                try {
+                    Thread.sleep(1000); // put in a delay
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+                html.append("<p/><p><b>").append(validationError).append("</b></p>");
             }
-            if (!found)
-            {
-               return Response.ok("<h1>Security Alert</h1><p>Known client not authorized to access this realm.</p>").type("text/html").build();
+            html.append("<p>A Third Party is requesting access to the following resources</p>");
+            html.append("<table>");
+            SkeletonKeyScope scope = tokenManager.decodeScope(scopeParam);
+            Map<String, ResourceModel> resourceMap = realm.getResourceMap();
+
+            for (String res : scope.keySet()) {
+                ResourceModel resource = resourceMap.get(res);
+                html.append("<tr><td><b>Resource: </b>").append(resource.getName()).append("</td><td><b>Roles:</b>");
+                Set<String> scopeMapping = resource.getScope(client);
+                for (String role : scope.get(res)) {
+                    html.append(" ").append(role);
+                    if (!scopeMapping.contains("*") && !scopeMapping.contains(role)) {
+                        return Response.ok("<h1>Security Alert</h1><p>Known client not authorized for the requested scope.</p>").type("text/html").build();
+                    }
+                }
+                html.append("</td></tr>");
             }
-            html.append("</table>");
-            try
-            {
-               String json = JsonSerialization.toString(scope, false);
-               scopeParam = Base64Url.encode(json.getBytes("UTF-8"));
-            }
-            catch (Exception e)
-            {
-               throw new RuntimeException(e);
+            html.append("</table><p>To Authorize, please login below</p>");
+        } else {
+            Set<String> scopeMapping = realm.getScope(client);
+            if (scopeMapping.contains("*")) {
+                html.append("<h1>Login For ").append(realm.getName()).append(" Realm</h1>");
+                if (validationError != null) {
+                    try {
+                        Thread.sleep(1000); // put in a delay
+                    } catch (InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                    html.append("<p/><p><b>").append(validationError).append("</b></p>");
+                }
+            } else {
+                html.append("<h1>Grant Request For ").append(realm.getName()).append(" Realm</h1>");
+                if (validationError != null) {
+                    try {
+                        Thread.sleep(1000); // put in a delay
+                    } catch (InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                    html.append("<p/><p><b>").append(validationError).append("</b></p>");
+                }
+                SkeletonKeyScope scope = new SkeletonKeyScope();
+                List<ResourceModel> resources = realm.getResources();
+                boolean found = false;
+                for (ResourceModel resource : resources) {
+                    Set<String> resourceScope = resource.getScope(client);
+                    if (resourceScope == null) continue;
+                    if (resourceScope.size() == 0) continue;
+                    if (!found) {
+                        found = true;
+                        html.append("<p>A Third Party is requesting access to the following resources</p>");
+                        html.append("<table>");
+                    }
+                    html.append("<tr><td><b>Resource: </b>").append(resource.getName()).append("</td><td><b>Roles:</b>");
+                    // todo add description of role
+                    for (String role : resourceScope) {
+                        html.append(" ").append(role);
+                        scope.add(resource.getName(), role);
+                    }
+                }
+                if (!found) {
+                    return Response.ok("<h1>Security Alert</h1><p>Known client not authorized to access this realm.</p>").type("text/html").build();
+                }
+                html.append("</table>");
+                try {
+                    String json = JsonSerialization.toString(scope, false);
+                    scopeParam = Base64Url.encode(json.getBytes("UTF-8"));
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+
             }
+        }
+
+        UriBuilder formActionUri = uriInfo.getBaseUriBuilder().path(TokenService.class).path(TokenService.class, "login");
+        String action = formActionUri.build(realm.getId()).toString();
+        html.append("<form action=\"").append(action).append("\" method=\"POST\">");
+        html.append("Username: <input type=\"text\" name=\"username\" size=\"20\"><br>");
 
-         }
-      }
-
-      UriBuilder formActionUri = uriInfo.getBaseUriBuilder().path(TokenService.class).path(TokenService.class, "login");
-      String action = formActionUri.build(realm.getId()).toString();
-      html.append("<form action=\"").append(action).append("\" method=\"POST\">");
-      html.append("Username: <input type=\"text\" name=\"username\" size=\"20\"><br>");
-
-      for (RequiredCredentialModel credential : realm.getRequiredCredentials())
-      {
-         if (!credential.isInput()) continue;
-         html.append(credential.getType()).append(": ");
-         if (credential.isSecret())
-         {
-            html.append("<input type=\"password\" name=\"").append(credential.getType()).append("\"  size=\"20\"><br>");
-
-         } else
-         {
-            html.append("<input type=\"text\" name=\"").append(credential.getType()).append("\"  size=\"20\"><br>");
-         }
-      }
-      html.append("<input type=\"hidden\" name=\"client_id\" value=\"").append(clientId).append("\">");
-      if (scopeParam != null)
-      {
-         html.append("<input type=\"hidden\" name=\"scope\" value=\"").append(scopeParam).append("\">");
-      }
-      if (state != null) html.append("<input type=\"hidden\" name=\"state\" value=\"").append(state).append("\">");
-      html.append("<input type=\"hidden\" name=\"redirect_uri\" value=\"").append(redirect).append("\">");
-      html.append("<input type=\"submit\" value=\"");
-      if (scopeParam == null) html.append("Login");
-      else html.append("Grant Access");
-      html.append("\">");
-      html.append("</form>");
-      return Response.ok(html.toString()).type("text/html").build();
-   }
+        for (RequiredCredentialModel credential : realm.getRequiredCredentials()) {
+            if (!credential.isInput()) continue;
+            html.append(credential.getType()).append(": ");
+            if (credential.isSecret()) {
+                html.append("<input type=\"password\" name=\"").append(credential.getType()).append("\"  size=\"20\"><br>");
+
+            } else {
+                html.append("<input type=\"text\" name=\"").append(credential.getType()).append("\"  size=\"20\"><br>");
+            }
+        }
+        html.append("<input type=\"hidden\" name=\"client_id\" value=\"").append(clientId).append("\">");
+        if (scopeParam != null) {
+            html.append("<input type=\"hidden\" name=\"scope\" value=\"").append(scopeParam).append("\">");
+        }
+        if (state != null) html.append("<input type=\"hidden\" name=\"state\" value=\"").append(state).append("\">");
+        html.append("<input type=\"hidden\" name=\"redirect_uri\" value=\"").append(redirect).append("\">");
+        html.append("<input type=\"submit\" value=\"");
+        if (scopeParam == null) html.append("Login");
+        else html.append("Grant Access");
+        html.append("\">");
+        html.append("</form>");
+        return Response.ok(html.toString()).type("text/html").build();
+    }
 }
diff --git a/services/src/test/java/org/keycloak/test/AdapterTest.java b/services/src/test/java/org/keycloak/test/AdapterTest.java
index 6605780..98fa18b 100755
--- a/services/src/test/java/org/keycloak/test/AdapterTest.java
+++ b/services/src/test/java/org/keycloak/test/AdapterTest.java
@@ -7,27 +7,23 @@ import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
 import org.keycloak.representations.idm.RequiredCredentialRepresentation;
+import org.keycloak.services.managers.InstallationManager;
 import org.keycloak.services.models.RealmManager;
 import org.keycloak.services.models.RealmModel;
-import org.keycloak.services.models.relationships.RealmResourceRelationship;
 import org.keycloak.services.models.RequiredCredentialModel;
-import org.keycloak.services.models.relationships.RequiredCredentialRelationship;
-import org.keycloak.services.models.relationships.ScopeRelationship;
 import org.keycloak.services.models.UserCredentialModel;
+import org.keycloak.services.resources.KeycloakApplication;
+import org.picketlink.idm.IdentitySession;
+import org.picketlink.idm.IdentitySessionFactory;
 import org.picketlink.idm.IdentityManager;
-import org.picketlink.idm.config.IdentityConfigurationBuilder;
 import org.picketlink.idm.credential.Credentials;
 import org.picketlink.idm.credential.Password;
 import org.picketlink.idm.credential.UsernamePasswordCredentials;
-import org.picketlink.idm.file.internal.FileUtils;
-import org.picketlink.idm.internal.IdentityManagerFactory;
-import org.picketlink.idm.model.Realm;
 import org.picketlink.idm.model.Role;
 import org.picketlink.idm.model.SimpleRole;
 import org.picketlink.idm.model.SimpleUser;
 import org.picketlink.idm.model.User;
 
-import java.io.File;
 import java.util.List;
 
 /**
@@ -35,125 +31,108 @@ import java.util.List;
  * @version $Revision: 1 $
  */
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class AdapterTest
-{
-   private static IdentityManagerFactory factory;
-   public static final String WORKING_DIRECTORY = "/tmp/keycloak";
-   public RealmManager adapter;
-   public RealmModel realmModel;
-   @Before
-   public void before() throws Exception
-   {
-      after();
-      factory = createFactory();
-      adapter = new RealmManager(factory);
-   }
+public class AdapterTest {
+    private IdentitySessionFactory factory;
+    private IdentitySession IdentitySession;
+    private RealmManager adapter;
+    private RealmModel realmModel;
 
-   private static IdentityManagerFactory createFactory() {
-      IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder();
+    @Before
+    public void before() throws Exception {
+        factory = KeycloakApplication.createFactory();
+        IdentitySession = factory.createIdentitySession();
+        adapter = new RealmManager(IdentitySession);
+    }
 
-      builder
-              .stores()
-              .file()
-              .addRealm(Realm.DEFAULT_REALM)
-              .workingDirectory(WORKING_DIRECTORY)
-              .preserveState(true)
-              .supportAllFeatures()
-              .supportRelationshipType(RealmResourceRelationship.class, RequiredCredentialRelationship.class, ScopeRelationship.class);
+    @After
+    public void after() throws Exception {
+        IdentitySession.close();
+        factory.close();
+    }
 
-      return new IdentityManagerFactory(builder.build());
-   }
+    @Test
+    public void installTest() throws Exception {
+        new InstallationManager().install(adapter);
 
-   @After
-   public void after() throws Exception
-   {
-      File file = new File(WORKING_DIRECTORY);
-      FileUtils.delete(file);
-      Thread.sleep(10); // my windows machine seems to have delays on deleting files sometimes
-   }
+    }
 
-   @Test
-   public void test1CreateRealm() throws Exception
-   {
-      realmModel = adapter.create("JUGGLER");
-      realmModel.setAccessCodeLifespan(100);
-      realmModel.setCookieLoginAllowed(true);
-      realmModel.setEnabled(true);
-      realmModel.setName("JUGGLER");
-      realmModel.setPrivateKeyPem("0234234");
-      realmModel.setPublicKeyPem("0234234");
-      realmModel.setTokenLifespan(1000);
-      realmModel.updateRealm();
+    @Test
+    public void test1CreateRealm() throws Exception {
+        realmModel = adapter.createRealm("JUGGLER");
+        realmModel.setAccessCodeLifespan(100);
+        realmModel.setCookieLoginAllowed(true);
+        realmModel.setEnabled(true);
+        realmModel.setName("JUGGLER");
+        realmModel.setPrivateKeyPem("0234234");
+        realmModel.setPublicKeyPem("0234234");
+        realmModel.setTokenLifespan(1000);
+        realmModel.updateRealm();
 
-      System.out.println(realmModel.getId());
-      realmModel = adapter.getRealm(realmModel.getId());
-      Assert.assertNotNull(realmModel);
-      Assert.assertEquals(realmModel.getAccessCodeLifespan(), 100);
-      Assert.assertEquals(realmModel.getTokenLifespan(), 1000);
-      Assert.assertEquals(realmModel.isEnabled(), true);
-      Assert.assertEquals(realmModel.getName(), "JUGGLER");
-      Assert.assertEquals(realmModel.getPrivateKeyPem(), "0234234");
-      Assert.assertEquals(realmModel.getPublicKeyPem(), "0234234");
-   }
+        System.out.println(realmModel.getId());
+        realmModel = adapter.getRealm(realmModel.getId());
+        Assert.assertNotNull(realmModel);
+        Assert.assertEquals(realmModel.getAccessCodeLifespan(), 100);
+        Assert.assertEquals(realmModel.getTokenLifespan(), 1000);
+        Assert.assertEquals(realmModel.isEnabled(), true);
+        Assert.assertEquals(realmModel.getName(), "JUGGLER");
+        Assert.assertEquals(realmModel.getPrivateKeyPem(), "0234234");
+        Assert.assertEquals(realmModel.getPublicKeyPem(), "0234234");
+    }
 
-   @Test
-   public void test2RequiredCredential() throws Exception
-   {
-      test1CreateRealm();
-      RequiredCredentialModel creds = new RequiredCredentialModel();
-      creds.setSecret(true);
-      creds.setType(RequiredCredentialRepresentation.PASSWORD);
-      creds.setInput(true);
-      realmModel.addRequiredCredential(creds);
-      creds = new RequiredCredentialModel();
-      creds.setSecret(true);
-      creds.setType(RequiredCredentialRepresentation.TOTP);
-      creds.setInput(true);
-      realmModel.addRequiredCredential(creds);
-      List<RequiredCredentialModel> storedCreds = realmModel.getRequiredCredentials();
-      Assert.assertEquals(2, storedCreds.size());
-      boolean totp = false;
-      boolean password = false;
-      for (RequiredCredentialModel cred : storedCreds)
-      {
-         if (cred.getType().equals(RequiredCredentialRepresentation.PASSWORD)) password = true;
-         else if (cred.getType().equals(RequiredCredentialRepresentation.TOTP)) totp = true;
-      }
-      Assert.assertTrue(totp);
-      Assert.assertTrue(password);
-   }
+    @Test
+    public void test2RequiredCredential() throws Exception {
+        test1CreateRealm();
+        RequiredCredentialModel creds = new RequiredCredentialModel();
+        creds.setSecret(true);
+        creds.setType(RequiredCredentialRepresentation.PASSWORD);
+        creds.setInput(true);
+        realmModel.addRequiredCredential(creds);
+        creds = new RequiredCredentialModel();
+        creds.setSecret(true);
+        creds.setType(RequiredCredentialRepresentation.TOTP);
+        creds.setInput(true);
+        realmModel.addRequiredCredential(creds);
+        List<RequiredCredentialModel> storedCreds = realmModel.getRequiredCredentials();
+        Assert.assertEquals(2, storedCreds.size());
+        boolean totp = false;
+        boolean password = false;
+        for (RequiredCredentialModel cred : storedCreds) {
+            if (cred.getType().equals(RequiredCredentialRepresentation.PASSWORD)) password = true;
+            else if (cred.getType().equals(RequiredCredentialRepresentation.TOTP)) totp = true;
+        }
+        Assert.assertTrue(totp);
+        Assert.assertTrue(password);
+    }
 
-   @Test
-   public void testCredentialValidation() throws Exception
-   {
-      test1CreateRealm();
-      User user = new SimpleUser("bburke");
-      realmModel.getIdm().add(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);
-   }
+    @Test
+    public void testCredentialValidation() throws Exception {
+        test1CreateRealm();
+        User user = new SimpleUser("bburke");
+        realmModel.getIdm().add(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);
+    }
 
-   @Test
-   public void testRoles() throws Exception
-   {
-      test1CreateRealm();
-      IdentityManager idm = realmModel.getIdm();
-      idm.add(new SimpleRole("admin"));
-      idm.add(new SimpleRole("user"));
-      List<Role> roles = realmModel.getRoles();
-      Assert.assertEquals(2, 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));
-   }
+    @Test
+    public void testRoles() throws Exception {
+        test1CreateRealm();
+        IdentityManager idm = realmModel.getIdm();
+        idm.add(new SimpleRole("admin"));
+        idm.add(new SimpleRole("user"));
+        List<Role> roles = realmModel.getRoles();
+        Assert.assertEquals(2, 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));
+    }
 
 
 }
diff --git a/services/src/test/java/org/keycloak/test/KeycloakTestBase.java b/services/src/test/java/org/keycloak/test/KeycloakTestBase.java
new file mode 100755
index 0000000..5bd0b6d
--- /dev/null
+++ b/services/src/test/java/org/keycloak/test/KeycloakTestBase.java
@@ -0,0 +1,31 @@
+package org.keycloak.test;
+
+import org.jboss.resteasy.jwt.JsonSerialization;
+import org.jboss.resteasy.test.BaseResourceTest;
+import org.keycloak.representations.idm.RealmRepresentation;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class KeycloakTestBase extends BaseResourceTest
+{
+   public static RealmRepresentation loadJson(String path) throws IOException
+   {
+      InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
+      ByteArrayOutputStream os = new ByteArrayOutputStream();
+      int c;
+      while ( (c = is.read()) != -1)
+      {
+         os.write(c);
+      }
+      byte[] bytes = os.toByteArray();
+      System.out.println(new String(bytes));
+
+      return JsonSerialization.fromBytes(RealmRepresentation.class, bytes);
+   }
+}
diff --git a/services/src/test/java/org/keycloak/test/RealmCreationTest.java b/services/src/test/java/org/keycloak/test/RealmCreationTest.java
new file mode 100755
index 0000000..57d378f
--- /dev/null
+++ b/services/src/test/java/org/keycloak/test/RealmCreationTest.java
@@ -0,0 +1,94 @@
+package org.keycloak.test;
+
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.jboss.resteasy.spi.ResteasyDeployment;
+import org.jboss.resteasy.test.EmbeddedContainer;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.keycloak.SkeletonKeyContextResolver;
+import org.keycloak.representations.AccessTokenResponse;
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.keycloak.representations.idm.RequiredCredentialRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
+import org.keycloak.services.managers.AuthenticationManager;
+import org.keycloak.services.managers.InstallationManager;
+import org.keycloak.services.models.RealmManager;
+import org.keycloak.services.resources.KeycloakApplication;
+import org.picketlink.idm.IdentitySession;
+import org.picketlink.idm.model.Realm;
+
+import javax.ws.rs.NotAuthorizedException;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+
+import static org.jboss.resteasy.test.TestPortProvider.generateURL;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class RealmCreationTest {
+
+    private static ResteasyDeployment deployment;
+    private static Client client;
+
+    @BeforeClass
+    public static void before() throws Exception {
+        deployment = new ResteasyDeployment();
+        deployment.setApplicationClass(KeycloakApplication.class.getName());
+        EmbeddedContainer.start(deployment);
+        KeycloakApplication application = (KeycloakApplication) deployment.getApplication();
+        IdentitySession IdentitySession = application.getFactory().createIdentitySession();
+        RealmManager manager = new RealmManager(IdentitySession);
+        new InstallationManager().install(manager);
+        client = new ResteasyClientBuilder().build();
+        client.register(SkeletonKeyContextResolver.class);
+    }
+
+    public static void after() throws Exception {
+        client.close();
+        EmbeddedContainer.stop();
+    }
+
+    @Test
+    public void testRegisterLoginAndCreate() throws Exception {
+        UserRepresentation user = new UserRepresentation();
+        user.setUsername("bburke");
+        user.credential(RequiredCredentialRepresentation.PASSWORD, "geheim", false);
+
+        WebTarget target = client.target(generateURL("/"));
+        Response response = target.path("registrations").request().post(Entity.json(user));
+        Assert.assertEquals(201, response.getStatus());
+        response.close();
+
+
+        AccessTokenResponse tokenResponse = null;
+        try {
+            Form form = new Form();
+            form.param(AuthenticationManager.FORM_USERNAME, "bburke");
+            form.param(RequiredCredentialRepresentation.PASSWORD, "badpassword");
+            tokenResponse = target.path("realms").path(Realm.DEFAULT_REALM).path("tokens/grants/identity-token").request().post(Entity.form(form), AccessTokenResponse.class);
+            Assert.fail();
+        } catch (NotAuthorizedException e) {
+        }
+        Form form = new Form();
+        form.param(AuthenticationManager.FORM_USERNAME, "bburke");
+        form.param(RequiredCredentialRepresentation.PASSWORD, "geheim");
+        tokenResponse = target.path("realms").path(Realm.DEFAULT_REALM).path("tokens/grants/identity-token").request().post(Entity.form(form), AccessTokenResponse.class);
+        Assert.assertNotNull(tokenResponse);
+        System.out.println(tokenResponse.getToken());
+        //
+
+        RealmRepresentation realm = KeycloakTestBase.loadJson("testrealm.json");
+        response = target.path("realms").request().header(HttpHeaders.AUTHORIZATION, "Bearer " + tokenResponse.getToken()).post(Entity.json(realm));
+        Assert.assertEquals(201, response.getStatus());
+        response.close();
+    }
+}
diff --git a/services/src/test/resources/META-INF/persistence.xml b/services/src/test/resources/META-INF/persistence.xml
index 1e5524f..7b7e664 100755
--- a/services/src/test/resources/META-INF/persistence.xml
+++ b/services/src/test/resources/META-INF/persistence.xml
@@ -2,7 +2,7 @@
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
     version="1.0">
-    <persistence-unit name="identitydb" transaction-type="RESOURCE_LOCAL">
+    <persistence-unit name="keycloak-identity-store" transaction-type="RESOURCE_LOCAL">
         <provider>org.hibernate.ejb.HibernatePersistence</provider>
         
         <class>org.picketlink.idm.jpa.schema.IdentityObject</class>