This commit is contained in:
Bill Burke 2013-07-19 17:59:36 -04:00
parent 79e6f46183
commit e1fe001a22
19 changed files with 466 additions and 45 deletions

View file

@ -15,6 +15,11 @@
<description/> <description/>
<dependencies> <dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jose-jwt</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.keycloak</groupId> <groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId> <artifactId>keycloak-core</artifactId>
@ -65,6 +70,11 @@
<artifactId>jaxrs-api</artifactId> <artifactId>jaxrs-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.161</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>

View file

@ -1,13 +1,42 @@
package org.keycloak.example.demo; package org.keycloak.example.demo;
import org.jboss.resteasy.jwt.JsonSerialization;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.models.RealmModel; import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RequiredCredentialModel; import org.keycloak.services.models.RequiredCredentialModel;
import org.keycloak.services.models.relationships.RealmAdminRelationship;
import org.keycloak.services.models.relationships.RequiredCredentialRelationship;
import org.keycloak.services.models.relationships.ResourceRelationship;
import org.keycloak.services.models.relationships.ScopeRelationship;
import org.keycloak.services.resources.KeycloakApplication; import org.keycloak.services.resources.KeycloakApplication;
import org.keycloak.services.resources.RegistrationService; import org.keycloak.services.resources.RegistrationService;
import org.picketlink.idm.IdentitySession;
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 org.picketlink.idm.model.Realm; import org.picketlink.idm.model.Realm;
import org.picketlink.idm.model.SimpleRole; import org.picketlink.idm.model.SimpleRole;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -16,7 +45,13 @@ public class DemoApplication extends KeycloakApplication {
public DemoApplication() { public DemoApplication() {
super(); super();
IdentitySession session = factory.createIdentitySession();
session.getTransaction().begin();
RealmManager realmManager = new RealmManager(session);
if (realmManager.defaultRealm() == null) {
install(realmManager);
}
session.getTransaction().commit();
} }
public void install(RealmManager manager) { public void install(RealmManager manager) {
@ -32,6 +67,31 @@ public class DemoApplication extends KeycloakApplication {
defaultRealm.updateRealm(); defaultRealm.updateRealm();
defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD); defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE)); defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
RealmRepresentation rep = loadJson("META-INF/testrealm.json");
RealmModel realm = manager.createRealm("demo", rep.getRealm());
manager.importRealm(rep, realm);
} }
public static RealmRepresentation loadJson(String path)
{
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
try {
while ( (c = is.read()) != -1)
{
os.write(c);
}
byte[] bytes = os.toByteArray();
//System.out.println(new String(bytes));
return JsonSerialization.fromBytes(RealmRepresentation.class, bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} }

View file

@ -0,0 +1,29 @@
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
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="keycloak-identity-store" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.picketlink.idm.jpa.schema.IdentityObject</class>
<class>org.picketlink.idm.jpa.schema.PartitionObject</class>
<class>org.picketlink.idm.jpa.schema.RelationshipObject</class>
<class>org.picketlink.idm.jpa.schema.RelationshipIdentityObject</class>
<class>org.picketlink.idm.jpa.schema.RelationshipIdentityWeakObject</class>
<class>org.picketlink.idm.jpa.schema.RelationshipObjectAttribute</class>
<class>org.picketlink.idm.jpa.schema.IdentityObjectAttribute</class>
<class>org.picketlink.idm.jpa.schema.CredentialObject</class>
<class>org.picketlink.idm.jpa.schema.CredentialObjectAttribute</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:h2:mem:test"/>
<property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>

View file

@ -0,0 +1,101 @@
{
"realm" : "demo",
"enabled" : true,
"tokenLifespan" : 6000,
"accessCodeLifespan" : 30,
"requiredCredentials" : [
{
"type" : "Password",
"input" : true,
"secret" : true
}
],
"users" : [
{
"username" : "wburke",
"enabled" : true,
"attributes" : {
"email" : "bburke@redhat.com"
},
"credentials" : [
{ "type" : "Password",
"value" : "userpassword" }
]
},
{
"username" : "loginclient",
"enabled" : true,
"credentials" : [
{ "type" : "Password",
"value" : "clientpassword" }
]
},
{
"username" : "admin",
"enabled" : true,
"credentials" : [
{ "type" : "Password",
"value" : "adminpassword" }
]
},
{
"username" : "oauthclient",
"enabled" : true,
"credentials" : [
{ "type" : "Password",
"value" : "clientpassword" }
]
}
],
"roleMappings" : [
{
"username" : "admin",
"roles" : ["admin"]
}
],
"scopeMappings" : [
{
"username" : "loginclient",
"roles" : ["*"]
}
],
"resources" : [
{
"name" : "Application",
"roles" : ["admin", "user"],
"roleMappings" : [
{
"username" : "wburke",
"roles" : ["user"]
},
{
"username" : "admin",
"roles" : ["admin"]
}
],
"scopeMappings" : [
{
"username" : "oauthclient",
"roles" : ["user"]
}
]
},
{
"name" : "OtherApp",
"roles" : ["admin", "user"],
"roleMappings" : [
{
"username" : "wburke",
"roles" : ["user"]
},
{
"username" : "admin",
"roles" : ["admin"]
}
]
}
]
}

View file

@ -0,0 +1,13 @@
<jboss-deployment-structure>
<deployment>
<!-- This allows you to define additional dependencies, it is the same as using the Dependencies: manifest attribute -->
<dependencies>
<!--
<module name="org.jboss.resteasy.resteasy-jaxrs" services="import"/>
<module name="org.jboss.resteasy.resteasy-jackson-provider" services="import"/> -->
<module name="org.jboss.resteasy.jose-jwt"/>
<module name="org.jboss.resteasy.resteasy-crypto"/>
<module name="org.bouncycastle"/>
</dependencies>
</deployment>
</jboss-deployment-structure>

View file

@ -3,6 +3,26 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> version="3.0">
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>org.keycloak.example.demo.DemoApplication</param-value>
</init-param>
<init-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- <!--
<security-constraint> <security-constraint>
<web-resource-collection> <web-resource-collection>

View file

@ -1,5 +1,6 @@
package org.keycloak.services.filters; package org.keycloak.services.filters;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.picketlink.idm.IdentitySession; import org.picketlink.idm.IdentitySession;
import org.picketlink.idm.IdentitySessionFactory; import org.picketlink.idm.IdentitySessionFactory;
@ -17,6 +18,7 @@ import java.io.IOException;
*/ */
@PreMatching @PreMatching
public class IdentitySessionFilter implements ContainerRequestFilter, ContainerResponseFilter { public class IdentitySessionFilter implements ContainerRequestFilter, ContainerResponseFilter {
protected static final Logger logger = Logger.getLogger(IdentitySessionFilter.class);
protected IdentitySessionFactory factory; protected IdentitySessionFactory factory;
public IdentitySessionFilter(IdentitySessionFactory factory) { public IdentitySessionFilter(IdentitySessionFactory factory) {

View file

@ -88,17 +88,23 @@ public class RealmManager {
public RealmModel importRealm(RealmRepresentation rep, User realmCreator) { public RealmModel importRealm(RealmRepresentation rep, User realmCreator) {
verifyRealmRepresentation(rep); verifyRealmRepresentation(rep);
RealmModel realm = createRealm(rep.getRealm()); RealmModel realm = createRealm(rep.getRealm());
generateRealmKeys(realm); importRealm(rep, realm);
realm.addRealmAdmin(realmCreator); realm.addRealmAdmin(realmCreator);
realm.setName(rep.getRealm());
realm.setEnabled(rep.isEnabled());
realm.setTokenLifespan(rep.getTokenLifespan());
realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
realm.setSslNotRequired(rep.isSslNotRequired());
realm.setCookieLoginAllowed(rep.isCookieLoginAllowed());
realm.updateRealm(); realm.updateRealm();
return realm;
}
public void importRealm(RealmRepresentation rep, RealmModel newRealm) {
generateRealmKeys(newRealm);
newRealm.setName(rep.getRealm());
newRealm.setEnabled(rep.isEnabled());
newRealm.setTokenLifespan(rep.getTokenLifespan());
newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
newRealm.setSslNotRequired(rep.isSslNotRequired());
newRealm.setCookieLoginAllowed(rep.isCookieLoginAllowed());
newRealm.updateRealm();
Map<String, User> userMap = new HashMap<String, User>(); Map<String, User> userMap = new HashMap<String, User>();
@ -108,7 +114,7 @@ public class RealmManager {
credential.setType(requiredCred.getType()); credential.setType(requiredCred.getType());
credential.setInput(requiredCred.isInput()); credential.setInput(requiredCred.isInput());
credential.setSecret(requiredCred.isSecret()); credential.setSecret(requiredCred.isSecret());
realm.addRequiredCredential(credential); newRealm.addRequiredCredential(credential);
} }
for (UserRepresentation userRep : rep.getUsers()) { for (UserRepresentation userRep : rep.getUsers()) {
@ -119,13 +125,13 @@ public class RealmManager {
user.setAttribute(new Attribute<String>(entry.getKey(), entry.getValue())); user.setAttribute(new Attribute<String>(entry.getKey(), entry.getValue()));
} }
} }
realm.getIdm().add(user); newRealm.getIdm().add(user);
if (userRep.getCredentials() != null) { if (userRep.getCredentials() != null) {
for (UserRepresentation.Credential cred : userRep.getCredentials()) { for (UserRepresentation.Credential cred : userRep.getCredentials()) {
UserCredentialModel credential = new UserCredentialModel(); UserCredentialModel credential = new UserCredentialModel();
credential.setType(cred.getType()); credential.setType(cred.getType());
credential.setValue(cred.getValue()); credential.setValue(cred.getValue());
realm.updateCredential(user, credential); newRealm.updateCredential(user, credential);
} }
} }
userMap.put(user.getLoginName(), user); userMap.put(user.getLoginName(), user);
@ -136,7 +142,7 @@ public class RealmManager {
if (rep.getRoles() != null) { if (rep.getRoles() != null) {
for (String roleString : rep.getRoles()) { for (String roleString : rep.getRoles()) {
SimpleRole role = new SimpleRole(roleString.trim()); SimpleRole role = new SimpleRole(roleString.trim());
realm.getIdm().add(role); newRealm.getIdm().add(role);
roles.put(role.getName(), role); roles.put(role.getName(), role);
} }
} }
@ -148,10 +154,10 @@ public class RealmManager {
Role role = roles.get(roleString.trim()); Role role = roles.get(roleString.trim());
if (role == null) { if (role == null) {
role = new SimpleRole(roleString.trim()); role = new SimpleRole(roleString.trim());
realm.getIdm().add(role); newRealm.getIdm().add(role);
roles.put(role.getName(), role); roles.put(role.getName(), role);
} }
realm.getIdm().grantRole(user, role); newRealm.getIdm().grantRole(user, role);
} }
} }
} }
@ -162,11 +168,11 @@ public class RealmManager {
Role role = roles.get(roleString.trim()); Role role = roles.get(roleString.trim());
if (role == null) { if (role == null) {
role = new SimpleRole(roleString.trim()); role = new SimpleRole(roleString.trim());
realm.getIdm().add(role); newRealm.getIdm().add(role);
roles.put(role.getName(), role); roles.put(role.getName(), role);
} }
User user = userMap.get(scope.getUsername()); User user = userMap.get(scope.getUsername());
realm.addScope(user, role.getName()); newRealm.addScope(user, role.getName());
} }
} }
@ -174,14 +180,13 @@ public class RealmManager {
if (!roles.containsKey("*")) { if (!roles.containsKey("*")) {
SimpleRole wildcard = new SimpleRole("*"); SimpleRole wildcard = new SimpleRole("*");
realm.getIdm().add(wildcard); newRealm.getIdm().add(wildcard);
roles.put("*", wildcard); roles.put("*", wildcard);
} }
if (rep.getResources() != null) { if (rep.getResources() != null) {
createResources(rep, realm, userMap); createResources(rep, newRealm, userMap);
} }
return realm;
} }
protected void createResources(RealmRepresentation rep, RealmModel realm, Map<String, User> userMap) { protected void createResources(RealmRepresentation rep, RealmModel realm, Map<String, User> userMap) {

View file

@ -93,7 +93,7 @@ public class TokenManager {
} }
public SkeletonKeyToken createLoginToken(RealmModel realm, User client, User user) { public SkeletonKeyToken createLoginToken(RealmModel realm, User client, User user) {
Set<String> mapping = realm.getScope(client); Set<String> mapping = realm.getScopes(client);
if (!mapping.contains("*")) { 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()); 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());
} }

