commit
3034c0c5ff
41 changed files with 1130 additions and 673 deletions
|
@ -3,6 +3,9 @@
|
|||
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"
|
||||
version="3.0">
|
||||
|
||||
<module-name>customer-portal</module-name>
|
||||
|
||||
<security-constraint>
|
||||
<web-resource-collection>
|
||||
<web-resource-name>Admins</web-resource-name>
|
||||
|
|
|
@ -3,6 +3,9 @@
|
|||
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"
|
||||
version="3.0">
|
||||
|
||||
<module-name>database</module-name>
|
||||
|
||||
<security-constraint>
|
||||
<web-resource-collection>
|
||||
<url-pattern>/*</url-pattern>
|
||||
|
|
|
@ -3,6 +3,9 @@
|
|||
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"
|
||||
version="3.0">
|
||||
|
||||
<module-name>product-portal</module-name>
|
||||
|
||||
<security-constraint>
|
||||
<web-resource-collection>
|
||||
<web-resource-name>Admins</web-resource-name>
|
||||
|
|
|
@ -30,6 +30,21 @@
|
|||
<artifactId>keycloak-services</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-google</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-twitter</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.picketlink</groupId>
|
||||
<artifactId>picketlink-idm-api</artifactId>
|
||||
|
|
|
@ -3,8 +3,8 @@
|
|||
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>
|
||||
|
||||
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
|
||||
|
||||
<class>org.picketlink.idm.jpa.model.sample.simple.AttributedTypeEntity</class>
|
||||
<class>org.picketlink.idm.jpa.model.sample.simple.AccountTypeEntity</class>
|
||||
<class>org.picketlink.idm.jpa.model.sample.simple.RoleTypeEntity</class>
|
||||
|
@ -22,12 +22,8 @@
|
|||
<class>org.keycloak.services.models.picketlink.mappings.ResourceEntity</class>
|
||||
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
|
||||
|
||||
<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" />
|
|
@ -3,6 +3,9 @@
|
|||
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"
|
||||
version="3.0">
|
||||
|
||||
<module-name>auth-server</module-name>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>Resteasy</servlet-name>
|
||||
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher</servlet-class>
|
||||
|
|
|
@ -22,13 +22,41 @@
|
|||
<body>
|
||||
<div class="modal-body">
|
||||
|
||||
<div id="facebook-login-box" onclick="loginFacebook()">
|
||||
<img id="facebook-sign" src="<%=application.getContextPath()%>/img/facebook.png" border="0"/>
|
||||
</div>
|
||||
<%
|
||||
String googleLogin = request.getAttribute("KEYCLOAK_SOCIAL_LOGIN").toString();
|
||||
googleLogin += "?provider_id=google";
|
||||
googleLogin += "&client_id=" + request.getAttribute("client_id");
|
||||
if (request.getAttribute("scope") != null) {
|
||||
googleLogin += "&scope=" + request.getAttribute("scope");
|
||||
}
|
||||
if (request.getAttribute("state") != null) {
|
||||
googleLogin += "&state=" + request.getAttribute("state");
|
||||
}
|
||||
googleLogin += "&redirect_uri=" + request.getAttribute("redirect_uri");
|
||||
%>
|
||||
|
||||
<a href="<%=googleLogin%>">
|
||||
Login with Google
|
||||
</a>
|
||||
|
||||
<div id="twitter-login-box" onclick="loginTwitter()">
|
||||
<img id="twitter-sign" src="<%=application.getContextPath()%>/img/twitter.png" border="0"/>
|
||||
</div>
|
||||
<%
|
||||
String twitterLogin = request.getAttribute("KEYCLOAK_SOCIAL_LOGIN").toString();
|
||||
twitterLogin = twitterLogin.replace("://localhost", "://127.0.0.1");
|
||||
|
||||
twitterLogin += "?provider_id=twitter";
|
||||
twitterLogin += "&client_id=" + request.getAttribute("client_id");
|
||||
if (request.getAttribute("scope") != null) {
|
||||
twitterLogin += "&scope=" + request.getAttribute("scope");
|
||||
}
|
||||
if (request.getAttribute("state") != null) {
|
||||
twitterLogin += "&state=" + request.getAttribute("state");
|
||||
}
|
||||
twitterLogin += "&redirect_uri=" + request.getAttribute("redirect_uri");
|
||||
%>
|
||||
|
||||
<a href="<%=twitterLogin%>">
|
||||
Login with Twitter
|
||||
</a>
|
||||
|
||||
<hr/>
|
||||
<% String errorMessage = (String)request.getAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE");
|
||||
|
|
|
@ -3,6 +3,9 @@
|
|||
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"
|
||||
version="3.0">
|
||||
|
||||
<module-name>oauth-client</module-name>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.jboss.resteasy.example.oauth.Bootstrap</listener-class>
|
||||
</listener>
|
||||
|
|
1
pom.xml
1
pom.xml
|
@ -57,6 +57,7 @@
|
|||
<module>services</module>
|
||||
<module>integration</module>
|
||||
<module>examples</module>
|
||||
<module>social</module>
|
||||
<!--
|
||||
<module>sdk-html</module>
|
||||
<module>social</module>
|
||||
|
|
|
@ -24,6 +24,12 @@
|
|||
<version>${project.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.logging</groupId>
|
||||
<artifactId>jboss-logging</artifactId>
|
||||
|
|
|
@ -0,0 +1,107 @@
|
|||
package org.keycloak.services.resources;
|
||||
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
import org.jboss.resteasy.logging.Logger;
|
||||
import org.jboss.resteasy.spi.HttpRequest;
|
||||
import org.jboss.resteasy.spi.HttpResponse;
|
||||
import org.keycloak.services.JspRequestParameters;
|
||||
import org.keycloak.services.managers.AccessCodeEntry;
|
||||
import org.keycloak.services.managers.RealmManager;
|
||||
import org.keycloak.services.managers.TokenManager;
|
||||
import org.keycloak.services.models.RealmModel;
|
||||
import org.keycloak.services.models.RoleModel;
|
||||
import org.keycloak.services.models.UserModel;
|
||||
|
||||
public abstract class AbstractLoginService {
|
||||
|
||||
@Context
|
||||
protected UriInfo uriInfo;
|
||||
@Context
|
||||
protected HttpHeaders headers;
|
||||
@Context
|
||||
HttpRequest request;
|
||||
@Context
|
||||
HttpResponse response;
|
||||
|
||||
protected String securityFailurePath = "/securityFailure.jsp";
|
||||
protected String loginFormPath = "/loginForm.jsp";
|
||||
protected String oauthFormPath = "/oauthGrantForm.jsp";
|
||||
|
||||
protected RealmModel realm;
|
||||
protected TokenManager tokenManager;
|
||||
|
||||
public AbstractLoginService(RealmModel realm, TokenManager tokenManager) {
|
||||
this.realm = realm;
|
||||
this.tokenManager = tokenManager;
|
||||
}
|
||||
|
||||
protected Response processAccessCode(String scopeParam, String state, String redirect, UserModel client, UserModel user) {
|
||||
RoleModel resourceRole = realm.getRole(RealmManager.RESOURCE_ROLE);
|
||||
RoleModel identityRequestRole = realm.getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
|
||||
boolean isResource = realm.hasRole(client, resourceRole);
|
||||
if (!isResource && !realm.hasRole(client, identityRequestRole)) {
|
||||
securityFailureForward("Login requester not allowed to request login.");
|
||||
return null;
|
||||
}
|
||||
AccessCodeEntry accessCode = tokenManager.createAccessCode(scopeParam, state, redirect, realm, client, user);
|
||||
getLogger().info("processAccessCode: isResource: " + isResource);
|
||||
getLogger().info("processAccessCode: go to oauth page?: "
|
||||
+ (!isResource && (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested()
|
||||
.size() > 0)));
|
||||
if (!isResource
|
||||
&& (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested().size() > 0)) {
|
||||
oauthGrantPage(accessCode, client);
|
||||
return null;
|
||||
}
|
||||
return redirectAccessCode(accessCode, state, redirect);
|
||||
}
|
||||
|
||||
protected Response redirectAccessCode(AccessCodeEntry accessCode, String state, String redirect) {
|
||||
String code = accessCode.getCode();
|
||||
UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("code", code);
|
||||
getLogger().info("redirectAccessCode: state: " + state);
|
||||
if (state != null)
|
||||
redirectUri.queryParam("state", state);
|
||||
Response.ResponseBuilder location = Response.status(302).location(redirectUri.build());
|
||||
if (realm.isCookieLoginAllowed()) {
|
||||
location.cookie(tokenManager.createLoginCookie(realm, accessCode.getUser(), uriInfo));
|
||||
}
|
||||
return location.build();
|
||||
}
|
||||
|
||||
protected void securityFailureForward(String message) {
|
||||
getLogger().error(message);
|
||||
request.setAttribute(JspRequestParameters.KEYCLOAK_SECURITY_FAILURE_MESSAGE, message);
|
||||
request.forward(securityFailurePath);
|
||||
}
|
||||
|
||||
protected void forwardToLoginForm(String redirect, String clientId, String scopeParam, String state) {
|
||||
request.setAttribute(RealmModel.class.getName(), realm);
|
||||
request.setAttribute("KEYCLOAK_LOGIN_ACTION", TokenService.processLoginUrl(uriInfo).build(realm.getId()));
|
||||
request.setAttribute("KEYCLOAK_SOCIAL_LOGIN", SocialService.redirectToProviderAuthUrl(uriInfo).build(realm.getId()));
|
||||
|
||||
// RESTEASY eats the form data, so we send via an attribute
|
||||
request.setAttribute("redirect_uri", redirect);
|
||||
request.setAttribute("client_id", clientId);
|
||||
request.setAttribute("scope", scopeParam);
|
||||
request.setAttribute("state", state);
|
||||
request.forward(loginFormPath);
|
||||
}
|
||||
|
||||
protected void oauthGrantPage(AccessCodeEntry accessCode, UserModel client) {
|
||||
request.setAttribute("realmRolesRequested", accessCode.getRealmRolesRequested());
|
||||
request.setAttribute("resourceRolesRequested", accessCode.getResourceRolesRequested());
|
||||
request.setAttribute("client", client);
|
||||
request.setAttribute("action", TokenService.processOAuthUrl(uriInfo).build(realm.getId()).toString());
|
||||
request.setAttribute("code", accessCode.getCode());
|
||||
|
||||
request.forward(oauthFormPath);
|
||||
}
|
||||
|
||||
protected abstract Logger getLogger();
|
||||
}
|
|
@ -9,6 +9,7 @@ import org.keycloak.services.models.picketlink.PicketlinkKeycloakSession;
|
|||
import org.keycloak.services.models.picketlink.PicketlinkKeycloakSessionFactory;
|
||||
import org.keycloak.services.models.picketlink.mappings.RealmEntity;
|
||||
import org.keycloak.services.models.picketlink.mappings.ResourceEntity;
|
||||
import org.keycloak.social.SocialRequestManager;
|
||||
import org.picketlink.idm.PartitionManager;
|
||||
import org.picketlink.idm.config.IdentityConfigurationBuilder;
|
||||
import org.picketlink.idm.internal.DefaultPartitionManager;
|
||||
|
@ -49,7 +50,7 @@ public class KeycloakApplication extends Application {
|
|||
KeycloakSessionFactory f = createSessionFactory();
|
||||
this.factory = f;
|
||||
KeycloakSessionRequestFilter filter = new KeycloakSessionRequestFilter(factory);
|
||||
singletons.add(new RealmsResource(new TokenManager()));
|
||||
singletons.add(new RealmsResource(new TokenManager(), new SocialRequestManager()));
|
||||
singletons.add(filter);
|
||||
classes.add(KeycloakSessionResponseFilter.class);
|
||||
classes.add(SkeletonKeyContextResolver.class);
|
||||
|
|
|
@ -10,6 +10,7 @@ import org.keycloak.services.models.KeycloakSessionFactory;
|
|||
import org.keycloak.services.models.RealmModel;
|
||||
import org.keycloak.services.models.RoleModel;
|
||||
import org.keycloak.services.models.UserModel;
|
||||
import org.keycloak.social.SocialRequestManager;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.NotAuthorizedException;
|
||||
|
@ -44,8 +45,11 @@ public class RealmsResource {
|
|||
|
||||
protected TokenManager tokenManager;
|
||||
|
||||
public RealmsResource(TokenManager tokenManager) {
|
||||
protected SocialRequestManager socialRequestManager;
|
||||
|
||||
public RealmsResource(TokenManager tokenManager, SocialRequestManager socialRequestManager) {
|
||||
this.tokenManager = tokenManager;
|
||||
this.socialRequestManager = socialRequestManager;
|
||||
}
|
||||
|
||||
public static UriBuilder realmBaseUrl(UriInfo uriInfo) {
|
||||
|
@ -71,6 +75,23 @@ public class RealmsResource {
|
|||
|
||||
}
|
||||
|
||||
@Path("{realm}/social")
|
||||
public SocialService getSocialService(final @PathParam("realm") String id) {
|
||||
return new Transaction(false) {
|
||||
@Override
|
||||
protected SocialService callImpl() {
|
||||
RealmManager realmManager = new RealmManager(session);
|
||||
RealmModel realm = realmManager.getRealm(id);
|
||||
if (realm == null) {
|
||||
logger.debug("realm not found");
|
||||
throw new NotFoundException();
|
||||
}
|
||||
SocialService socialService = new SocialService(realm, tokenManager, socialRequestManager);
|
||||
resourceContext.initResource(socialService);
|
||||
return socialService;
|
||||
}
|
||||
}.call();
|
||||
}
|
||||
|
||||
@Path("{realm}")
|
||||
public RealmSubResource getRealmResource(final @PathParam("realm") String id) {
|
||||
|
|
|
@ -0,0 +1,259 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.services.resources;
|
||||
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import javax.imageio.spi.ServiceRegistry;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
import org.jboss.resteasy.logging.Logger;
|
||||
import org.keycloak.services.managers.TokenManager;
|
||||
import org.keycloak.services.models.RealmModel;
|
||||
import org.keycloak.services.models.UserModel;
|
||||
import org.keycloak.social.AuthCallback;
|
||||
import org.keycloak.social.AuthRequest;
|
||||
import org.keycloak.social.RequestDetails;
|
||||
import org.keycloak.social.RequestDetailsBuilder;
|
||||
import org.keycloak.social.SocialProvider;
|
||||
import org.keycloak.social.SocialProviderConfig;
|
||||
import org.keycloak.social.SocialProviderException;
|
||||
import org.keycloak.social.SocialRequestManager;
|
||||
import org.keycloak.social.SocialUser;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class SocialService extends AbstractLoginService {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SocialService.class);
|
||||
|
||||
@Context
|
||||
private HttpHeaders headers;
|
||||
|
||||
@Context
|
||||
private UriInfo uriInfo;
|
||||
|
||||
public static UriBuilder socialServiceBaseUrl(UriInfo uriInfo) {
|
||||
UriBuilder base = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getSocialService");
|
||||
return base;
|
||||
}
|
||||
|
||||
public static UriBuilder redirectToProviderAuthUrl(UriInfo uriInfo) {
|
||||
return socialServiceBaseUrl(uriInfo).path(SocialService.class, "redirectToProviderAuth");
|
||||
|
||||
}
|
||||
|
||||
public static UriBuilder callbackUrl(UriInfo uriInfo) {
|
||||
return socialServiceBaseUrl(uriInfo).path(SocialService.class, "callback");
|
||||
|
||||
}
|
||||
|
||||
private SocialRequestManager socialRequestManager;
|
||||
|
||||
public SocialService(RealmModel realm, TokenManager tokenManager, SocialRequestManager socialRequestManager) {
|
||||
super(realm, tokenManager);
|
||||
this.socialRequestManager = socialRequestManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("callback")
|
||||
public Response callback() throws URISyntaxException {
|
||||
return new Transaction() {
|
||||
protected Response callImpl() {
|
||||
Map<String, String[]> queryParams = getQueryParams();
|
||||
|
||||
RequestDetails requestData = getRequestDetails(queryParams);
|
||||
SocialProvider provider = getProvider(requestData.getProviderId());
|
||||
|
||||
String key = System.getProperty("keycloak.social." + requestData.getProviderId() + ".key");
|
||||
String secret = System.getProperty("keycloak.social." + requestData.getProviderId() + ".secret");
|
||||
String callbackUri = callbackUrl(uriInfo).build(realm.getId()).toString();
|
||||
|
||||
SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);
|
||||
|
||||
AuthCallback callback = new AuthCallback(requestData.getSocialAttributes(), queryParams);
|
||||
|
||||
SocialUser socialUser = null;
|
||||
try {
|
||||
socialUser = provider.processCallback(config, callback);
|
||||
} catch (SocialProviderException e) {
|
||||
logger.warn("Failed to process social callback", e);
|
||||
securityFailureForward("Failed to process social callback");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!realm.isEnabled()) {
|
||||
securityFailureForward("Realm not enabled.");
|
||||
return null;
|
||||
}
|
||||
|
||||
String clientId = requestData.getClientAttributes().get("clientId");
|
||||
|
||||
UserModel client = realm.getUser(clientId);
|
||||
if (client == null) {
|
||||
securityFailureForward("Unknown login requester.");
|
||||
return null;
|
||||
}
|
||||
if (!client.isEnabled()) {
|
||||
securityFailureForward("Login requester not enabled.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO Lookup user based on attribute for provider id - this is so a user can have a friendly username + link a
|
||||
// user to
|
||||
// multiple social logins
|
||||
UserModel user = realm.getUser(provider.getId() + "." + socialUser.getId());
|
||||
|
||||
if (user == null) {
|
||||
user = realm.addUser(provider.getId() + "." + socialUser.getId());
|
||||
user.setAttribute(provider.getId() + ".id", socialUser.getId());
|
||||
|
||||
// TODO Grant default roles for realm when available
|
||||
realm.grantRole(user, realm.getRole("user"));
|
||||
}
|
||||
|
||||
if (!user.isEnabled()) {
|
||||
securityFailureForward("Your account is not enabled.");
|
||||
return null;
|
||||
}
|
||||
|
||||
String scope = requestData.getClientAttributes().get("scope");
|
||||
String state = requestData.getClientAttributes().get("state");
|
||||
String redirectUri = requestData.getClientAttributes().get("redirectUri");
|
||||
|
||||
return processAccessCode(scope, state, redirectUri, client, user);
|
||||
}
|
||||
}.call();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("providers")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public List<SocialProvider> getProviders() {
|
||||
List<SocialProvider> providers = new LinkedList<SocialProvider>();
|
||||
Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(SocialProvider.class);
|
||||
while (itr.hasNext()) {
|
||||
providers.add(itr.next());
|
||||
}
|
||||
return providers;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("login")
|
||||
public Response redirectToProviderAuth(@QueryParam("provider_id") final String providerId,
|
||||
@QueryParam("client_id") final String clientId, @QueryParam("scope") final String scope,
|
||||
@QueryParam("state") final String state, @QueryParam("redirect_uri") final String redirectUri) {
|
||||
return new Transaction() {
|
||||
protected Response callImpl() {
|
||||
SocialProvider provider = getProvider(providerId);
|
||||
if (provider == null) {
|
||||
securityFailureForward("Social provider not found");
|
||||
return null;
|
||||
}
|
||||
|
||||
String key = System.getProperty("keycloak.social." + providerId + ".key");
|
||||
String secret = System.getProperty("keycloak.social." + providerId + ".secret");
|
||||
String callbackUri = callbackUrl(uriInfo).build(realm.getId()).toString();
|
||||
|
||||
SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);
|
||||
|
||||
try {
|
||||
AuthRequest authRequest = provider.getAuthUrl(config);
|
||||
|
||||
RequestDetails socialRequest = RequestDetailsBuilder.create(providerId)
|
||||
.putSocialAttributes(authRequest.getAttributes()).putClientAttribute("clientId", clientId)
|
||||
.putClientAttribute("scope", scope).putClientAttribute("state", state)
|
||||
.putClientAttribute("redirectUri", redirectUri).build();
|
||||
|
||||
socialRequestManager.addRequest(authRequest.getId(), socialRequest);
|
||||
|
||||
return Response.status(Status.FOUND).location(authRequest.getAuthUri()).build();
|
||||
} catch (Throwable t) {
|
||||
logger.error("Failed to redirect to social auth", t);
|
||||
securityFailureForward("Failed to redirect to social auth");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}.call();
|
||||
}
|
||||
|
||||
private RequestDetails getRequestDetails(Map<String, String[]> queryParams) {
|
||||
Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(SocialProvider.class);
|
||||
|
||||
while (itr.hasNext()) {
|
||||
SocialProvider provider = itr.next();
|
||||
|
||||
if (queryParams.containsKey(provider.getRequestIdParamName())) {
|
||||
String requestId = queryParams.get(provider.getRequestIdParamName())[0];
|
||||
if (socialRequestManager.isRequestId(requestId)) {
|
||||
return socialRequestManager.retrieveData(requestId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private SocialProvider getProvider(String providerId) {
|
||||
Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(SocialProvider.class);
|
||||
|
||||
while (itr.hasNext()) {
|
||||
SocialProvider provider = itr.next();
|
||||
if (provider.getId().equals(providerId)) {
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Map<String, String[]> getQueryParams() {
|
||||
Map<String, String[]> queryParams = new HashMap<String, String[]>();
|
||||
for (Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
|
||||
queryParams.put(e.getKey(), e.getValue().toArray(new String[e.getValue().size()]));
|
||||
}
|
||||
return queryParams;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
}
|
|
@ -5,17 +5,13 @@ import org.jboss.resteasy.jose.jws.JWSInput;
|
|||
import org.jboss.resteasy.jose.jws.crypto.RSAProvider;
|
||||
import org.jboss.resteasy.jwt.JsonSerialization;
|
||||
import org.jboss.resteasy.logging.Logger;
|
||||
import org.jboss.resteasy.spi.HttpRequest;
|
||||
import org.jboss.resteasy.spi.HttpResponse;
|
||||
import org.keycloak.representations.AccessTokenResponse;
|
||||
import org.keycloak.representations.SkeletonKeyToken;
|
||||
import org.keycloak.services.JspRequestParameters;
|
||||
import org.keycloak.services.managers.AccessCodeEntry;
|
||||
import org.keycloak.services.managers.AuthenticationManager;
|
||||
import org.keycloak.services.managers.RealmManager;
|
||||
import org.keycloak.services.managers.ResourceAdminManager;
|
||||
import org.keycloak.services.managers.TokenManager;
|
||||
import org.keycloak.services.models.KeycloakSession;
|
||||
import org.keycloak.services.models.RealmModel;
|
||||
import org.keycloak.services.models.RoleModel;
|
||||
import org.keycloak.services.models.UserModel;
|
||||
|
@ -28,7 +24,6 @@ import javax.ws.rs.Path;
|
|||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
@ -44,37 +39,21 @@ import java.util.Map;
|
|||
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
|
||||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class TokenService {
|
||||
public class TokenService extends AbstractLoginService {
|
||||
|
||||
|
||||
protected static final Logger logger = Logger.getLogger(TokenService.class);
|
||||
|
||||
@Context
|
||||
protected UriInfo uriInfo;
|
||||
@Context
|
||||
protected Providers providers;
|
||||
@Context
|
||||
protected SecurityContext securityContext;
|
||||
@Context
|
||||
protected HttpHeaders headers;
|
||||
@Context
|
||||
HttpRequest request;
|
||||
@Context
|
||||
HttpResponse response;
|
||||
|
||||
protected String securityFailurePath = "/securityFailure.jsp";
|
||||
protected String loginFormPath = "/loginForm.jsp";
|
||||
protected String oauthFormPath = "/oauthGrantForm.jsp";
|
||||
|
||||
protected RealmModel realm;
|
||||
protected TokenManager tokenManager;
|
||||
|
||||
protected AuthenticationManager authManager = new AuthenticationManager();
|
||||
private ResourceAdminManager resourceAdminManager = new ResourceAdminManager();
|
||||
|
||||
public TokenService(RealmModel realm, TokenManager tokenManager) {
|
||||
this.realm = realm;
|
||||
this.tokenManager = tokenManager;
|
||||
super(realm, tokenManager);
|
||||
}
|
||||
|
||||
public static UriBuilder tokenServiceBaseUrl(UriInfo uriInfo) {
|
||||
|
@ -227,36 +206,6 @@ public class TokenService {
|
|||
}.call();
|
||||
}
|
||||
|
||||
protected Response processAccessCode(String scopeParam, String state, String redirect, UserModel client, UserModel user) {
|
||||
RoleModel resourceRole = realm.getRole(RealmManager.RESOURCE_ROLE);
|
||||
RoleModel identityRequestRole = realm.getRole(RealmManager.IDENTITY_REQUESTER_ROLE);
|
||||
boolean isResource = realm.hasRole(client, resourceRole);
|
||||
if (!isResource && !realm.hasRole(client, identityRequestRole)) {
|
||||
securityFailureForward("Login requester not allowed to request login.");
|
||||
return null;
|
||||
}
|
||||
AccessCodeEntry accessCode = tokenManager.createAccessCode(scopeParam, state, redirect, realm, client, user);
|
||||
logger.info("processAccessCode: isResource: " + isResource);
|
||||
logger.info("processAccessCode: go to oauth page?: " + (!isResource && (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested().size() > 0)));
|
||||
if (!isResource && (accessCode.getRealmRolesRequested().size() > 0 || accessCode.getResourceRolesRequested().size() > 0)) {
|
||||
oauthGrantPage(accessCode, client);
|
||||
return null;
|
||||
}
|
||||
return redirectAccessCode(accessCode, state, redirect);
|
||||
}
|
||||
|
||||
protected Response redirectAccessCode(AccessCodeEntry accessCode, String state, String redirect) {
|
||||
String code = accessCode.getCode();
|
||||
UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("code", code);
|
||||
logger.info("redirectAccessCode: state: " + state);
|
||||
if (state != null) redirectUri.queryParam("state", state);
|
||||
Response.ResponseBuilder location = Response.status(302).location(redirectUri.build());
|
||||
if (realm.isCookieLoginAllowed()) {
|
||||
location.cookie(tokenManager.createLoginCookie(realm, accessCode.getUser(), uriInfo));
|
||||
}
|
||||
return location.build();
|
||||
}
|
||||
|
||||
@Path("access/codes")
|
||||
@POST
|
||||
@Produces("application/json")
|
||||
|
@ -382,27 +331,6 @@ public class TokenService {
|
|||
return res;
|
||||
}
|
||||
|
||||
protected void securityFailureForward(String message) {
|
||||
logger.error(message);
|
||||
request.setAttribute(JspRequestParameters.KEYCLOAK_SECURITY_FAILURE_MESSAGE, message);
|
||||
request.forward(securityFailurePath);
|
||||
}
|
||||
|
||||
protected void forwardToLoginForm(String redirect,
|
||||
String clientId,
|
||||
String scopeParam,
|
||||
String state) {
|
||||
request.setAttribute(RealmModel.class.getName(), realm);
|
||||
request.setAttribute("KEYCLOAK_LOGIN_ACTION", processLoginUrl(uriInfo).build(realm.getId()));
|
||||
|
||||
// RESTEASY eats the form data, so we send via an attribute
|
||||
request.setAttribute("redirect_uri", redirect);
|
||||
request.setAttribute("client_id", clientId);
|
||||
request.setAttribute("scope", scopeParam);
|
||||
request.setAttribute("state", state);
|
||||
request.forward(loginFormPath);
|
||||
}
|
||||
|
||||
@Path("login")
|
||||
@GET
|
||||
public Response loginPage(final @QueryParam("response_type") String responseType,
|
||||
|
@ -517,14 +445,9 @@ public class TokenService {
|
|||
return location.build();
|
||||
}
|
||||
|
||||
protected void oauthGrantPage(AccessCodeEntry accessCode, UserModel client) {
|
||||
request.setAttribute("realmRolesRequested", accessCode.getRealmRolesRequested());
|
||||
request.setAttribute("resourceRolesRequested", accessCode.getResourceRolesRequested());
|
||||
request.setAttribute("client", client);
|
||||
request.setAttribute("action", processOAuthUrl(uriInfo).build(realm.getId()).toString());
|
||||
request.setAttribute("code", accessCode.getCode());
|
||||
|
||||
request.forward(oauthFormPath);
|
||||
@Override
|
||||
protected Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
23
social/core/pom.xml
Executable file
23
social/core/pom.xml
Executable file
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0"?>
|
||||
<project>
|
||||
<parent>
|
||||
<artifactId>keycloak-social-parent</artifactId>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<version>1.0-alpha-1</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>keycloak-social-core</artifactId>
|
||||
<name>Keycloak Social Core</name>
|
||||
<description/>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>jaxrs-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,52 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class AuthCallback {
|
||||
|
||||
private Map<String, String> attributes;
|
||||
|
||||
private Map<String, String[]> queryParams;
|
||||
|
||||
public AuthCallback(Map<String, String> attributes, Map<String, String[]> queryParams) {
|
||||
this.attributes = attributes;
|
||||
this.queryParams = queryParams;
|
||||
}
|
||||
|
||||
public String getAttribute(String name) {
|
||||
return attributes.get(name);
|
||||
}
|
||||
|
||||
public String getQueryParam(String name) {
|
||||
String[] value = queryParams.get(name);
|
||||
if (value.length > 0) {
|
||||
return value[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -21,28 +21,36 @@
|
|||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class IdentityProviderState {
|
||||
public class AuthRequest {
|
||||
|
||||
private final Map<String, Object> state = Collections.synchronizedMap(new HashMap<String, Object>());
|
||||
private String id;
|
||||
|
||||
public boolean contains(String key) {
|
||||
return state.containsKey(key);
|
||||
private URI authUri;
|
||||
|
||||
private Map<String, String> attributes;
|
||||
|
||||
AuthRequest(String id, URI authUri, Map<String, String> attributes) {
|
||||
this.id = id;
|
||||
this.authUri = authUri;
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
public void put(String key, Object value) {
|
||||
state.put(key, value);
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T remove(String key) {
|
||||
return (T) state.remove(key);
|
||||
public URI getAuthUri() {
|
||||
return authUri;
|
||||
}
|
||||
|
||||
public Map<String, String> getAttributes() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class AuthRequestBuilder {
|
||||
|
||||
private UriBuilder b;
|
||||
|
||||
private Map<String, String> attributes;
|
||||
|
||||
private String id;
|
||||
|
||||
private AuthRequestBuilder() {
|
||||
}
|
||||
|
||||
public static AuthRequestBuilder create(String id, String path) {
|
||||
AuthRequestBuilder req = new AuthRequestBuilder();
|
||||
req.id = id;
|
||||
req.b = UriBuilder.fromUri(path);
|
||||
req.attributes = new HashMap<String, String>();
|
||||
return req;
|
||||
}
|
||||
|
||||
public AuthRequestBuilder setQueryParam(String name, String value) {
|
||||
b.queryParam(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuthRequestBuilder setAttribute(String name, String value) {
|
||||
attributes.put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuthRequest build() {
|
||||
return new AuthRequest(id, b.build(), attributes);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class RequestDetails {
|
||||
|
||||
private String providerId;
|
||||
|
||||
private Map<String, String> clientAttributes;
|
||||
|
||||
private Map<String, String> socialAttributes;
|
||||
|
||||
RequestDetails(String providerId, Map<String, String> clientAttributes, Map<String, String> socialAttributes) {
|
||||
this.providerId = providerId;
|
||||
this.clientAttributes = clientAttributes;
|
||||
this.socialAttributes = socialAttributes;
|
||||
}
|
||||
|
||||
public String getProviderId() {
|
||||
return providerId;
|
||||
}
|
||||
|
||||
public String getClientAttribute(String name) {
|
||||
return clientAttributes.get(name);
|
||||
}
|
||||
|
||||
public Map<String, String> getClientAttributes() {
|
||||
return clientAttributes;
|
||||
}
|
||||
|
||||
public String getSocialAttribute(String name) {
|
||||
return socialAttributes.get(name);
|
||||
}
|
||||
|
||||
public Map<String, String> getSocialAttributes() {
|
||||
return socialAttributes;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class RequestDetailsBuilder {
|
||||
|
||||
private String providerId;
|
||||
|
||||
private Map<String, String> clientAttributes;
|
||||
|
||||
private Map<String, String> socialAttributes;
|
||||
|
||||
private RequestDetailsBuilder() {
|
||||
}
|
||||
|
||||
public static RequestDetailsBuilder create(String providerId) {
|
||||
RequestDetailsBuilder req = new RequestDetailsBuilder();
|
||||
req.providerId = providerId;
|
||||
req.clientAttributes = new HashMap<String, String>();
|
||||
req.socialAttributes = new HashMap<String, String>();
|
||||
return req;
|
||||
}
|
||||
|
||||
public RequestDetailsBuilder putClientAttribute(String name, String value) {
|
||||
clientAttributes.put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RequestDetailsBuilder putClientAttributes(Map<String, String> attributes) {
|
||||
clientAttributes.putAll(attributes);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RequestDetailsBuilder putSocialAttribute(String name, String value) {
|
||||
socialAttributes.put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RequestDetailsBuilder putSocialAttributes(Map<String, String> attributes) {
|
||||
socialAttributes.putAll(attributes);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RequestDetails build() {
|
||||
return new RequestDetails(providerId, clientAttributes, socialAttributes);
|
||||
}
|
||||
|
||||
}
|
|
@ -21,30 +21,25 @@
|
|||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
import org.picketlink.idm.model.User;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
@XmlRootElement
|
||||
public interface IdentityProvider {
|
||||
public interface SocialProvider {
|
||||
|
||||
String getId();
|
||||
|
||||
@XmlTransient
|
||||
URI getAuthUrl(IdentityProviderCallback callback) throws IdentityProviderException;
|
||||
AuthRequest getAuthUrl(SocialProviderConfig config) throws SocialProviderException;
|
||||
|
||||
String getRequestIdParamName();
|
||||
|
||||
String getName();
|
||||
|
||||
@XmlTransient
|
||||
boolean isCallbackHandler(IdentityProviderCallback callback);
|
||||
|
||||
@XmlTransient
|
||||
User processCallback(IdentityProviderCallback callback) throws IdentityProviderException;
|
||||
SocialUser processCallback(SocialProviderConfig config, AuthCallback callback) throws SocialProviderException;
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class SocialProviderConfig {
|
||||
|
||||
private String callbackUrl;
|
||||
|
||||
private String key;
|
||||
|
||||
private String secret;
|
||||
|
||||
public SocialProviderConfig(String key, String secret, String callbackUrl) {
|
||||
this.key = key;
|
||||
this.secret = secret;
|
||||
this.callbackUrl = callbackUrl;
|
||||
}
|
||||
|
||||
public String getCallbackUrl() {
|
||||
return callbackUrl;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
}
|
||||
|
||||
public void setSecret(String secret) {
|
||||
this.secret = secret;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class SocialProviderException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public SocialProviderException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public SocialProviderException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public SocialProviderException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class SocialRequestManager {
|
||||
|
||||
public static final long TIMEOUT = 10 * 60 * 1000;
|
||||
|
||||
private Map<String, RequestDetails> map = new HashMap<String, RequestDetails>();
|
||||
|
||||
private LinkedHashMap<String, Long> expires = new LinkedHashMap<String, Long>();
|
||||
|
||||
public synchronized void addRequest(String requestId, RequestDetails request) {
|
||||
pruneExpired();
|
||||
|
||||
map.put(requestId, request);
|
||||
expires.put(requestId, System.currentTimeMillis() + TIMEOUT);
|
||||
}
|
||||
|
||||
public synchronized boolean isRequestId(String requestId) {
|
||||
return map.containsKey(requestId);
|
||||
}
|
||||
|
||||
public synchronized RequestDetails retrieveData(String requestId) {
|
||||
expires.remove(requestId);
|
||||
RequestDetails details = map.remove(requestId);
|
||||
|
||||
pruneExpired();
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
private void pruneExpired() {
|
||||
Iterator<Entry<String, Long>> itr = expires.entrySet().iterator();
|
||||
while (itr.hasNext()) {
|
||||
Entry<String, Long> e = itr.next();
|
||||
if (e.getValue() < System.currentTimeMillis()) {
|
||||
itr.remove();
|
||||
map.remove(e.getKey());
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package org.keycloak.social;
|
||||
|
||||
public class SocialUser {
|
||||
|
||||
private String id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String email;
|
||||
|
||||
public SocialUser(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
}
|
37
social/google/pom.xml
Executable file
37
social/google/pom.xml
Executable file
|
@ -0,0 +1,37 @@
|
|||
<?xml version="1.0"?>
|
||||
<project>
|
||||
<parent>
|
||||
<artifactId>keycloak-social-parent</artifactId>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<version>1.0-alpha-1</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>keycloak-social-google</artifactId>
|
||||
<name>Keycloak Social Google</name>
|
||||
<description/>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
<artifactId>google-api-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.apis</groupId>
|
||||
<artifactId>google-api-services-oauth2</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -21,14 +21,15 @@
|
|||
*/
|
||||
package org.keycloak.social.google;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.keycloak.social.IdentityProvider;
|
||||
import org.keycloak.social.IdentityProviderCallback;
|
||||
import org.keycloak.social.IdentityProviderException;
|
||||
import org.picketlink.idm.model.SimpleUser;
|
||||
import org.picketlink.idm.model.User;
|
||||
import org.keycloak.social.AuthCallback;
|
||||
import org.keycloak.social.AuthRequest;
|
||||
import org.keycloak.social.AuthRequestBuilder;
|
||||
import org.keycloak.social.SocialProvider;
|
||||
import org.keycloak.social.SocialProviderConfig;
|
||||
import org.keycloak.social.SocialProviderException;
|
||||
import org.keycloak.social.SocialUser;
|
||||
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
|
||||
|
@ -42,7 +43,13 @@ import com.google.api.services.oauth2.model.Userinfo;
|
|||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class GoogleProvider implements IdentityProvider {
|
||||
public class GoogleProvider implements SocialProvider {
|
||||
|
||||
private static final String DEFAULT_RESPONSE_TYPE = "code";
|
||||
|
||||
private static final String AUTH_PATH = "https://accounts.google.com/o/oauth2/auth";
|
||||
|
||||
private static final String DEFAULT_SCOPE = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email";
|
||||
|
||||
private static final JacksonFactory JSON_FACTORY = new JacksonFactory();
|
||||
|
||||
|
@ -54,18 +61,16 @@ public class GoogleProvider implements IdentityProvider {
|
|||
}
|
||||
|
||||
@Override
|
||||
public URI getAuthUrl(IdentityProviderCallback callback) {
|
||||
public AuthRequest getAuthUrl(SocialProviderConfig config) throws SocialProviderException {
|
||||
String state = UUID.randomUUID().toString();
|
||||
callback.putState(state, null);
|
||||
|
||||
AuthRequestBuilder b = AuthRequestBuilder.create(state, AUTH_PATH).setQueryParam("client_id", config.getKey())
|
||||
.setQueryParam("response_type", DEFAULT_RESPONSE_TYPE).setQueryParam("scope", DEFAULT_SCOPE)
|
||||
.setQueryParam("redirect_uri", config.getCallbackUrl()).setQueryParam("state", state);
|
||||
|
||||
return callback
|
||||
.createUri("https://accounts.google.com/o/oauth2/auth")
|
||||
.setQueryParam("client_id", callback.getProviderKey())
|
||||
.setQueryParam("response_type", "code")
|
||||
.setQueryParam("scope",
|
||||
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
|
||||
.setQueryParam("redirect_uri", callback.getProviderCallbackUrl().toString()).setQueryParam("state", state)
|
||||
.build();
|
||||
b.setAttribute("state", state);
|
||||
|
||||
return b.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -74,21 +79,20 @@ public class GoogleProvider implements IdentityProvider {
|
|||
}
|
||||
|
||||
@Override
|
||||
public boolean isCallbackHandler(IdentityProviderCallback callback) {
|
||||
return callback.containsQueryParam("state") && callback.containsState(callback.getQueryParam("state"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public User processCallback(IdentityProviderCallback callback) throws IdentityProviderException {
|
||||
String code = callback.getQueryParam("code");
|
||||
public SocialUser processCallback(SocialProviderConfig config, AuthCallback callback) throws SocialProviderException {
|
||||
String code = callback.getQueryParam(DEFAULT_RESPONSE_TYPE);
|
||||
|
||||
try {
|
||||
if (!callback.getQueryParam("state").equals(callback.getAttribute("state"))) {
|
||||
throw new SocialProviderException("Invalid state");
|
||||
}
|
||||
|
||||
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY,
|
||||
callback.getProviderKey(), callback.getProviderSecret(), code, callback.getProviderCallbackUrl().toString())
|
||||
config.getKey(), config.getSecret(), code, config.getCallbackUrl().toString())
|
||||
.execute();
|
||||
|
||||
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT)
|
||||
.setClientSecrets(callback.getProviderKey(), callback.getProviderSecret()).build()
|
||||
.setClientSecrets(config.getKey(), config.getSecret()).build()
|
||||
.setFromTokenResponse(tokenResponse);
|
||||
|
||||
Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build();
|
||||
|
@ -96,19 +100,25 @@ public class GoogleProvider implements IdentityProvider {
|
|||
Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
|
||||
|
||||
if (tokenInfo.containsKey("error")) {
|
||||
throw new RuntimeException("error");
|
||||
throw new SocialProviderException((String) tokenInfo.get("error"));
|
||||
}
|
||||
|
||||
Userinfo userInfo = oauth2.userinfo().get().execute();
|
||||
User user = new SimpleUser(userInfo.getEmail());
|
||||
|
||||
SocialUser user = new SocialUser(userInfo.getId());
|
||||
user.setFirstName(userInfo.getGivenName());
|
||||
user.setLastName(userInfo.getFamilyName());
|
||||
user.setEmail(userInfo.getEmail());
|
||||
|
||||
return user;
|
||||
} catch (Exception e) {
|
||||
throw new IdentityProviderException(e);
|
||||
throw new SocialProviderException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRequestIdParamName() {
|
||||
return "state";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
org.keycloak.social.google.GoogleProvider
|
|
@ -8,63 +8,15 @@
|
|||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>keycloak-social</artifactId>
|
||||
<name>Keycloak Social</name>
|
||||
<artifactId>keycloak-social-parent</artifactId>
|
||||
<name>Keycloak Social Parent</name>
|
||||
<description/>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>resteasy-jaxrs</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>jaxrs-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.picketlink</groupId>
|
||||
<artifactId>picketlink-idm-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec.javax.ejb</groupId>
|
||||
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
||||
<version>1.0.0.Alpha2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
<artifactId>google-api-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.apis</groupId>
|
||||
<artifactId>google-api-services-oauth2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.twitter4j</groupId>
|
||||
<artifactId>twitter4j-core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<modules>
|
||||
<module>core</module>
|
||||
<module>google</module>
|
||||
<module>twitter</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,113 +0,0 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
import org.keycloak.social.util.UriBuilder;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class IdentityProviderCallback {
|
||||
|
||||
private String application;
|
||||
|
||||
private HttpHeaders headers;
|
||||
|
||||
private String providerKey;
|
||||
|
||||
private String providerSecret;
|
||||
|
||||
private IdentityProviderState providerState;
|
||||
|
||||
private UriInfo uriInfo;
|
||||
|
||||
public boolean containsQueryParam(String key) {
|
||||
return uriInfo.getQueryParameters().containsKey(key);
|
||||
}
|
||||
|
||||
public boolean containsState(String key) {
|
||||
return providerState.contains(key);
|
||||
}
|
||||
|
||||
public UriBuilder createUri(String path) {
|
||||
return new UriBuilder(headers, uriInfo, path);
|
||||
}
|
||||
|
||||
public URI getProviderCallbackUrl() {
|
||||
return createUri("social/" + application + "/callback").build();
|
||||
}
|
||||
|
||||
public String getProviderKey() {
|
||||
return providerKey;
|
||||
}
|
||||
|
||||
public String getProviderSecret() {
|
||||
return providerSecret;
|
||||
}
|
||||
|
||||
public String getQueryParam(String key) {
|
||||
List<String> values = uriInfo.getQueryParameters().get(key);
|
||||
if (!values.isEmpty()) {
|
||||
return values.get(0);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public <T> T getState(String key) {
|
||||
return providerState.remove(key);
|
||||
}
|
||||
|
||||
public void putState(String key, Object value) {
|
||||
providerState.put(key, value);
|
||||
}
|
||||
|
||||
public void setApplication(String application) {
|
||||
this.application = application;
|
||||
}
|
||||
|
||||
public void setHeaders(HttpHeaders headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
public void setProviderKey(String providerKey) {
|
||||
this.providerKey = providerKey;
|
||||
}
|
||||
|
||||
public void setProviderSecret(String providerSecret) {
|
||||
this.providerSecret = providerSecret;
|
||||
}
|
||||
|
||||
public void setProviderState(IdentityProviderState providerState) {
|
||||
this.providerState = providerState;
|
||||
}
|
||||
|
||||
public void setUriInfo(UriInfo uriInfo) {
|
||||
this.uriInfo = uriInfo;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
package org.keycloak.social;
|
||||
|
||||
public class IdentityProviderErrors {
|
||||
public static final String INVALID_PROVIDER = "invalid_provider";
|
||||
public static final String PROVIDER_ERROR = "provider_error";
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
package org.keycloak.social;
|
||||
|
||||
public class IdentityProviderException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IdentityProviderException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
package org.keycloak.social.resources;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
|
||||
@ApplicationPath("social/api")
|
||||
public class SocialApplication extends Application {
|
||||
|
||||
}
|
|
@ -1,221 +0,0 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social.resources;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.imageio.spi.ServiceRegistry;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
import org.jboss.resteasy.logging.Logger;
|
||||
import org.keycloak.social.IdentityProvider;
|
||||
import org.keycloak.social.IdentityProviderCallback;
|
||||
import org.keycloak.social.IdentityProviderErrors;
|
||||
import org.keycloak.social.IdentityProviderException;
|
||||
import org.keycloak.social.IdentityProviderState;
|
||||
import org.keycloak.social.util.UriBuilder;
|
||||
import org.picketlink.idm.model.Attribute;
|
||||
import org.picketlink.idm.model.User;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
@Path("")
|
||||
public class SocialResource {
|
||||
|
||||
private static final Logger log = Logger.getLogger(SocialResource.class);
|
||||
|
||||
// TODO This is just temporary - need to either save state variables somewhere they can be flushed after a timeout, or
|
||||
// alternatively they could be saved in http session, but that is probably not a good idea
|
||||
private static final Map<String, IdentityProviderState> states = new HashMap<String, IdentityProviderState>();
|
||||
|
||||
private static synchronized IdentityProviderState getProviderState(IdentityProvider provider) {
|
||||
IdentityProviderState s = states.get(provider.getId());
|
||||
if (s == null) {
|
||||
s = new IdentityProviderState();
|
||||
states.put(provider.getId(), s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@Context
|
||||
private HttpHeaders headers;
|
||||
|
||||
@Context
|
||||
private UriInfo uriInfo;
|
||||
|
||||
@GET
|
||||
@Path("{application}/callback")
|
||||
public Response callback(@PathParam("application") String application) throws URISyntaxException {
|
||||
String realm = null; // TODO Get realm for application
|
||||
|
||||
IdentityProviderCallback callback = new IdentityProviderCallback();
|
||||
callback.setApplication(application);
|
||||
callback.setHeaders(headers);
|
||||
callback.setUriInfo(uriInfo);
|
||||
|
||||
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
|
||||
|
||||
for (IdentityProvider provider = itr.next(); itr.hasNext();) {
|
||||
callback.setProviderState(getProviderState(provider));
|
||||
|
||||
if (provider.isCallbackHandler(callback)) {
|
||||
User user = null;
|
||||
try {
|
||||
user = provider.processCallback(callback);
|
||||
} catch (IdentityProviderException e) {
|
||||
log.warn("Failed to process callback", e);
|
||||
redirectToLogin(application, IdentityProviderErrors.PROVIDER_ERROR);
|
||||
}
|
||||
|
||||
String providerUsername = user.getLoginName();
|
||||
String providerUsernameKey = provider.getId() + ".username";
|
||||
|
||||
user.setAttribute(new Attribute<String>(providerUsernameKey, user.getLoginName()));
|
||||
|
||||
User existingUser = getUser(realm, user.getLoginName());
|
||||
|
||||
if (existingUser != null) {
|
||||
user = mergeUser(user, existingUser);
|
||||
|
||||
updateUser(realm, user);
|
||||
} else {
|
||||
if (user.getEmail() != null && getUser(realm, user.getEmail()) == null) {
|
||||
user.setLoginName(user.getEmail());
|
||||
} else if (getUser(realm, user.getLoginName()) != null) {
|
||||
for (int i = 0;; i++) {
|
||||
if (getUser(realm, providerUsername + i) == null) {
|
||||
user.setLoginName(providerUsername + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createUser(realm, user);
|
||||
}
|
||||
|
||||
// TODO Get bearer token etc and redirect to application callback url
|
||||
URI uri = null;
|
||||
return Response.seeOther(uri).build();
|
||||
}
|
||||
}
|
||||
|
||||
return redirectToLogin(application, "login_failed");
|
||||
}
|
||||
|
||||
private void createUser(String realm, User user) {
|
||||
// TODO Save user in IDM
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("providers")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public List<IdentityProvider> getProviders() {
|
||||
List<IdentityProvider> providers = new LinkedList<IdentityProvider>();
|
||||
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
|
||||
while (itr.hasNext()) {
|
||||
providers.add(itr.next());
|
||||
}
|
||||
return providers;
|
||||
}
|
||||
|
||||
private User getUser(String realm, String username) {
|
||||
// TODO Get user from IDM
|
||||
return null;
|
||||
}
|
||||
|
||||
private User mergeUser(User source, User destination) {
|
||||
if (source.getEmail() != null) {
|
||||
destination.setEmail(source.getEmail());
|
||||
}
|
||||
|
||||
if (source.getFirstName() != null) {
|
||||
destination.setFirstName(source.getFirstName());
|
||||
}
|
||||
|
||||
if (source.getLastName() != null) {
|
||||
destination.setLastName(source.getLastName());
|
||||
}
|
||||
|
||||
for (Attribute<? extends Serializable> attribute : source.getAttributes()) {
|
||||
destination.setAttribute(attribute);
|
||||
}
|
||||
|
||||
return destination;
|
||||
}
|
||||
|
||||
private Response redirectToLogin(String application, String error) {
|
||||
URI uri = new UriBuilder(headers, uriInfo, "sdk/api/" + application + "/login").setQueryParam("error", error).build();
|
||||
return Response.seeOther(uri).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("{application}/auth/{provider}")
|
||||
public Response redirectToProviderAuth(@PathParam("application") String application,
|
||||
@PathParam("provider") String providerId) {
|
||||
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
|
||||
|
||||
IdentityProvider provider;
|
||||
for (provider = itr.next(); itr.hasNext() && !provider.getId().equals(providerId);) {
|
||||
}
|
||||
|
||||
if (provider == null) {
|
||||
log.warn("Failed to redirect to provider auth: " + providerId + " not found");
|
||||
return redirectToLogin(application, IdentityProviderErrors.INVALID_PROVIDER);
|
||||
}
|
||||
|
||||
IdentityProviderCallback callback = new IdentityProviderCallback();
|
||||
callback.setApplication(application);
|
||||
callback.setHeaders(headers);
|
||||
callback.setUriInfo(uriInfo);
|
||||
callback.setProviderKey(null); // TODO Get provider key
|
||||
callback.setProviderSecret(null); // TODO Get provider secret
|
||||
callback.setProviderState(getProviderState(provider));
|
||||
|
||||
try {
|
||||
return Response.seeOther(provider.getAuthUrl(callback)).build();
|
||||
} catch (Throwable t) {
|
||||
log.warn("Failed to redirect to provider auth", t);
|
||||
return redirectToLogin(application, IdentityProviderErrors.PROVIDER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateUser(String realm, User user) {
|
||||
// TODO Update user in IDM
|
||||
}
|
||||
|
||||
}
|
|
@ -1,85 +0,0 @@
|
|||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright 2012, Red Hat, Inc., and individual contributors
|
||||
* as indicated by the @author tags. See the copyright.txt file in the
|
||||
* distribution for a full listing of individual contributors.
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation; either version 2.1 of
|
||||
* the License, or (at your option) any later version.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this software; if not, write to the Free
|
||||
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
|
||||
*/
|
||||
package org.keycloak.social.util;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class UriBuilder {
|
||||
|
||||
private final javax.ws.rs.core.UriBuilder b;
|
||||
|
||||
private String fragment;
|
||||
|
||||
public UriBuilder(HttpHeaders headers, UriInfo uriInfo, String path) {
|
||||
if (path.contains("#")) {
|
||||
String t = path;
|
||||
path = t.substring(0, t.indexOf('#'));
|
||||
fragment = t.substring(t.indexOf('#'));
|
||||
}
|
||||
|
||||
if (path.contains("://")) {
|
||||
b = javax.ws.rs.core.UriBuilder.fromUri(path);
|
||||
} else {
|
||||
URI absolutePath = uriInfo.getAbsolutePath();
|
||||
|
||||
if (headers.getRequestHeaders().containsKey("x-forwarded-proto")) {
|
||||
String scheme = headers.getRequestHeaders().get("x-forwarded-proto").get(0);
|
||||
try {
|
||||
absolutePath = new URI(absolutePath.toString().replaceFirst(".*://", scheme + "://"));
|
||||
} catch (URISyntaxException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (path.startsWith("/")) {
|
||||
b = javax.ws.rs.core.UriBuilder.fromUri(absolutePath.resolve(path));
|
||||
} else {
|
||||
URI uri = absolutePath;
|
||||
String p = uri.getPath();
|
||||
p = p.substring(0, p.indexOf('/', 1) + 1);
|
||||
uri = uri.resolve(p + path);
|
||||
b = javax.ws.rs.core.UriBuilder.fromUri(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public URI build() {
|
||||
URI uri = b.build();
|
||||
if (fragment != null) {
|
||||
uri = uri.resolve(fragment);
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
public UriBuilder setQueryParam(String name, String value) {
|
||||
b.replaceQueryParam(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
org.keycloak.social.google.GoogleProvider
|
||||
org.keycloak.social.twitter.TwitterProvider
|
29
social/twitter/pom.xml
Executable file
29
social/twitter/pom.xml
Executable file
|
@ -0,0 +1,29 @@
|
|||
<?xml version="1.0"?>
|
||||
<project>
|
||||
<parent>
|
||||
<artifactId>keycloak-social-parent</artifactId>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<version>1.0-alpha-1</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>keycloak-social-twitter</artifactId>
|
||||
<name>Keycloak Social Twitter</name>
|
||||
<description/>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-social-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.twitter4j</groupId>
|
||||
<artifactId>twitter4j-core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -21,13 +21,13 @@
|
|||
*/
|
||||
package org.keycloak.social.twitter;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.keycloak.social.IdentityProvider;
|
||||
import org.keycloak.social.IdentityProviderCallback;
|
||||
import org.keycloak.social.IdentityProviderException;
|
||||
import org.picketlink.idm.model.SimpleUser;
|
||||
import org.picketlink.idm.model.User;
|
||||
import org.keycloak.social.AuthCallback;
|
||||
import org.keycloak.social.AuthRequest;
|
||||
import org.keycloak.social.AuthRequestBuilder;
|
||||
import org.keycloak.social.SocialProvider;
|
||||
import org.keycloak.social.SocialProviderConfig;
|
||||
import org.keycloak.social.SocialProviderException;
|
||||
import org.keycloak.social.SocialUser;
|
||||
|
||||
import twitter4j.Twitter;
|
||||
import twitter4j.TwitterFactory;
|
||||
|
@ -36,7 +36,7 @@ import twitter4j.auth.RequestToken;
|
|||
/**
|
||||
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
|
||||
*/
|
||||
public class TwitterProvider implements IdentityProvider {
|
||||
public class TwitterProvider implements SocialProvider {
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
|
@ -44,16 +44,18 @@ public class TwitterProvider implements IdentityProvider {
|
|||
}
|
||||
|
||||
@Override
|
||||
public URI getAuthUrl(IdentityProviderCallback callback) throws IdentityProviderException {
|
||||
public AuthRequest getAuthUrl(SocialProviderConfig request) throws SocialProviderException {
|
||||
try {
|
||||
Twitter twitter = new TwitterFactory().getInstance();
|
||||
twitter.setOAuthConsumer(callback.getProviderKey(), callback.getProviderSecret());
|
||||
twitter.setOAuthConsumer(request.getKey(), request.getSecret());
|
||||
|
||||
RequestToken requestToken = twitter.getOAuthRequestToken();
|
||||
callback.putState(requestToken.getToken(), requestToken);
|
||||
return callback.createUri(requestToken.getAuthenticationURL()).build();
|
||||
|
||||
return AuthRequestBuilder.create(requestToken.getToken(), requestToken.getAuthenticationURL())
|
||||
.setAttribute("token", requestToken.getToken()).setAttribute("tokenSecret", requestToken.getTokenSecret())
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
throw new IdentityProviderException(e);
|
||||
throw new SocialProviderException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -63,28 +65,29 @@ public class TwitterProvider implements IdentityProvider {
|
|||
}
|
||||
|
||||
@Override
|
||||
public boolean isCallbackHandler(IdentityProviderCallback callback) {
|
||||
return callback.containsQueryParam("oauth_token") && callback.containsState(callback.getQueryParam("oauth_token"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public User processCallback(IdentityProviderCallback callback) throws IdentityProviderException {
|
||||
public SocialUser processCallback(SocialProviderConfig config, AuthCallback callback) throws SocialProviderException {
|
||||
try {
|
||||
Twitter twitter = new TwitterFactory().getInstance();
|
||||
twitter.setOAuthConsumer(callback.getProviderKey(), callback.getProviderSecret());
|
||||
twitter.setOAuthConsumer(config.getKey(), config.getSecret());
|
||||
|
||||
String verifier = callback.getQueryParam("oauth_verifier");
|
||||
RequestToken requestToken = callback.getState(callback.getQueryParam("oauth_token"));
|
||||
RequestToken requestToken = new RequestToken(callback.getAttribute("token"), callback.getAttribute("tokenSecret"));
|
||||
|
||||
twitter.getOAuthAccessToken(requestToken, verifier);
|
||||
twitter4j.User twitterUser = twitter.verifyCredentials();
|
||||
|
||||
User user = new SimpleUser(String.valueOf(twitterUser.getScreenName()));
|
||||
SocialUser user = new SocialUser(Long.toString(twitterUser.getId()));
|
||||
user.setFirstName(twitterUser.getName());
|
||||
|
||||
return user;
|
||||
} catch (Exception e) {
|
||||
throw new IdentityProviderException(e);
|
||||
throw new SocialProviderException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRequestIdParamName() {
|
||||
return "oauth_token";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
org.keycloak.social.twitter.TwitterProvider
|
Loading…
Reference in a new issue