diff --git a/sdk-html/src/main/resources/META-INF/web-fragment.xml b/forms/src/main/resources/META-INF/web-fragment.xml
similarity index 100%
rename from sdk-html/src/main/resources/META-INF/web-fragment.xml
rename to forms/src/main/resources/META-INF/web-fragment.xml
diff --git a/forms/src/main/resources/org/keycloak/forms/messages.properties b/forms/src/main/resources/org/keycloak/forms/messages.properties
new file mode 100644
index 0000000000..842091c14a
--- /dev/null
+++ b/forms/src/main/resources/org/keycloak/forms/messages.properties
@@ -0,0 +1,32 @@
+logIn=Log in
+logInTo=Log in to
+logInWith=Log in with
+noAccount=No account?
+register=Register
+registerWith=Register with
+allRequired=All fields are required
+alreadyHaveAccount=Already have an account?
+
+poweredByKeycloak=Powered by Keycloak
+
+username=Username
+fullName=Full name
+email=Email
+password=Password
+passwordConfirm=Password confirmation
+
+authenticatorCode=Authenticator Code
+clientCertificate=Client Certificate
+
+invalidUser=Invalid username or password
+invalidPassword=Invalid username or password
+accountDisabled=Account is disabled, contact admin
+
+missingName=Please specify full name
+missingEmail=Please specify email
+missingUsername=Please specify username
+missingPassword=Please specify password
+
+invalidPasswordConfirm=Password confirmation doesn't match
+
+usernameExists=Username already exists
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index b55e06dcb0..b0e3b2205a 100755
--- a/pom.xml
+++ b/pom.xml
@@ -58,7 +58,7 @@
integration
examples
social
-
sdk-html
+
forms
diff --git a/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/login.xhtml b/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/login.xhtml
deleted file mode 100755
index 93c73469f6..0000000000
--- a/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/login.xhtml
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
- Log in to #{login.name}
-
-
-
-
-
-
-
- No account? Register.
-
-
-
\ No newline at end of file
diff --git a/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/register.xhtml b/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/register.xhtml
deleted file mode 100755
index ad68348afa..0000000000
--- a/sdk-html/src/main/resources/META-INF/resources/sdk/theme/default/register.xhtml
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
-
-
- Register with #{login.name}
-
-
-
-
-
-
- Already have an account? Log in.
-
-
\ No newline at end of file
diff --git a/services/src/main/java/org/keycloak/services/managers/RealmManager.java b/services/src/main/java/org/keycloak/services/managers/RealmManager.java
index 7c149f6525..029eb8b6dd 100755
--- a/services/src/main/java/org/keycloak/services/managers/RealmManager.java
+++ b/services/src/main/java/org/keycloak/services/managers/RealmManager.java
@@ -103,6 +103,7 @@ public class RealmManager {
newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
newRealm.setSslNotRequired(rep.isSslNotRequired());
newRealm.setCookieLoginAllowed(rep.isCookieLoginAllowed());
+ newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.getPrivateKey() == null || rep.getPublicKey() == null) {
generateRealmKeys(newRealm);
} else {
diff --git a/services/src/main/java/org/keycloak/services/messages/Messages.java b/services/src/main/java/org/keycloak/services/messages/Messages.java
new file mode 100644
index 0000000000..0441cc2a1a
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/messages/Messages.java
@@ -0,0 +1,47 @@
+/*
+ * 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.messages;
+
+/**
+ * @author
Stian Thorgersen
+ */
+public class Messages {
+
+ public static final String ACCOUNT_DISABLED = "accountDisabled";
+
+ public static final String INVALID_PASSWORD = "invalidPassword";
+
+ public static final String INVALID_PASSWORD_CONFIRM = "invalidPasswordConfirm";
+
+ public static final String INVALID_USER = "invalidUser";
+
+ public static final String MISSING_EMAIL = "missingEmail";
+
+ public static final String MISSING_NAME = "missingName";
+
+ public static final String MISSING_PASSWORD = "missingPassword";
+
+ public static final String MISSING_USERNAME = "missingUsername";
+
+ public static final String USERNAME_EXISTS = "usernameExists";
+
+}
diff --git a/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java b/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
index a72bcbad3a..de99a7c18b 100755
--- a/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
+++ b/services/src/main/java/org/keycloak/services/models/RequiredCredentialModel.java
@@ -62,19 +62,19 @@ public class RequiredCredentialModel {
PASSWORD.setType(CredentialRepresentation.PASSWORD);
PASSWORD.setInput(true);
PASSWORD.setSecret(true);
- PASSWORD.setFormLabel("Password");
+ PASSWORD.setFormLabel("password");
map.put(PASSWORD.getType(), PASSWORD);
TOTP = new RequiredCredentialModel();
TOTP.setType(CredentialRepresentation.TOTP);
TOTP.setInput(true);
TOTP.setSecret(false);
- TOTP.setFormLabel("Authenticator Code");
+ TOTP.setFormLabel("authenticatorCode");
map.put(TOTP.getType(), TOTP);
CLIENT_CERT = new RequiredCredentialModel();
CLIENT_CERT.setType(CredentialRepresentation.CLIENT_CERT);
CLIENT_CERT.setInput(false);
CLIENT_CERT.setSecret(false);
- CLIENT_CERT.setFormLabel("Client Certificate");
+ CLIENT_CERT.setFormLabel("clientCertificate");
map.put(CLIENT_CERT.getType(), CLIENT_CERT);
BUILT_IN = Collections.unmodifiableMap(map);
}
diff --git a/services/src/main/java/org/keycloak/services/resources/AbstractLoginService.java b/services/src/main/java/org/keycloak/services/resources/AbstractLoginService.java
deleted file mode 100755
index 6535acf4f7..0000000000
--- a/services/src/main/java/org/keycloak/services/resources/AbstractLoginService.java
+++ /dev/null
@@ -1,112 +0,0 @@
-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.AuthenticationManager;
-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;
-
-import java.net.URI;
-
-public abstract class AbstractLoginService {
-
- @Context
- protected UriInfo uriInfo;
- @Context
- protected HttpHeaders headers;
- @Context
- HttpRequest request;
- @Context
- HttpResponse response;
-
- public final static String securityFailurePath = "/saas/securityFailure.jsp";
- public final static String loginFormPath = "/sdk/login.xhtml";
- public final static String oauthFormPath = "/saas/oauthGrantForm.jsp";
-
- protected RealmModel realm;
- protected TokenManager tokenManager;
- protected AuthenticationManager authManager = new AuthenticationManager();
-
- 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(authManager.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()));
- request.setAttribute("KEYCLOAK_REGISTRATION_PAGE", URI.create("not-implemented-yet"));
-
- // 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();
-}
diff --git a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
index 980487c0cf..cd464248f7 100755
--- a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
+++ b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
@@ -49,7 +49,11 @@ public class KeycloakApplication extends Application {
KeycloakSessionFactory f = createSessionFactory();
this.factory = f;
classes.add(KeycloakSessionCleanupFilter.class);
- singletons.add(new RealmsResource(new TokenManager(), new SocialRequestManager()));
+
+ TokenManager tokenManager = new TokenManager();
+
+ singletons.add(new RealmsResource(tokenManager));
+ singletons.add(new SocialResource(tokenManager, new SocialRequestManager()));
classes.add(SkeletonKeyContextResolver.class);
classes.add(SaasService.class);
}
diff --git a/services/src/main/java/org/keycloak/services/resources/PublicRealmResource.java b/services/src/main/java/org/keycloak/services/resources/PublicRealmResource.java
index ab12f38295..7085eab839 100755
--- a/services/src/main/java/org/keycloak/services/resources/PublicRealmResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/PublicRealmResource.java
@@ -41,7 +41,7 @@ public class PublicRealmResource {
@NoCache
@Produces("application/json")
public PublishedRealmRepresentation getRealm(@PathParam("realm") String id) {
- return new Transaction() {
+ return new Transaction
() {
protected PublishedRealmRepresentation callImpl() {
return realmRep(realm, uriInfo);
}
@@ -53,7 +53,7 @@ public class PublicRealmResource {
@Path("html")
@Produces("text/html")
public String getRealmHtml(@PathParam("realm") String id) {
- return new Transaction() {
+ return new Transaction() {
protected String callImpl() {
StringBuffer html = new StringBuffer();
diff --git a/services/src/main/java/org/keycloak/services/resources/RealmsResource.java b/services/src/main/java/org/keycloak/services/resources/RealmsResource.java
index 437502595a..3a4fa57609 100755
--- a/services/src/main/java/org/keycloak/services/resources/RealmsResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/RealmsResource.java
@@ -43,11 +43,8 @@ public class RealmsResource {
protected TokenManager tokenManager;
- protected SocialRequestManager socialRequestManager;
-
- public RealmsResource(TokenManager tokenManager, SocialRequestManager socialRequestManager) {
+ public RealmsResource(TokenManager tokenManager) {
this.tokenManager = tokenManager;
- this.socialRequestManager = socialRequestManager;
}
public static UriBuilder realmBaseUrl(UriInfo uriInfo) {
@@ -56,7 +53,7 @@ public class RealmsResource {
@Path("{realm}/tokens")
public TokenService getTokenService(final @PathParam("realm") String id) {
- return new Transaction(false) {
+ return new Transaction(false) {
@Override
protected TokenService callImpl() {
RealmManager realmManager = new RealmManager(session);
@@ -73,27 +70,9 @@ 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 PublicRealmResource getRealmResource(final @PathParam("realm") String id) {
- return new Transaction(false) {
+ return new Transaction(false) {
@Override
protected PublicRealmResource callImpl() {
RealmManager realmManager = new RealmManager(session);
diff --git a/services/src/main/java/org/keycloak/services/resources/SaasService.java b/services/src/main/java/org/keycloak/services/resources/SaasService.java
index 3665c53b20..e969d7e05d 100755
--- a/services/src/main/java/org/keycloak/services/resources/SaasService.java
+++ b/services/src/main/java/org/keycloak/services/resources/SaasService.java
@@ -9,14 +9,17 @@ import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.RealmManager;
+import org.keycloak.services.messages.Messages;
import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RoleModel;
import org.keycloak.services.models.UserCredentialModel;
import org.keycloak.services.models.UserModel;
import org.keycloak.services.resources.admin.RealmsAdminResource;
+import org.keycloak.services.resources.flows.Flows;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
+
import java.net.URI;
import java.util.StringTokenizer;
@@ -39,8 +42,6 @@ public class SaasService {
@Context
HttpResponse response;
- protected String saasLoginPath = "/saas/saas-login.jsp";
- protected String saasRegisterPath = "/saas/saas-register.jsp";
protected String adminPath = "/saas/admin/index.html";
protected AuthenticationManager authManager = new AuthenticationManager();
@@ -78,12 +79,13 @@ public class SaasService {
@NoCache
public Response keepalive(final @Context HttpHeaders headers) {
logger.info("keepalive");
- return new Transaction() {
+ return new Transaction() {
@Override
public Response callImpl() {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.defaultRealm();
- if (realm == null) throw new NotFoundException();
+ if (realm == null)
+ throw new NotFoundException();
UserModel user = authManager.authenticateSaasIdentityCookie(realm, uriInfo, headers);
if (user == null) {
return Response.status(401).build();
@@ -99,12 +101,13 @@ public class SaasService {
@Produces("application/json")
@NoCache
public Response whoAmI(final @Context HttpHeaders headers) {
- return new Transaction() {
+ return new Transaction() {
@Override
public Response callImpl() {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.defaultRealm();
- if (realm == null) throw new NotFoundException();
+ if (realm == null)
+ throw new NotFoundException();
UserModel user = authManager.authenticateSaasIdentityCookie(realm, uriInfo, headers);
if (user == null) {
return Response.status(401).build();
@@ -119,7 +122,7 @@ public class SaasService {
@Produces("application/javascript")
@NoCache
public String isLoggedIn(final @Context HttpHeaders headers) {
- return new Transaction() {
+ return new Transaction() {
@Override
public String callImpl() {
logger.info("WHOAMI Javascript start.");
@@ -139,7 +142,6 @@ public class SaasService {
}.call();
}
-
public static UriBuilder contextRoot(UriInfo uriInfo) {
return UriBuilder.fromUri(uriInfo.getBaseUri()).replacePath("/auth-server");
}
@@ -150,12 +152,13 @@ public class SaasService {
@Path("admin/realms")
public RealmsAdminResource getRealmsAdmin(@Context final HttpHeaders headers) {
- return new Transaction(false) {
+ return new Transaction(false) {
@Override
protected RealmsAdminResource callImpl() {
RealmManager realmManager = new RealmManager(session);
RealmModel saasRealm = realmManager.defaultRealm();
- if (saasRealm == null) throw new NotFoundException();
+ if (saasRealm == null)
+ throw new NotFoundException();
UserModel admin = authManager.authenticateSaasIdentity(saasRealm, uriInfo, headers);
if (admin == null) {
throw new NotAuthorizedException("Bearer");
@@ -170,7 +173,7 @@ public class SaasService {
}.call();
}
- @Path("loginPage.html")
+ @Path("login")
@GET
@NoCache
public void loginPage() {
@@ -180,7 +183,24 @@ public class SaasService {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.defaultRealm();
authManager.expireSaasIdentityCookie(uriInfo);
- forwardToLoginForm(realm);
+
+ Flows.forms(realm, request).forwardToLogin();
+ }
+ }.run();
+ }
+
+ @Path("registrations")
+ @GET
+ @NoCache
+ public void registerPage() {
+ new Transaction() {
+ @Override
+ protected void runImpl() {
+ RealmManager realmManager = new RealmManager(session);
+ RealmModel realm = realmManager.defaultRealm();
+ authManager.expireSaasIdentityCookie(uriInfo);
+
+ Flows.forms(realm, request).forwardToRegistration();
}
}.run();
}
@@ -195,12 +215,12 @@ public class SaasService {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.defaultRealm();
authManager.expireSaasIdentityCookie(uriInfo);
- forwardToLoginForm(realm);
+
+ Flows.forms(realm, request).forwardToLogin();
}
}.run();
}
-
@Path("logout-cookie")
@GET
@NoCache
@@ -214,30 +234,18 @@ public class SaasService {
}.run();
}
- public final static String loginFormPath = "/sdk/login.xhtml";
-
- protected void forwardToLoginForm(RealmModel realm) {
- request.setAttribute(RealmModel.class.getName(), realm);
- URI action = uriInfo.getBaseUriBuilder().path(SaasService.class).path(SaasService.class, "processLogin").build();
- URI register = contextRoot(uriInfo).path(saasRegisterPath).build();
- request.setAttribute("KEYCLOAK_LOGIN_ACTION", action);
- request.setAttribute("KEYCLOAK_REGISTRATION_PAGE", register);
- request.setAttribute("KEYCLOAK_SOCIAL_LOGIN", SocialService.redirectToProviderAuthUrl(uriInfo).build(realm.getId()));
- request.forward(loginFormPath);
- }
-
-
@Path("login")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processLogin(final MultivaluedMap formData) {
logger.info("processLogin start");
- return new Transaction() {
+ return new Transaction() {
@Override
protected Response callImpl() {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.defaultRealm();
- if (realm == null) throw new NotFoundException();
+ if (realm == null)
+ throw new NotFoundException();
if (!realm.isEnabled()) {
throw new NotImplementedYetException();
@@ -246,29 +254,27 @@ public class SaasService {
UserModel user = realm.getUser(username);
if (user == null) {
logger.info("Not Authenticated! Incorrect user name");
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Incorrect user name.");
- forwardToLoginForm(realm);
- return null;
+
+ return Flows.forms(realm, request).setError(Messages.INVALID_USER).setFormData(formData)
+ .forwardToLogin();
}
if (!user.isEnabled()) {
- logger.info("NAccount is disabled, contact admin.");
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Account is disabled, contact admin.");
- forwardToLoginForm(realm);
- return null;
+ logger.info("Account is disabled, contact admin.");
+
+ return Flows.forms(realm, request).setError(Messages.ACCOUNT_DISABLED)
+ .setFormData(formData).forwardToLogin();
}
boolean authenticated = authManager.authenticateForm(realm, user, formData);
if (!authenticated) {
logger.info("Not Authenticated! Invalid credentials");
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Invalid credentials.");
- forwardToLoginForm(realm);
- return null;
+
+ return Flows.forms(realm, request).setError(Messages.INVALID_PASSWORD).setFormData(formData)
+ .forwardToLogin();
}
NewCookie cookie = authManager.createSaasIdentityCookie(realm, user, uriInfo);
- return Response.status(302)
- .cookie(cookie)
- .location(contextRoot(uriInfo).path(adminPath).build()).build();
+ return Response.status(302).cookie(cookie).location(contextRoot(uriInfo).path(adminPath).build()).build();
}
}.call();
}
@@ -277,7 +283,7 @@ public class SaasService {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response register(final UserRepresentation newUser) {
- return new Transaction() {
+ return new Transaction() {
@Override
protected Response callImpl() {
RealmManager realmManager = new RealmManager(session);
@@ -295,24 +301,24 @@ public class SaasService {
@Path("registrations")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public Response processRegister(final @FormParam("name") String fullname,
- final @FormParam("email") String email,
- final @FormParam("username") String username,
- final @FormParam("password") String password,
- final @FormParam("password-confirm") String confirm) {
- if (!password.equals(confirm)) {
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Password confirmation doesn't match.");
- request.forward(saasRegisterPath);
- return null;
- }
- return new Transaction() {
+ public Response processRegister(final MultivaluedMap formData) {
+ return new Transaction() {
@Override
protected Response callImpl() {
RealmManager realmManager = new RealmManager(session);
RealmModel defaultRealm = realmManager.defaultRealm();
+
+ String error = validateRegistrationForm(formData);
+ if (error != null) {
+ return Flows.forms(defaultRealm, request).setError(error).setFormData(formData)
+ .forwardToRegistration();
+ }
+
UserRepresentation newUser = new UserRepresentation();
- newUser.setUsername(username);
- newUser.setEmail(email);
+ newUser.setUsername(formData.getFirst("username"));
+ newUser.setEmail(formData.getFirst("email"));
+
+ String fullname = formData.getFirst("name");
if (fullname != null) {
StringTokenizer tokenizer = new StringTokenizer(fullname, " ");
StringBuffer first = null;
@@ -330,16 +336,16 @@ public class SaasService {
last = token;
}
}
- if (first == null) first = new StringBuffer();
+ if (first == null)
+ first = new StringBuffer();
newUser.setFirstName(first.toString());
newUser.setLastName(last);
}
- newUser.credential(CredentialRepresentation.PASSWORD, password);
+ newUser.credential(CredentialRepresentation.PASSWORD, formData.getFirst("password"));
UserModel user = registerMe(defaultRealm, newUser);
if (user == null) {
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Username already exists.");
- request.forward(saasRegisterPath);
- return null;
+ return Flows.forms(defaultRealm, request).setError(Messages.USERNAME_EXISTS)
+ .setFormData(formData).forwardToRegistration();
}
NewCookie cookie = authManager.createSaasIdentityCookie(defaultRealm, user, uriInfo);
@@ -348,7 +354,6 @@ public class SaasService {
}.call();
}
-
protected UserModel registerMe(RealmModel defaultRealm, UserRepresentation newUser) {
if (!defaultRealm.isEnabled()) {
throw new ForbiddenException();
@@ -376,5 +381,32 @@ public class SaasService {
return user;
}
+ private String validateRegistrationForm(MultivaluedMap formData) {
+ if (isEmpty(formData.getFirst("name"))) {
+ return Messages.MISSING_NAME;
+ }
+
+ if (isEmpty(formData.getFirst("email"))) {
+ return Messages.MISSING_EMAIL;
+ }
+
+ if (isEmpty(formData.getFirst("username"))) {
+ return Messages.MISSING_USERNAME;
+ }
+
+ if (isEmpty(formData.getFirst("password"))) {
+ return Messages.MISSING_PASSWORD;
+ }
+
+ if (!formData.getFirst("password").equals(formData.getFirst("password-confirm"))) {
+ return Messages.INVALID_PASSWORD_CONFIRM;
+ }
+
+ return null;
+ }
+
+ private boolean isEmpty(String s) {
+ return s == null || s.length() == 0;
+ }
}
diff --git a/services/src/main/java/org/keycloak/services/resources/SocialService.java b/services/src/main/java/org/keycloak/services/resources/SocialResource.java
similarity index 59%
rename from services/src/main/java/org/keycloak/services/resources/SocialService.java
rename to services/src/main/java/org/keycloak/services/resources/SocialResource.java
index d497f8ebaf..35d625a57e 100644
--- a/services/src/main/java/org/keycloak/services/resources/SocialService.java
+++ b/services/src/main/java/org/keycloak/services/resources/SocialResource.java
@@ -24,7 +24,6 @@ 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;
@@ -32,20 +31,25 @@ 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.PathParam;
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.jboss.resteasy.spi.HttpRequest;
+import org.keycloak.services.managers.AuthenticationManager;
+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;
+import org.keycloak.services.resources.flows.Flows;
+import org.keycloak.services.resources.flows.OAuthFlows;
+import org.keycloak.services.resources.flows.Urls;
import org.keycloak.social.AuthCallback;
import org.keycloak.social.AuthRequest;
import org.keycloak.social.RequestDetails;
@@ -59,52 +63,69 @@ import org.keycloak.social.SocialUser;
/**
* @author Stian Thorgersen
*/
-public class SocialService extends AbstractLoginService {
+@Path("/social")
+public class SocialResource {
- private static final Logger logger = Logger.getLogger(SocialService.class);
+ protected static Logger logger = Logger.getLogger(SocialResource.class);
@Context
- private HttpHeaders headers;
+ protected UriInfo uriInfo;
@Context
- private UriInfo uriInfo;
+ protected HttpHeaders headers;
- 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");
-
- }
+ @Context
+ private HttpRequest request;
private SocialRequestManager socialRequestManager;
- public SocialService(RealmModel realm, TokenManager tokenManager, SocialRequestManager socialRequestManager) {
- super(realm, tokenManager);
+ private TokenManager tokenManager;
+
+ private AuthenticationManager authManager = new AuthenticationManager();
+
+ public SocialResource(TokenManager tokenManager, SocialRequestManager socialRequestManager) {
+ this.tokenManager = tokenManager;
this.socialRequestManager = socialRequestManager;
}
@GET
@Path("callback")
public Response callback() throws URISyntaxException {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
Map queryParams = getQueryParams();
RequestDetails requestData = getRequestDetails(queryParams);
SocialProvider provider = getProvider(requestData.getProviderId());
+ String realmId = requestData.getClientAttribute("realmId");
+
+ RealmManager realmManager = new RealmManager(session);
+ RealmModel realm = realmManager.getRealm(realmId);
+
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
+
+ if (!realm.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Realm not enabled.");
+ }
+
+ if (!realm.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Realm not enabled.");
+ }
+
+ String clientId = requestData.getClientAttributes().get("clientId");
+
+ UserModel client = realm.getUser(clientId);
+ if (client == null) {
+ return oauth.forwardToSecurityFailure("Unknown login requester.");
+ }
+ if (!client.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Login requester not enabled.");
+ }
+
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();
-
+ String callbackUri = Urls.socialCallback(uriInfo.getBaseUri()).toString();
SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);
AuthCallback callback = new AuthCallback(requestData.getSocialAttributes(), queryParams);
@@ -114,25 +135,7 @@ public class SocialService extends AbstractLoginService {
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;
+ return oauth.forwardToSecurityFailure("Failed to process social callback");
}
// TODO Lookup user based on attribute for provider id - this is so a user can have a friendly username + link a
@@ -145,72 +148,55 @@ public class SocialService extends AbstractLoginService {
user.setAttribute(provider.getId() + ".id", socialUser.getId());
// TODO Grant default roles for realm when available
- realm.grantRole(user, realm.getRole("user"));
+ RoleModel defaultRole = realm.getRole("user");
+
+ realm.grantRole(user, defaultRole);
}
if (!user.isEnabled()) {
- securityFailureForward("Your account is not enabled.");
- return null;
+ return oauth.forwardToSecurityFailure("Your account is not enabled.");
}
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);
+ return oauth.processAccessCode(scope, state, redirectUri, client, user);
}
}.call();
}
@GET
- @Path("providers")
- @Produces(MediaType.APPLICATION_JSON)
- public List getProviders() {
- List providers = new LinkedList();
- Iterator itr = ServiceRegistry.lookupProviders(SocialProvider.class);
- while (itr.hasNext()) {
- providers.add(itr.next());
+ @Path("{realm}/login")
+ public Response redirectToProviderAuth(@PathParam("realm") final String realmId,
+ @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) {
+ SocialProvider provider = getProvider(providerId);
+ if (provider == null) {
+ return Flows.pages(request).forwardToSecurityFailure("Social provider not found");
}
- 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 = Urls.socialCallback(uriInfo.getBaseUri()).toString();
- 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);
- SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);
+ try {
+ AuthRequest authRequest = provider.getAuthUrl(config);
- try {
- AuthRequest authRequest = provider.getAuthUrl(config);
+ RequestDetails socialRequest = RequestDetailsBuilder.create(providerId)
+ .putSocialAttributes(authRequest.getAttributes()).putClientAttribute("realmId", realmId)
+ .putClientAttribute("clientId", clientId).putClientAttribute("scope", scope)
+ .putClientAttribute("state", state).putClientAttribute("redirectUri", redirectUri).build();
- 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);
- 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();
+ return Response.status(Status.FOUND).location(authRequest.getAuthUri()).build();
+ } catch (Throwable t) {
+ return Flows.pages(request).forwardToSecurityFailure("Failed to redirect to social auth");
+ }
}
private RequestDetails getRequestDetails(Map queryParams) {
@@ -251,9 +237,4 @@ public class SocialService extends AbstractLoginService {
return queryParams;
}
- @Override
- protected Logger getLogger() {
- return logger;
- }
-
}
diff --git a/services/src/main/java/org/keycloak/services/resources/TokenService.java b/services/src/main/java/org/keycloak/services/resources/TokenService.java
index 4f295fefca..7488fe1685 100755
--- a/services/src/main/java/org/keycloak/services/resources/TokenService.java
+++ b/services/src/main/java/org/keycloak/services/resources/TokenService.java
@@ -6,18 +6,27 @@ 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.representations.idm.CredentialRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
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.messages.Messages;
import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RoleModel;
+import org.keycloak.services.models.UserCredentialModel;
import org.keycloak.services.models.UserModel;
+import org.keycloak.services.resources.flows.Flows;
+import org.keycloak.services.resources.flows.OAuthFlows;
import javax.ws.rs.Consumes;
+import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
@@ -25,40 +34,55 @@ 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.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
+
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;
+import java.util.StringTokenizer;
/**
* @author Bill Burke
* @version $Revision: 1 $
*/
-public class TokenService extends AbstractLoginService {
-
+public class TokenService {
protected static final Logger logger = Logger.getLogger(TokenService.class);
+ protected RealmModel realm;
+ protected TokenManager tokenManager;
+ protected AuthenticationManager authManager = new AuthenticationManager();
+
@Context
protected Providers providers;
@Context
protected SecurityContext securityContext;
+ @Context
+ protected UriInfo uriInfo;
+ @Context
+ protected HttpHeaders headers;
+ @Context
+ HttpRequest request;
+ @Context
+ HttpResponse response;
private ResourceAdminManager resourceAdminManager = new ResourceAdminManager();
public TokenService(RealmModel realm, TokenManager tokenManager) {
- super(realm, tokenManager);
+ this.realm = realm;
+ this.tokenManager = tokenManager;
}
public static UriBuilder tokenServiceBaseUrl(UriInfo uriInfo) {
- UriBuilder base = uriInfo.getBaseUriBuilder()
- .path(RealmsResource.class).path(RealmsResource.class, "getTokenService");
+ UriBuilder base = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getTokenService");
return base;
}
@@ -89,13 +113,12 @@ public class TokenService extends AbstractLoginService {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "processOAuth");
}
-
@Path("grants/identity-token")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response grantIdentityToken(final MultivaluedMap form) {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
if (username == null) {
@@ -128,7 +151,7 @@ public class TokenService extends AbstractLoginService {
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response grantAccessToken(final MultivaluedMap form) {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
if (username == null) {
@@ -159,49 +182,126 @@ public class TokenService extends AbstractLoginService {
@Path("auth/request/login")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public Response processLogin(final MultivaluedMap formData) {
- return new Transaction() {
+ public Response processLogin(@QueryParam("client_id") final String clientId, @QueryParam("scope") final String scopeParam,
+ @QueryParam("state") final String state, @QueryParam("redirect_uri") final String redirect,
+ final MultivaluedMap formData) {
+ return new Transaction() {
protected Response callImpl() {
- String clientId = formData.getFirst("client_id");
- String scopeParam = formData.getFirst("scope");
- String state = formData.getFirst("state");
- String redirect = formData.getFirst("redirect_uri");
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
if (!realm.isEnabled()) {
- securityFailureForward("Realm not enabled.");
- return null;
+ return oauth.forwardToSecurityFailure("Realm not enabled.");
}
UserModel client = realm.getUser(clientId);
if (client == null) {
- securityFailureForward("Unknown login requester.");
- return null;
+ return oauth.forwardToSecurityFailure("Unknown login requester.");
}
if (!client.isEnabled()) {
- securityFailureForward("Login requester not enabled.");
- return null;
+ return oauth.forwardToSecurityFailure("Login requester not enabled.");
}
String username = formData.getFirst("username");
UserModel user = realm.getUser(username);
if (user == null) {
logger.error("Incorrect user name.");
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Incorrect user name.");
- forwardToLoginForm(redirect, clientId, scopeParam, state);
- return null;
+
+ return Flows.forms(realm, request).setError(Messages.INVALID_USER).setFormData(formData)
+ .forwardToLogin();
}
if (!user.isEnabled()) {
- securityFailureForward("Your account is not enabled.");
- return null;
+ return oauth.forwardToSecurityFailure("Your account is not enabled.");
}
boolean authenticated = authManager.authenticateForm(realm, user, formData);
if (!authenticated) {
logger.error("Authentication failed");
- request.setAttribute("username", username);
- request.setAttribute("KEYCLOAK_LOGIN_ERROR_MESSAGE", "Invalid credentials.");
- forwardToLoginForm(redirect, clientId, scopeParam, state);
- return null;
+
+ return Flows.forms(realm, request).setError(Messages.INVALID_PASSWORD).setFormData(formData)
+ .forwardToLogin();
}
- return processAccessCode(scopeParam, state, redirect, client, user);
+ return oauth.processAccessCode(scopeParam, state, redirect, client, user);
+ }
+ }.call();
+ }
+
+ @Path("registrations")
+ @POST
+ @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+ public Response processRegister(@QueryParam("client_id") final String clientId,
+ @QueryParam("scope") final String scopeParam, @QueryParam("state") final String state,
+ @QueryParam("redirect_uri") final String redirect, final MultivaluedMap formData) {
+ return new Transaction() {
+ @Override
+ protected Response callImpl() {
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
+
+ if (!realm.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Realm not enabled");
+ }
+ UserModel client = realm.getUser(clientId);
+ if (client == null) {
+ return oauth.forwardToSecurityFailure("Unknown login requester.");
+ }
+
+ if (!client.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Login requester not enabled.");
+ }
+
+ if (!realm.isRegistrationAllowed()) {
+ return oauth.forwardToSecurityFailure("Registration not allowed");
+ }
+
+ String error = validateRegistrationForm(formData);
+ if (error != null) {
+ return Flows.forms(realm, request).setError(error).setFormData(formData).forwardToRegistration();
+ }
+
+ String username = formData.getFirst("username");
+
+ UserModel user = realm.getUser(username);
+ if (user != null) {
+ return Flows.forms(realm, request).setError(Messages.USERNAME_EXISTS).setFormData(formData)
+ .forwardToRegistration();
+ }
+
+ user = realm.addUser(username);
+
+ String fullname = formData.getFirst("name");
+ if (fullname != null) {
+ StringTokenizer tokenizer = new StringTokenizer(fullname, " ");
+ StringBuffer first = null;
+ String last = "";
+ while (tokenizer.hasMoreTokens()) {
+ String token = tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens()) {
+ if (first == null) {
+ first = new StringBuffer();
+ } else {
+ first.append(" ");
+ }
+ first.append(token);
+ } else {
+ last = token;
+ }
+ }
+ if (first == null)
+ first = new StringBuffer();
+ user.setFirstName(first.toString());
+ user.setLastName(last);
+ }
+
+ user.setEmail(formData.getFirst("email"));
+
+ UserCredentialModel credentials = new UserCredentialModel();
+ credentials.setType(CredentialRepresentation.PASSWORD);
+ credentials.setValue(formData.getFirst("password"));
+ realm.updateCredential(user, credentials);
+
+ // TODO Grant default roles for realm when available
+ RoleModel defaultRole = realm.getRole("user");
+
+ realm.grantRole(user, defaultRole);
+
+ return processLogin(clientId, scopeParam, state, redirect, formData);
}
}.call();
}
@@ -210,7 +310,7 @@ public class TokenService extends AbstractLoginService {
@POST
@Produces("application/json")
public Response accessCodeToToken(final MultivaluedMap formData) {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
logger.info("accessRequest <---");
if (!realm.isEnabled()) {
@@ -258,7 +358,6 @@ public class TokenService extends AbstractLoginService {
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
-
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
@@ -270,7 +369,8 @@ public class TokenService extends AbstractLoginService {
Map res = new HashMap();
res.put("error", "invalid_grant");
res.put("error_description", "Unable to verify code signature");
- return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+ return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
+ .build();
}
String key = input.readContent(String.class);
AccessCodeEntry accessCode = tokenManager.pullAccessCode(key);
@@ -278,25 +378,29 @@ public class TokenService extends AbstractLoginService {
Map res = new HashMap();
res.put("error", "invalid_grant");
res.put("error_description", "Code not found");
- return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+ return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
+ .build();
}
if (accessCode.isExpired()) {
Map res = new HashMap();
res.put("error", "invalid_grant");
res.put("error_description", "Code is expired");
- return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+ return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
+ .build();
}
if (!accessCode.getToken().isActive()) {
Map res = new HashMap();
res.put("error", "invalid_grant");
res.put("error_description", "Token expired");
- return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+ return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
+ .build();
}
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) {
Map res = new HashMap();
res.put("error", "invalid_grant");
res.put("error_description", "Auth error");
- return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res).build();
+ return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
+ .build();
}
logger.info("accessRequest SUCCESS");
AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
@@ -313,9 +417,7 @@ public class TokenService extends AbstractLoginService {
} catch (Exception e) {
throw new RuntimeException(e);
}
- String encodedToken = new JWSBuilder()
- .content(tokenBytes)
- .rsa256(privateKey);
+ String encodedToken = new JWSBuilder().content(tokenBytes).rsa256(privateKey);
return accessTokenResponse(token, encodedToken);
}
@@ -334,25 +436,25 @@ public class TokenService extends AbstractLoginService {
@Path("login")
@GET
public Response loginPage(final @QueryParam("response_type") String responseType,
- final @QueryParam("redirect_uri") String redirect,
- final @QueryParam("client_id") String clientId,
- final @QueryParam("scope") String scopeParam,
- final @QueryParam("state") String state) {
- return new Transaction() {
+ final @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
+ final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state) {
+ return new Transaction() {
protected Response callImpl() {
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
+
if (!realm.isEnabled()) {
- securityFailureForward("Realm not enabled");
+ oauth.forwardToSecurityFailure("Realm not enabled");
return null;
}
UserModel client = realm.getUser(clientId);
if (client == null) {
- securityFailureForward("Unknown login requester.");
+ oauth.forwardToSecurityFailure("Unknown login requester.");
transaction.rollback();
return null;
}
if (!client.isEnabled()) {
- securityFailureForward("Login requester not enabled.");
+ oauth.forwardToSecurityFailure("Login requester not enabled.");
transaction.rollback();
session.close();
return null;
@@ -362,7 +464,7 @@ public class TokenService extends AbstractLoginService {
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.");
+ oauth.forwardToSecurityFailure("Login requester not allowed to request login.");
transaction.rollback();
session.close();
return null;
@@ -371,11 +473,42 @@ public class TokenService extends AbstractLoginService {
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers);
if (user != null) {
logger.info(user.getLoginName() + " already logged in.");
- return processAccessCode(scopeParam, state, redirect, client, user);
+ return oauth.processAccessCode(scopeParam, state, redirect, client, user);
}
- forwardToLoginForm(redirect, clientId, scopeParam, state);
- return null;
+ return Flows.forms(realm, request).forwardToLogin();
+ }
+ }.call();
+ }
+
+ @Path("registrations")
+ @GET
+ public Response registerPage(final @QueryParam("response_type") String responseType,
+ final @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
+ final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state) {
+ return new Transaction() {
+ protected Response callImpl() {
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
+
+ if (!realm.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Realm not enabled");
+ }
+ UserModel client = realm.getUser(clientId);
+ if (client == null) {
+ return oauth.forwardToSecurityFailure("Unknown login requester.");
+ }
+
+ if (!client.isEnabled()) {
+ return oauth.forwardToSecurityFailure("Login requester not enabled.");
+ }
+
+ if (!realm.isRegistrationAllowed()) {
+ return oauth.forwardToSecurityFailure("Registration not allowed");
+ }
+
+ authManager.expireIdentityCookie(realm, uriInfo);
+
+ return Flows.forms(realm, request).forwardToRegistration();
}
}.call();
}
@@ -384,7 +517,7 @@ public class TokenService extends AbstractLoginService {
@GET
@NoCache
public Response logout(final @QueryParam("redirect_uri") String redirectUri) {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
// todo do we care if anybody can trigger this?
@@ -404,8 +537,10 @@ public class TokenService extends AbstractLoginService {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processOAuth(final MultivaluedMap formData) {
- return new Transaction() {
+ return new Transaction() {
protected Response callImpl() {
+ OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
+
String code = formData.getFirst("code");
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
@@ -415,16 +550,12 @@ public class TokenService extends AbstractLoginService {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
- securityFailureForward("Illegal access code.");
- session.close();
- return null;
+ return oauth.forwardToSecurityFailure("Illegal access code.");
}
String key = input.readContent(String.class);
AccessCodeEntry accessCodeEntry = tokenManager.getAccessCode(key);
if (accessCodeEntry == null) {
- securityFailureForward("Unknown access code.");
- session.close();
- return null;
+ return oauth.forwardToSecurityFailure("Unknown access code.");
}
String redirect = accessCodeEntry.getRedirectUri();
@@ -434,21 +565,45 @@ public class TokenService extends AbstractLoginService {
return redirectAccessDenied(redirect, state);
}
- return redirectAccessCode(accessCodeEntry, state, redirect);
+ return oauth.redirectAccessCode(accessCodeEntry, state, redirect);
}
}.call();
}
protected Response redirectAccessDenied(String redirect, String state) {
UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("error", "access_denied");
- if (state != null) redirectUri.queryParam("state", state);
+ if (state != null)
+ redirectUri.queryParam("state", state);
Response.ResponseBuilder location = Response.status(302).location(redirectUri.build());
return location.build();
}
- @Override
- protected Logger getLogger() {
- return logger;
+ private String validateRegistrationForm(MultivaluedMap formData) {
+ if (isEmpty(formData.getFirst("name"))) {
+ return Messages.MISSING_NAME;
+ }
+
+ if (isEmpty(formData.getFirst("email"))) {
+ return Messages.MISSING_EMAIL;
+ }
+
+ if (isEmpty(formData.getFirst("username"))) {
+ return Messages.MISSING_USERNAME;
+ }
+
+ if (isEmpty(formData.getFirst("password"))) {
+ return Messages.MISSING_PASSWORD;
+ }
+
+ if (!formData.getFirst("password").equals(formData.getFirst("password-confirm"))) {
+ return Messages.INVALID_PASSWORD_CONFIRM;
+ }
+
+ return null;
+ }
+
+ private boolean isEmpty(String s) {
+ return s == null || s.length() == 0;
}
}
diff --git a/services/src/main/java/org/keycloak/services/resources/Transaction.java b/services/src/main/java/org/keycloak/services/resources/Transaction.java
index 32f4319d1b..d88cc050b7 100755
--- a/services/src/main/java/org/keycloak/services/resources/Transaction.java
+++ b/services/src/main/java/org/keycloak/services/resources/Transaction.java
@@ -13,7 +13,7 @@ import javax.ws.rs.core.Application;
* @author Bill Burke
* @version $Revision: 1 $
*/
-public class Transaction {
+public class Transaction {
protected KeycloakSession session;
protected KeycloakTransaction transaction;
protected boolean closeSession;
@@ -83,7 +83,7 @@ public class Transaction {
}
}
- protected T callImpl() {
+ protected T callImpl() {
return null;
}
@@ -91,7 +91,7 @@ public class Transaction {
* Will not begin or end a transaction or close a session if the transaction was already active when called
*
*/
- public T call() {
+ public T call() {
boolean wasActive = transaction.isActive();
if (!wasActive) transaction.begin();
try {
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/ApplicationResource.java b/services/src/main/java/org/keycloak/services/resources/admin/ApplicationResource.java
index 35038d2984..36540ac1b1 100755
--- a/services/src/main/java/org/keycloak/services/resources/admin/ApplicationResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/ApplicationResource.java
@@ -36,7 +36,7 @@ public class ApplicationResource {
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void update(final ApplicationRepresentation rep) {
- new Transaction() {
+ new Transaction() {
@Override
protected void runImpl() {
ResourceManager resourceManager = new ResourceManager(new RealmManager(session));
@@ -50,7 +50,7 @@ public class ApplicationResource {
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public ApplicationRepresentation getResource(final @PathParam("id") String id) {
- return new Transaction() {
+ return new Transaction() {
@Override
protected ApplicationRepresentation callImpl() {
ResourceManager resourceManager = new ResourceManager(new RealmManager(session));
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/ApplicationsResource.java b/services/src/main/java/org/keycloak/services/resources/admin/ApplicationsResource.java
index e7496af971..9be8bbdc7e 100755
--- a/services/src/main/java/org/keycloak/services/resources/admin/ApplicationsResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/ApplicationsResource.java
@@ -42,7 +42,7 @@ public class ApplicationsResource {
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public List getResources() {
- return new Transaction() {
+ return new Transaction>() {
@Override
protected List callImpl() {
List rep = new ArrayList();
@@ -59,7 +59,7 @@ public class ApplicationsResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createResource(final @Context UriInfo uriInfo, final ApplicationRepresentation rep) {
- return new Transaction() {
+ return new Transaction() {
@Override
protected Response callImpl() {
ResourceManager resourceManager = new ResourceManager(new RealmManager(session));
@@ -71,7 +71,7 @@ public class ApplicationsResource {
@Path("{id}")
public ApplicationResource getResource(final @PathParam("id") String id) {
- return new Transaction(false) {
+ return new Transaction(false) {
@Override
protected ApplicationResource callImpl() {
ApplicationModel applicationModel = realm.getApplicationById(id);
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
index e5fc7ac59b..c8309cbd1e 100755
--- a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
@@ -6,21 +6,25 @@ import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.services.managers.RealmManager;
-import org.keycloak.services.managers.UserManager;
import org.keycloak.services.models.RealmModel;
import org.keycloak.services.models.RoleModel;
import org.keycloak.services.models.UserModel;
import org.keycloak.services.resources.Transaction;
-import javax.ws.rs.*;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.InternalServerErrorException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+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.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
/**
* @author Bill Burke
@@ -45,7 +49,7 @@ public class RealmAdminResource {
@NoCache
@Produces("application/json")
public RealmRepresentation getRealm() {
- return new Transaction() {
+ return new Transaction() {
@Override
protected RealmRepresentation callImpl() {
return new RealmManager(session).toRepresentation(realm);
@@ -58,15 +62,14 @@ public class RealmAdminResource {
@GET
@NoCache
@Produces("application/json")
- public List queryRoles() {
- return new Transaction() {
+ public List getRoles() {
+ return new Transaction>() {
@Override
protected List callImpl() {
List roleModels = realm.getRoles();
List roles = new ArrayList();
for (RoleModel roleModel : roleModels) {
RoleRepresentation role = new RoleRepresentation(roleModel.getName(), roleModel.getDescription());
- role.setId(roleModel.getId());
roles.add(role);
}
return roles;
@@ -92,7 +95,7 @@ public class RealmAdminResource {
@NoCache
@Produces("application/json")
public RoleRepresentation getRole(final @PathParam("id") String id) {
- return new Transaction() {
+ return new Transaction() {
@Override
protected RoleRepresentation callImpl() {
RoleModel roleModel = realm.getRoleById(id);
@@ -129,7 +132,7 @@ public class RealmAdminResource {
@POST
@Consumes("application/json")
public Response createRole(final @Context UriInfo uriInfo, final RoleRepresentation rep) {
- return new Transaction() {
+ return new Transaction() {
@Override
protected Response callImpl() {
if (realm.getRole(rep.getName()) != null) {
@@ -151,85 +154,10 @@ public class RealmAdminResource {
@GET
@NoCache
@Produces("application/json")
- public List queryUsers(final @Context UriInfo uriInfo) {
- return new Transaction() {
- @Override
- protected List callImpl() {
- logger.info("queryUsers");
- Map params = new HashMap();
- MultivaluedMap queryParameters = uriInfo.getQueryParameters();
- for (String key : queryParameters.keySet()) {
- logger.info(" " + key + "=" + queryParameters.getFirst(key));
- params.put(key, queryParameters.getFirst(key));
- }
- List userModels = realm.queryUsers(params);
- List users = new ArrayList();
- for (UserModel userModel : userModels) {
- users.add(UserManager.toRepresentation(userModel));
- }
- logger.info(" resultSet: " + users.size());
- return users;
- }
- }.call();
+ public List getUsers() {
+ return null;
}
- @Path("users/{loginName}")
- @GET
- @NoCache
- @Produces("application/json")
- public UserRepresentation getUser(final @PathParam("loginName") String loginName) {
- return new Transaction() {
- @Override
- protected UserRepresentation callImpl() {
- UserModel userModel = realm.getUser(loginName);
- if (userModel == null) {
- throw new NotFoundException();
- }
- return UserManager.toRepresentation(userModel);
- }
- }.call();
- }
-
- @Path("users")
- @POST
- @NoCache
- @Consumes("application/json")
- public Response createUser(final @Context UriInfo uriInfo, final UserRepresentation rep) {
- return new Transaction() {
- @Override
- protected Response callImpl() {
- if (realm.getUser(rep.getUsername()) != null) {
- return Response.status(Response.Status.FOUND).build();
- }
- rep.setCredentials(null); // don't allow credential creation
- UserManager userManager = new UserManager();
- UserModel userModel = userManager.createUser(realm, rep);
- return Response.created(uriInfo.getAbsolutePathBuilder().path(userModel.getLoginName()).build()).build();
- }
- }.call();
- }
-
- @Path("users/{loginName}")
- @PUT
- @NoCache
- @Consumes("application/json")
- public void updateUser(final @PathParam("loginName") String loginName, final UserRepresentation rep) {
- new Transaction() {
- @Override
- protected void runImpl() {
- UserModel userModel = realm.getUser(loginName);
- if (userModel == null) {
- throw new NotFoundException();
- }
- UserManager userManager = new UserManager();
- userManager.updateUserAsAdmin(userModel, rep);
- }
- }.run();
- }
-
-
-
-
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RealmsAdminResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RealmsAdminResource.java
index fd5485a507..1082f69a04 100755
--- a/services/src/main/java/org/keycloak/services/resources/admin/RealmsAdminResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/RealmsAdminResource.java
@@ -54,7 +54,7 @@ public class RealmsAdminResource {
@NoCache
@Produces("application/json")
public List getRealms() {
- return new Transaction() {
+ return new Transaction>() {
@Override
protected List callImpl() {
logger.info(("getRealms()"));
@@ -81,7 +81,7 @@ public class RealmsAdminResource {
@Consumes("application/json")
public Response importRealm(@Context final UriInfo uriInfo, final RealmRepresentation rep) {
logger.info("importRealm: " + rep.getRealm());
- return new Transaction() {
+ return new Transaction() {
@Override
protected Response callImpl() {
RealmManager realmManager = new RealmManager(session);
@@ -96,7 +96,7 @@ public class RealmsAdminResource {
@Path("{id}")
public RealmAdminResource getRealmAdmin(@Context final HttpHeaders headers,
@PathParam("id") final String id) {
- return new Transaction(false) {
+ return new Transaction(false) {
@Override
protected RealmAdminResource callImpl() {
RealmManager realmManager = new RealmManager(session);
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/Flows.java b/services/src/main/java/org/keycloak/services/resources/flows/Flows.java
new file mode 100644
index 0000000000..723d023567
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/Flows.java
@@ -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.services.resources.flows;
+
+import javax.ws.rs.core.UriInfo;
+
+import org.jboss.resteasy.spi.HttpRequest;
+import org.keycloak.services.managers.AuthenticationManager;
+import org.keycloak.services.managers.TokenManager;
+import org.keycloak.services.models.RealmModel;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class Flows {
+
+ private Flows() {
+ }
+
+ public static PageFlows pages(HttpRequest request) {
+ return new PageFlows(request);
+ }
+
+ public static FormFlows forms(RealmModel realm, HttpRequest request) {
+ return new FormFlows(realm, request);
+ }
+
+ public static OAuthFlows oauth(RealmModel realm, HttpRequest request, UriInfo uriInfo, AuthenticationManager authManager,
+ TokenManager tokenManager) {
+ return new OAuthFlows(realm, request, uriInfo, authManager, tokenManager);
+ }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/FormFlows.java b/services/src/main/java/org/keycloak/services/resources/flows/FormFlows.java
new file mode 100644
index 0000000000..722f8bd193
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/FormFlows.java
@@ -0,0 +1,85 @@
+/*
+ * 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.flows;
+
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+
+import org.jboss.resteasy.spi.HttpRequest;
+import org.keycloak.services.models.RealmModel;
+import org.picketlink.idm.model.sample.Realm;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class FormFlows {
+
+ public static final String REALM = Realm.class.getName();
+ public static final String ERROR_MESSAGE = "KEYCLOAK_FORMS_ERROR_MESSAGE";
+ public static final String DATA = "KEYCLOAK_FORMS_DATA";
+
+ private MultivaluedMap formData;
+ private String error;
+
+ private RealmModel realm;
+
+ private HttpRequest request;
+
+ FormFlows(RealmModel realm, HttpRequest request) {
+ this.realm = realm;
+ this.request = request;
+ }
+
+ public FormFlows setFormData(MultivaluedMap formData) {
+ this.formData = formData;
+ return this;
+ }
+
+ public FormFlows setError(String error) {
+ this.error = error;
+ return this;
+ }
+
+ public Response forwardToLogin() {
+ return forwardToForm(Pages.LOGIN);
+ }
+
+ public Response forwardToRegistration() {
+ return forwardToForm(Pages.REGISTER);
+ }
+
+ private Response forwardToForm(String form) {
+ request.setAttribute(REALM, realm);
+
+ if (error != null) {
+ request.setAttribute(ERROR_MESSAGE, error);
+ }
+
+ if (formData != null) {
+ request.setAttribute(DATA, formData);
+ }
+
+ request.forward(form);
+ return null;
+ }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/OAuthFlows.java b/services/src/main/java/org/keycloak/services/resources/flows/OAuthFlows.java
new file mode 100644
index 0000000000..6a87ead696
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/OAuthFlows.java
@@ -0,0 +1,114 @@
+/*
+ * 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.flows;
+
+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.keycloak.services.managers.AccessCodeEntry;
+import org.keycloak.services.managers.AuthenticationManager;
+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;
+import org.keycloak.services.resources.TokenService;
+
+/**
+ * @author Bill Burke
+ * @author Stian Thorgersen
+ */
+public class OAuthFlows {
+
+ private static final Logger log = Logger.getLogger(OAuthFlows.class);
+
+ private RealmModel realm;
+
+ private HttpRequest request;
+
+ private UriInfo uriInfo;
+
+ private AuthenticationManager authManager;
+
+ private TokenManager tokenManager;
+
+ OAuthFlows(RealmModel realm, HttpRequest request, UriInfo uriInfo, AuthenticationManager authManager,
+ TokenManager tokenManager) {
+ this.realm = realm;
+ this.request = request;
+ this.uriInfo = uriInfo;
+ this.authManager = authManager;
+ this.tokenManager = tokenManager;
+ }
+
+ public Response redirectAccessCode(AccessCodeEntry accessCode, String state, String redirect) {
+ String code = accessCode.getCode();
+ UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("code", code);
+ log.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(authManager.createLoginCookie(realm, accessCode.getUser(), uriInfo));
+ }
+ return location.build();
+ }
+
+ public 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)) {
+ return forwardToSecurityFailure("Login requester not allowed to request login.");
+ }
+ AccessCodeEntry accessCode = tokenManager.createAccessCode(scopeParam, state, redirect, realm, client, user);
+ log.info("processAccessCode: isResource: " + isResource);
+ log.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)) {
+ return oauthGrantPage(accessCode, client);
+ }
+
+ return redirectAccessCode(accessCode, state, redirect);
+ }
+
+ public Response 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(Pages.OAUTH_GRANT);
+ return null;
+ }
+
+ public Response forwardToSecurityFailure(String message) {
+ return Flows.pages(request).forwardToSecurityFailure(message);
+ }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/PageFlows.java b/services/src/main/java/org/keycloak/services/resources/flows/PageFlows.java
new file mode 100644
index 0000000000..9b38098f59
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/PageFlows.java
@@ -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.services.resources.flows;
+
+import javax.ws.rs.core.Response;
+
+import org.jboss.resteasy.logging.Logger;
+import org.jboss.resteasy.spi.HttpRequest;
+import org.keycloak.services.JspRequestParameters;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class PageFlows {
+
+ private static final Logger log = Logger.getLogger(PageFlows.class);
+
+ private HttpRequest request;
+
+ PageFlows(HttpRequest request) {
+ this.request = request;
+ }
+
+ public Response forwardToSecurityFailure(String message) {
+ log.error(message);
+
+ request.setAttribute(JspRequestParameters.KEYCLOAK_SECURITY_FAILURE_MESSAGE, message);
+
+ request.forward(Pages.SECURITY_FAILURE);
+ return null;
+ }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/Pages.java b/services/src/main/java/org/keycloak/services/resources/flows/Pages.java
new file mode 100644
index 0000000000..1f069652c5
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/Pages.java
@@ -0,0 +1,37 @@
+/*
+ * 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.flows;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class Pages {
+
+ public final static String LOGIN = "/sdk/login.xhtml";
+
+ public final static String OAUTH_GRANT = "/saas/oauthGrantForm.jsp";
+
+ public final static String REGISTER = "/sdk/register.xhtml";
+
+ public final static String SECURITY_FAILURE = "/saas/securityFailure.jsp";
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/flows/Urls.java b/services/src/main/java/org/keycloak/services/resources/flows/Urls.java
new file mode 100644
index 0000000000..7b8d51dc03
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/flows/Urls.java
@@ -0,0 +1,95 @@
+/*
+ * 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.flows;
+
+import java.net.URI;
+
+import javax.ws.rs.core.UriBuilder;
+
+import org.keycloak.services.resources.RealmsResource;
+import org.keycloak.services.resources.SaasService;
+import org.keycloak.services.resources.SocialResource;
+import org.keycloak.services.resources.TokenService;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class Urls {
+
+ private static UriBuilder realmBase(URI baseUri) {
+ return UriBuilder.fromUri(baseUri).path(RealmsResource.class);
+ }
+
+ private static UriBuilder tokenBase(URI baseUri) {
+ return realmBase(baseUri).path(RealmsResource.class, "getTokenService");
+ }
+
+ public static URI realmLoginAction(URI baseUri, String realmId) {
+ return tokenBase(baseUri).path(TokenService.class, "processLogin").build(realmId);
+ }
+
+ public static URI realmLoginPage(URI baseUri, String realmId) {
+ return tokenBase(baseUri).path(TokenService.class, "loginPage").build(realmId);
+ }
+
+ public static URI realmRegisterAction(URI baseUri, String realmId) {
+ return tokenBase(baseUri).path(TokenService.class, "processRegister").build(realmId);
+ }
+
+ public static URI realmRegisterPage(URI baseUri, String realmId) {
+ return tokenBase(baseUri).path(TokenService.class, "registerPage").build(realmId);
+ }
+
+ private static UriBuilder saasBase(URI baseUri) {
+ return UriBuilder.fromUri(baseUri).path(SaasService.class);
+ }
+
+ public static URI saasLoginAction(URI baseUri) {
+ return saasBase(baseUri).path(SaasService.class, "processLogin").build();
+ }
+
+ public static URI saasLoginPage(URI baseUri) {
+ return saasBase(baseUri).path(SaasService.class, "loginPage").build();
+ }
+
+ public static URI saasRegisterAction(URI baseUri) {
+ return saasBase(baseUri).path(SaasService.class, "processRegister").build();
+ }
+
+ public static URI saasRegisterPage(URI baseUri) {
+ return saasBase(baseUri).path(SaasService.class, "registerPage").build();
+ }
+
+ private static UriBuilder socialBase(URI baseUri) {
+ return UriBuilder.fromUri(baseUri).path(SocialResource.class);
+ }
+
+ public static URI socialCallback(URI baseUri) {
+ return socialBase(baseUri).path(SocialResource.class, "callback").build();
+ }
+
+ public static URI socialRedirectToProviderAuth(URI baseUri, String realmId) {
+ return socialBase(baseUri).path(SocialResource.class, "redirectToProviderAuth")
+ .build(realmId);
+ }
+
+}
diff --git a/services/src/test/java/org/keycloak/test/ImportTest.java b/services/src/test/java/org/keycloak/test/ImportTest.java
index 727aa081c8..d1534d68ef 100755
--- a/services/src/test/java/org/keycloak/test/ImportTest.java
+++ b/services/src/test/java/org/keycloak/test/ImportTest.java
@@ -71,7 +71,7 @@ public class ImportTest {
List creds = realm.getRequiredCredentials();
Assert.assertEquals(1, creds.size());
RequiredCredentialModel cred = creds.get(0);
- Assert.assertEquals("Password", cred.getFormLabel());
+ Assert.assertEquals("password", cred.getFormLabel());
UserModel user = realm.getUser("loginclient");
Assert.assertNotNull(user);
diff --git a/social/README.md b/social/README.md
new file mode 100644
index 0000000000..90df3c281d
--- /dev/null
+++ b/social/README.md
@@ -0,0 +1,59 @@
+Keycloak social
+===============
+
+This document describes how to configure social providers for Keycloak. At the moment social providers are configured globally using system properties. These can either be passed using '-D' when starting the application server or added to the standalone.xml file, for example:
+
+
+
+
+
+
+
+
+
+
+Social provides implementations for Facebook, Google and Twitter.
+
+
+Configure Facebook
+------------------
+
+Open https://developers.facebook.com/apps. Click on Create New App
+
+Use any app name that you'd like, click Continue
+
+Select Disabled for Sandbox Mode
+
+Under Select how your app integrates with Facebook select Website with Facebook login. Fill in the form with the following values:
+
+* Site URL: http://[]/auth-server/rest/social/callback
+
+Click on Save changes. Use the value of App ID as the value of the system property "keycloak.social.facebook.key", and the value of App Secret as the value of "keycloak.social.facebook.secret".
+
+
+Configure Google
+----------------
+
+Open https://code.google.com/apis/console/. From the drop-down menu select Create.
+
+Use any name that you'd like, click Create Project, select API Access and click on Create an OAuth 2.0 client ID.
+
+Use any product name you'd like and leave the other fields empty, then click Next. On the next page select Web application as the application type. Click more options next> to Your site or hostname. Fill in the form with the following values:
+
+* Authorized Redirect URIs: http://[]/auth-server/rest/social/callback
+
+Click on Create client ID. Use the value of Client ID as the value of the system property "keycloak.social.google.key", and the value of Client secret as the value of "keycloak.social.google.secret".
+
+
+Configure Twitter
+-----------------
+
+Open https://dev.twitter.com/apps. Click on Create a new application.
+
+Fill in name, description and website. Leave Callback URL empty!
+
+Agree to the rules, fill in the captcha and click on Create your Twitter application.
+
+Now click on Settings and tick the box Allow this application to be used to Sign in with Twitter, and click on Update this Twitter application's settings.
+
+Finally click on Details. Use the value of Client key as the value of the system property "keycloak.social.twitter.key", and the value of Client secret as the value of "keycloak.social.twitter.secret".
diff --git a/social/core/src/main/java/org/keycloak/social/SocialProvider.java b/social/core/src/main/java/org/keycloak/social/SocialProvider.java
index 81d9216a68..70da76de24 100644
--- a/social/core/src/main/java/org/keycloak/social/SocialProvider.java
+++ b/social/core/src/main/java/org/keycloak/social/SocialProvider.java
@@ -21,25 +21,20 @@
*/
package org.keycloak.social;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlTransient;
/**
* @author Stian Thorgersen
*/
-@XmlRootElement
public interface SocialProvider {
String getId();
- @XmlTransient
AuthRequest getAuthUrl(SocialProviderConfig config) throws SocialProviderException;
String getRequestIdParamName();
String getName();
- @XmlTransient
SocialUser processCallback(SocialProviderConfig config, AuthCallback callback) throws SocialProviderException;
}
diff --git a/social/facebook/pom.xml b/social/facebook/pom.xml
new file mode 100644
index 0000000000..a2bec96836
--- /dev/null
+++ b/social/facebook/pom.xml
@@ -0,0 +1,34 @@
+
+
+ keycloak-social-parent
+ org.keycloak
+ 1.0-alpha-1
+ ../pom.xml
+
+ 4.0.0
+ jar
+
+ keycloak-social-facebook
+ Keycloak Social Facebook
+
+
+
+
+ org.keycloak
+ keycloak-social-core
+ ${project.version}
+ provided
+
+
+ org.jboss.resteasy
+ resteasy-client
+ provided
+
+
+ org.codehaus.jackson
+ jackson-core-asl
+ provided
+
+
+
diff --git a/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookProvider.java b/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookProvider.java
new file mode 100644
index 0000000000..dbe42547c2
--- /dev/null
+++ b/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookProvider.java
@@ -0,0 +1,145 @@
+package org.keycloak.social.facebook;
+
+import java.net.URI;
+import java.util.UUID;
+
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+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;
+
+/**
+ * Social provider for Facebook
+ *
+ * @author Marek Posolda
+ */
+public class FacebookProvider implements SocialProvider {
+
+ private static final String AUTHENTICATION_ENDPOINT_URL = "https://graph.facebook.com/oauth/authorize";
+
+ private static final String ACCESS_TOKEN_ENDPOINT_URL = "https://graph.facebook.com/oauth/access_token";
+
+ private static final String PROFILE_ENDPOINT_URL = "https://graph.facebook.com/me";
+
+ private static final String DEFAULT_RESPONSE_TYPE = "code";
+
+ private static final String DEFAULT_SCOPE = "email";
+
+ @Override
+ public String getId() {
+ return "facebook";
+ }
+
+ @Override
+ public AuthRequest getAuthUrl(SocialProviderConfig config) throws SocialProviderException {
+ String state = UUID.randomUUID().toString();
+
+ AuthRequestBuilder b = AuthRequestBuilder.create(state, AUTHENTICATION_ENDPOINT_URL).setQueryParam("client_id", config.getKey())
+ .setQueryParam("response_type", DEFAULT_RESPONSE_TYPE).setQueryParam("scope", DEFAULT_SCOPE)
+ .setQueryParam("redirect_uri", config.getCallbackUrl()).setQueryParam("state", state);
+
+ b.setAttribute("state", state);
+
+ return b.build();
+ }
+
+ @Override
+ public String getRequestIdParamName() {
+ return "state";
+ }
+
+ @Override
+ public String getName() {
+ return "Facebook";
+ }
+
+ @Override
+ 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");
+ }
+
+ ResteasyClient client = new ResteasyClientBuilder()
+ .hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY).build();
+
+ String accessToken = loadAccessToken(code, config, client);
+
+ FacebookUser facebookUser = loadUser(accessToken, client);
+
+ SocialUser socialUser = new SocialUser(facebookUser.getId());
+ socialUser.setEmail(facebookUser.getEmail());
+ socialUser.setLastName(facebookUser.getLastName());
+ socialUser.setFirstName(facebookUser.getFirstName());
+
+ return socialUser;
+ } catch (SocialProviderException spe) {
+ throw spe;
+ } catch (Exception e) {
+ throw new SocialProviderException(e);
+ }
+ }
+
+ protected String loadAccessToken(String code, SocialProviderConfig config, ResteasyClient client) throws SocialProviderException {
+ Form form = new Form();
+ form.param("grant_type", "authorization_code")
+ .param("code", code)
+ .param("client_id", config.getKey())
+ .param("client_secret", config.getSecret())
+ .param("redirect_uri", config.getCallbackUrl());
+
+ Response response = client.target(ACCESS_TOKEN_ENDPOINT_URL).request().post(Entity.form(form));
+
+ if (response.getStatus() != 200) {
+ String errorTokenResponse = response.readEntity(String.class);
+ throw new SocialProviderException("Access token request to Facebook failed. Status: " + response.getStatus() + ", response: " + errorTokenResponse);
+ }
+
+ String accessTokenResponse = response.readEntity(String.class);
+ return parseParameter(accessTokenResponse, "access_token");
+ }
+
+ protected FacebookUser loadUser(String accessToken, ResteasyClient client) throws SocialProviderException {
+ URI userDetailsUri = UriBuilder.fromUri(PROFILE_ENDPOINT_URL)
+ .queryParam("access_token", accessToken)
+ .queryParam("fields", "id,name,username,first_name,last_name,email")
+ .build();
+
+ Response response = client.target(userDetailsUri).request()
+ .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
+ .get();
+ if (response.getStatus() != 200) {
+ String errorTokenResponse = response.readEntity(String.class);
+ throw new SocialProviderException("Request to Facebook for obtaining user failed. Status: " + response.getStatus() + ", response: " + errorTokenResponse);
+ }
+
+ return response.readEntity(FacebookUser.class);
+ }
+
+ // Parses value of given parameter from input string like "my_param=abcd&another_param=xyz"
+ private String parseParameter(String input, String paramName) {
+ int start = input.indexOf(paramName + "=");
+ if (start != -1) {
+ input = input.substring(start + paramName.length() + 1);
+ int end = input.indexOf("&");
+ return end==-1 ? input : input.substring(0, end);
+ } else {
+ throw new IllegalArgumentException("Parameter " + paramName + " not available in response " + input);
+ }
+
+ }
+}
diff --git a/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookUser.java b/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookUser.java
new file mode 100644
index 0000000000..8a30fc7a0d
--- /dev/null
+++ b/social/facebook/src/main/java/org/keycloak/social/facebook/FacebookUser.java
@@ -0,0 +1,77 @@
+package org.keycloak.social.facebook;
+
+import org.codehaus.jackson.annotate.JsonProperty;
+
+/**
+ * Wrap info about user from Facebook
+ *
+ * @author Marek Posolda
+ */
+public class FacebookUser {
+
+ @JsonProperty("id")
+ private String id;
+
+ @JsonProperty("first_name")
+ private String firstName;
+
+ @JsonProperty("last_name")
+ private String lastName;
+
+ @JsonProperty("username")
+ private String username;
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("email")
+ private String email;
+
+ 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 getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+}
diff --git a/social/facebook/src/main/resources/META-INF/services/org.keycloak.social.SocialProvider b/social/facebook/src/main/resources/META-INF/services/org.keycloak.social.SocialProvider
new file mode 100644
index 0000000000..5c147a5107
--- /dev/null
+++ b/social/facebook/src/main/resources/META-INF/services/org.keycloak.social.SocialProvider
@@ -0,0 +1 @@
+org.keycloak.social.facebook.FacebookProvider
\ No newline at end of file
diff --git a/social/pom.xml b/social/pom.xml
index 9efd60c0e4..2041baecf2 100755
--- a/social/pom.xml
+++ b/social/pom.xml
@@ -17,6 +17,7 @@
core
google
twitter
+ facebook
diff --git a/social/twitter/src/main/java/org/keycloak/social/twitter/TwitterProvider.java b/social/twitter/src/main/java/org/keycloak/social/twitter/TwitterProvider.java
index ee5175b529..d014e81137 100644
--- a/social/twitter/src/main/java/org/keycloak/social/twitter/TwitterProvider.java
+++ b/social/twitter/src/main/java/org/keycloak/social/twitter/TwitterProvider.java
@@ -49,7 +49,7 @@ public class TwitterProvider implements SocialProvider {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(request.getKey(), request.getSecret());
- RequestToken requestToken = twitter.getOAuthRequestToken();
+ RequestToken requestToken = twitter.getOAuthRequestToken(request.getCallbackUrl());
return AuthRequestBuilder.create(requestToken.getToken(), requestToken.getAuthenticationURL())
.setAttribute("token", requestToken.getToken()).setAttribute("tokenSecret", requestToken.getTokenSecret())