View file

@ -315,11 +315,12 @@ public class RealmModel {
ScopeRelationship scope = new ScopeRelationship(); ScopeRelationship scope = new ScopeRelationship();
scope.setClient(agent); scope.setClient(agent);
scope.setScope(role); scope.setScope(role);
idm.add(scope);
} }
public Set<String> getScope(Agent agent) { public Set<String> getScopes(Agent agent) {
RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class); RelationshipQuery<ScopeRelationship> query = getIdm().createRelationshipQuery(ScopeRelationship.class);
query.setParameter(ScopeRelationship.CLIENT, agent); query.setParameter(ScopeRelationship.CLIENT, agent);
List<ScopeRelationship> scope = query.getResultList(); List<ScopeRelationship> scope = query.getResultList();

View file

@ -54,7 +54,7 @@ public class KeycloakApplication extends Application {
factory.close(); factory.close();
} }
public static IdentitySessionFactory createFactory() { public IdentitySessionFactory createFactory() {
ResourceLocalJpaIdentitySessionHandler handler = new ResourceLocalJpaIdentitySessionHandler("keycloak-identity-store"); ResourceLocalJpaIdentitySessionHandler handler = new ResourceLocalJpaIdentitySessionHandler("keycloak-identity-store");
IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder(); IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder();

View file

@ -45,22 +45,10 @@ public class RealmSubResource {
public String getRealmHtml(@PathParam("realm") String id) { public String getRealmHtml(@PathParam("realm") String id) {
StringBuffer html = new StringBuffer(); StringBuffer html = new StringBuffer();
UriBuilder auth = uriInfo.getBaseUriBuilder(); String authUri = TokenService.loginPage(uriInfo).build(realm.getId()).toString();
auth.path(TokenService.class) String codeUri = TokenService.accessCodeRequest(uriInfo).build(realm.getId()).toString();
.path(TokenService.class, "requestAccessCode"); String grantUrl = TokenService.grantRequest(uriInfo).build(realm.getId()).toString();
String authUri = auth.build(realm.getId()).toString(); String idGrantUrl = TokenService.identityGrantRequest(uriInfo).build(realm.getId()).toString();
UriBuilder code = uriInfo.getBaseUriBuilder();
code.path(TokenService.class).path(TokenService.class, "accessRequest");
String codeUri = code.build(realm.getId()).toString();
UriBuilder grant = uriInfo.getBaseUriBuilder();
grant.path(TokenService.class).path(TokenService.class, "accessTokenGrant");
String grantUrl = grant.build(realm.getId()).toString();
UriBuilder idGrant = uriInfo.getBaseUriBuilder();
grant.path(TokenService.class).path(TokenService.class, "identityTokenGrant");
String idGrantUrl = idGrant.build(realm.getId()).toString();
html.append("<html><body><h1>Realm: ").append(realm.getName()).append("</h1>"); html.append("<html><body><h1>Realm: ").append(realm.getName()).append("</h1>");
html.append("<p>auth: ").append(authUri).append("</p>"); html.append("<p>auth: ").append(authUri).append("</p>");

View file

@ -12,11 +12,13 @@ import org.picketlink.idm.model.Role;
import org.picketlink.idm.model.User; import org.picketlink.idm.model.User;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException; import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException; import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.container.ResourceContext; import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
@ -53,6 +55,7 @@ public class RealmsResource {
@Path("{realm}/tokens") @Path("{realm}/tokens")
public TokenService getTokenService(@PathParam("realm") String id) { public TokenService getTokenService(@PathParam("realm") String id) {
logger.info("**** HERE token service****");
RealmManager realmManager = new RealmManager(identitySession); RealmManager realmManager = new RealmManager(identitySession);
RealmModel realm = realmManager.getRealm(id); RealmModel realm = realmManager.getRealm(id);
if (realm == null) { if (realm == null) {
@ -68,6 +71,7 @@ public class RealmsResource {
@Path("{realm}") @Path("{realm}")
public RealmSubResource getRealmResource(@PathParam("realm") String id) { public RealmSubResource getRealmResource(@PathParam("realm") String id) {
logger.info("**** HERE @Path {realm} ****");
RealmManager realmManager = new RealmManager(identitySession); RealmManager realmManager = new RealmManager(identitySession);
RealmModel realm = realmManager.getRealm(id); RealmModel realm = realmManager.getRealm(id);
if (realm == null) { if (realm == null) {

View file

@ -12,8 +12,10 @@ import org.picketlink.idm.model.User;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.ForbiddenException; import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;

View file

@ -71,6 +71,36 @@ public class TokenService {
this.tokenManager = tokenManager; this.tokenManager = tokenManager;
} }
public static UriBuilder tokenServiceBase(UriInfo uriInfo) {
UriBuilder base = uriInfo.getBaseUriBuilder()
.path(RealmsResource.class).path(RealmsResource.class, "getTokenService");
return base;
}
public static UriBuilder accessCodeRequest(UriInfo uriInfo) {
return tokenServiceBase(uriInfo).path(TokenService.class, "accessRequest");
}
public static UriBuilder grantRequest(UriInfo uriInfo) {
return tokenServiceBase(uriInfo).path(TokenService.class, "accessTokenGrant");
}
public static UriBuilder identityGrantRequest(UriInfo uriInfo) {
return tokenServiceBase(uriInfo).path(TokenService.class, "accessTokenGrant");
}
public static UriBuilder loginPage(UriInfo uriInfo) {
return tokenServiceBase(uriInfo).path(TokenService.class, "requestAccessCode");
}
public static UriBuilder loginAction(UriInfo uriInfo) {
return tokenServiceBase(uriInfo).path(TokenService.class, "login");
}
@Path("grants/identity-token") @Path("grants/identity-token")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ -334,7 +364,7 @@ public class TokenService {
} }
html.append("</table><p>To Authorize, please login below</p>"); html.append("</table><p>To Authorize, please login below</p>");
} else { } else {
Set<String> scopeMapping = realm.getScope(client); Set<String> scopeMapping = realm.getScopes(client);
if (scopeMapping.contains("*")) { if (scopeMapping.contains("*")) {
html.append("<h1>Login For ").append(realm.getName()).append(" Realm</h1>"); html.append("<h1>Login For ").append(realm.getName()).append(" Realm</h1>");
if (validationError != null) { if (validationError != null) {
@ -388,7 +418,7 @@ public class TokenService {
} }
} }
UriBuilder formActionUri = uriInfo.getBaseUriBuilder().path(TokenService.class).path(TokenService.class, "login"); UriBuilder formActionUri = loginAction(uriInfo);
String action = formActionUri.build(realm.getId()).toString(); String action = formActionUri.build(realm.getId()).toString();
html.append("<form action=\"").append(action).append("\" method=\"POST\">"); html.append("<form action=\"").append(action).append("\" method=\"POST\">");
html.append("Username: <input type=\"text\" name=\"username\" size=\"20\"><br>"); html.append("Username: <input type=\"text\" name=\"username\" size=\"20\"><br>");

View file

@ -12,13 +12,29 @@ import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.models.RealmModel; import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RequiredCredentialModel; import org.keycloak.services.models.RequiredCredentialModel;
import org.keycloak.services.models.UserCredentialModel; import org.keycloak.services.models.UserCredentialModel;
import org.keycloak.services.models.relationships.RealmAdminRelationship;
import org.keycloak.services.models.relationships.RequiredCredentialRelationship;
import org.keycloak.services.models.relationships.ResourceRelationship;
import org.keycloak.services.models.relationships.ScopeRelationship;
import org.keycloak.services.resources.KeycloakApplication; import org.keycloak.services.resources.KeycloakApplication;
import org.picketlink.idm.IdentitySession; import org.picketlink.idm.IdentitySession;
import org.picketlink.idm.IdentitySessionFactory; import org.picketlink.idm.IdentitySessionFactory;
import org.picketlink.idm.IdentityManager; import org.picketlink.idm.IdentityManager;
import org.picketlink.idm.config.IdentityConfiguration;
import org.picketlink.idm.config.IdentityConfigurationBuilder;
import org.picketlink.idm.credential.Credentials; import org.picketlink.idm.credential.Credentials;
import org.picketlink.idm.credential.Password; import org.picketlink.idm.credential.Password;
import org.picketlink.idm.credential.UsernamePasswordCredentials; import org.picketlink.idm.credential.UsernamePasswordCredentials;
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 org.picketlink.idm.model.Role; import org.picketlink.idm.model.Role;
import org.picketlink.idm.model.SimpleRole; import org.picketlink.idm.model.SimpleRole;
import org.picketlink.idm.model.SimpleUser; import org.picketlink.idm.model.SimpleUser;
@ -39,11 +55,35 @@ public class AdapterTest {
@Before @Before
public void before() throws Exception { public void before() throws Exception {
factory = KeycloakApplication.createFactory(); factory = createFactory();
IdentitySession = factory.createIdentitySession(); IdentitySession = factory.createIdentitySession();
adapter = new RealmManager(IdentitySession); adapter = new RealmManager(IdentitySession);
} }
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);
}
@After @After
public void after() throws Exception { public void after() throws Exception {
IdentitySession.close(); IdentitySession.close();

View file

@ -0,0 +1,116 @@
package org.keycloak.test;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RequiredCredentialModel;
import org.keycloak.services.models.relationships.RealmAdminRelationship;
import org.keycloak.services.models.relationships.RequiredCredentialRelationship;
import org.keycloak.services.models.relationships.ResourceRelationship;
import org.keycloak.services.models.relationships.ScopeRelationship;
import org.keycloak.services.resources.RegistrationService;
import org.picketlink.idm.IdentitySession;
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 org.picketlink.idm.model.Realm;
import org.picketlink.idm.model.SimpleRole;
import org.picketlink.idm.model.User;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ImportTest {
private IdentitySessionFactory factory;
private IdentitySession identitySession;
private RealmManager manager;
private RealmModel realmModel;
@Before
public void before() throws Exception {
factory = createFactory();
identitySession = factory.createIdentitySession();
manager = new RealmManager(identitySession);
}
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);
}
@After
public void after() throws Exception {
identitySession.close();
factory.close();
}
@Test
public void install() throws Exception {
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);
defaultRealm.setRegistrationAllowed(true);
manager.generateRealmKeys(defaultRealm);
defaultRealm.updateRealm();
defaultRealm.addRequiredCredential(RequiredCredentialModel.PASSWORD);
defaultRealm.getIdm().add(new SimpleRole(RegistrationService.REALM_CREATOR_ROLE));
RealmRepresentation rep = KeycloakTestBase.loadJson("testrealm.json");
RealmModel realm = manager.createRealm("demo", rep.getRealm());
manager.importRealm(rep, realm);
User user = realm.getIdm().getUser("loginclient");
Assert.assertNotNull(user);
Set<String> scopes = realm.getScopes(user);
System.out.println("Scopes size: " + scopes.size());
Assert.assertTrue(scopes.contains("*"));
}
}

View file

@ -21,8 +21,8 @@
<property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/> <property name="hibernate.connection.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" /> <property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" /> <property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" /> <property name="hibernate.format_sql" value="false" />
</properties> </properties>
</persistence-unit> </persistence-unit>

2
services/src/test/resources/testrealm.json Normal file → Executable file
View file

@ -56,7 +56,7 @@
"scopeMappings" : [ "scopeMappings" : [
{ {
"username" : "loginclient", "username" : "loginclient",
"roles" : ["login"] "roles" : ["*"]
} }
], ],
"resources" : [ "resources" : [