Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Bill Burke committed 2013-10-21 14:49:56 -04:00
commit 158f85cb7a
90 files changed
+1512 -941

No files matched your search

+4
View File
@@ -165,6 +165,10 @@
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@@ -44,9 +44,9 @@ public interface FormService {
private RealmModel realm;
private UserModel userModel;
private String error;
private String message;
private FormFlows.ErrorType errorType;
private FormFlows.MessageType messageType;
private MultivaluedMap<String, String> formData;
private URI baseURI;
@@ -81,11 +81,11 @@ public interface FormService {
private String contextPath;
public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String error){
public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String message){
this.realm = realm;
this.userModel = userModel;
this.formData = formData;
this.error = error;
this.message = message;
}
public URI getBaseURI() {
@@ -96,12 +96,12 @@ public interface FormService {
this.baseURI = baseURI;
}
public String getError() {
return error;
public String getMessage() {
return message;
}
public void setError(String error) {
this.error = error;
public void setMessage(String message) {
this.message = message;
}
public MultivaluedMap<String, String> getFormData() {
@@ -128,12 +128,12 @@ public interface FormService {
this.userModel = userModel;
}
public FormFlows.ErrorType getErrorType() {
return errorType;
public FormFlows.MessageType getMessageType() {
return messageType;
}
public void setErrorType(FormFlows.ErrorType errorType) {
this.errorType = errorType;
public void setMessageType(FormFlows.MessageType messageType) {
this.messageType = messageType;
}
/* OAuth Part */
@@ -42,6 +42,11 @@ public class ApplicationManager {
resourceUser.addRedirectUri(redirectUri);
}
}
if (resourceRep.getWebOrigins() != null) {
for (String webOrigin : resourceRep.getWebOrigins()) {
resourceUser.addWebOrigin(webOrigin);
}
}
realm.grantRole(resourceUser, loginRole);
@@ -97,6 +102,11 @@ public class ApplicationManager {
if (redirectUris != null) {
resource.getApplicationUser().setRedirectUris(new HashSet<String>(redirectUris));
}
List<String> webOrigins = rep.getWebOrigins();
if (webOrigins != null) {
resource.getApplicationUser().setWebOrigins(new HashSet<String>(webOrigins));
}
}
public ApplicationRepresentation toRepresentation(ApplicationModel applicationModel) {
@@ -113,6 +123,11 @@ public class ApplicationManager {
rep.setRedirectUris(new LinkedList<String>(redirectUris));
}
Set<String> webOrigins = applicationModel.getApplicationUser().getWebOrigins();
if (webOrigins != null) {
rep.setWebOrigins(new LinkedList<String>(webOrigins));
}
return rep;
}
@@ -13,6 +13,7 @@ import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.resources.AccountService;
import org.keycloak.services.resources.RealmsResource;
import org.keycloak.services.resources.SaasService;
@@ -61,6 +62,11 @@ public class AuthenticationManager {
return createLoginCookie(realm, user, cookieName, cookiePath);
}
public NewCookie createAccountIdentityCookie(RealmModel realm, UserModel user, URI uri) {
String cookieName = AccountService.ACCOUNT_IDENTITY_COOKIE;
String cookiePath = uri.getPath();
return createLoginCookie(realm, user, cookieName, cookiePath);
}
protected NewCookie createLoginCookie(RealmModel realm, UserModel user, String cookieName, String cookiePath) {
SkeletonKeyToken identityToken = createIdentityToken(realm, user.getLoginName());
@@ -99,6 +105,11 @@ public class AuthenticationManager {
expireCookie(SaasService.SAAS_IDENTITY_COOKIE, cookiePath);
}
public void expireAccountIdentityCookie(URI uri) {
String cookiePath = uri.getPath();
expireCookie(AccountService.ACCOUNT_IDENTITY_COOKIE, cookiePath);
}
public void expireCookie(String cookieName, String path) {
HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
if (response == null) {
@@ -120,6 +131,11 @@ public class AuthenticationManager {
return authenticateIdentityCookie(realm, uriInfo, headers, cookieName);
}
public UserModel authenticateAccountIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
String cookieName = AccountService.ACCOUNT_IDENTITY_COOKIE;
return authenticateIdentityCookie(realm, uriInfo, headers, cookieName);
}
public UserModel authenticateSaasIdentity(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
UserModel user = authenticateSaasIdentityCookie(realm, uriInfo, headers);
if (user != null) return user;
@@ -90,6 +90,36 @@ public class RealmManager {
if (rep.getDefaultRoles() != null) {
realm.updateDefaultRoles(rep.getDefaultRoles());
}
if (rep.isAccountManagement()) {
enableAccountManagement(realm);
} else {
disableAccountManagement(realm);
}
}
private void enableAccountManagement(RealmModel realm) {
ApplicationModel application = realm.getApplicationById(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
if (application == null) {
application = realm.addApplication(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
UserCredentialModel password = new UserCredentialModel();
password.setType(UserCredentialModel.PASSWORD);
password.setValue(UUID.randomUUID().toString()); // just a random password as we'll never access it
realm.updateCredential(application.getApplicationUser(), password);
RoleModel applicationRole = realm.getRole(Constants.APPLICATION_ROLE);
realm.grantRole(application.getApplicationUser(), applicationRole);
}
application.setEnabled(true);
}
private void disableAccountManagement(RealmModel realm) {
ApplicationModel application = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
if (application != null) {
application.setEnabled(false); // TODO Should we delete the application instead?
}
}
public RealmModel importRealm(RealmRepresentation rep, UserModel realmCreator) {
@@ -214,6 +244,10 @@ public class RealmManager {
}
}
}
if (rep.isAccountManagement() != null && rep.isAccountManagement()) {
enableAccountManagement(newRealm);
}
}
public void createRole(RealmModel newRealm, RoleRepresentation roleRep) {
@@ -370,6 +404,9 @@ public class RealmManager {
rep.setAccessCodeLifespan(realm.getAccessCodeLifespan());
rep.setAccessCodeLifespanUserAction(realm.getAccessCodeLifespanUserAction());
ApplicationModel accountManagementApplication = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
rep.setAccountManagement(accountManagementApplication != null && accountManagementApplication.isEnabled());
List<RoleModel> defaultRoles = realm.getDefaultRoles();
if (defaultRoles.size() > 0) {
String[] d = new String[defaultRoles.size()];
@@ -37,16 +37,20 @@ public class ResourceAdminManager {
}
protected boolean logoutResource(RealmModel realm, ApplicationModel resource, String user, ResteasyClient client) {
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), System.currentTimeMillis() / 1000 + 30, resource.getName(), user);
String token = new TokenManager().encodeToken(realm, adminAction);
Form form = new Form();
form.param("token", token);
String managementUrl = resource.getManagementUrl();
logger.info("logout user: " + user + " resource: " + resource.getName() + " url" + managementUrl);
Response response = client.target(managementUrl).queryParam("action", "logout").request().post(Entity.form(form));
boolean success = response.getStatus() == 204;
response.close();
return success;
if (managementUrl != null) {
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), System.currentTimeMillis() / 1000 + 30, resource.getName(), user);
String token = new TokenManager().encodeToken(realm, adminAction);
Form form = new Form();
form.param("token", token);
logger.info("logout user: " + user + " resource: " + resource.getName() + " url" + managementUrl);
Response response = client.target(managementUrl).queryParam("action", "logout").request().post(Entity.form(form));
boolean success = response.getStatus() == 204;
response.close();
return success;
} else {
return false;
}
}
}
@@ -44,6 +44,8 @@ public class Messages {
public static final String MISSING_PASSWORD = "missingPassword";
public static final String NOTMATCH_PASSWORD = "notMatchPassword";
public static final String MISSING_USERNAME = "missingUsername";
public static final String MISSING_TOTP = "missingTotp";
@@ -52,6 +54,14 @@ public class Messages {
public static final String USERNAME_EXISTS = "usernameExists";
public static final String ACTION_WARN_TOTP = "actionTotpWarning";
public static final String ACTION_WARN_PROFILE = "actionProfileWarning";
public static final String ACTION_WARN_PASSWD = "actionPasswordWarning";
public static final String ACTION_WARN_EMAIL = "actionEmailWarning";
public static final String ERROR = "error";
}
@@ -21,37 +21,35 @@
*/
package org.keycloak.services.resources;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.jose.jws.JWSInput;
import org.jboss.resteasy.jose.jws.crypto.RSAProvider;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.AbstractOAuthClient;
import org.keycloak.jaxrs.JaxrsOAuthClient;
import org.keycloak.models.*;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.email.EmailSender;
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.messages.Messages;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction;
import org.keycloak.services.resources.flows.Flows;
import org.keycloak.services.resources.flows.FormFlows;
import org.keycloak.services.resources.flows.Pages;
import org.keycloak.services.resources.flows.Urls;
import org.keycloak.services.validation.Validation;
import org.picketlink.idm.credential.util.TimeBasedOTP;
@@ -60,6 +58,10 @@ import org.picketlink.idm.credential.util.TimeBasedOTP;
*/
public class AccountService {
private static final Logger logger = Logger.getLogger(AccountService.class);
public static final String ACCOUNT_IDENTITY_COOKIE = "KEYCLOAK_ACCOUNT_IDENTITY";
private RealmModel realm;
@Context
@@ -72,50 +74,85 @@ public class AccountService {
private UriInfo uriInfo;
@Context
protected Providers providers;
private Providers providers;
protected AuthenticationManager authManager = new AuthenticationManager();
private AuthenticationManager authManager = new AuthenticationManager();
private ApplicationModel application;
private TokenManager tokenManager;
public AccountService(RealmModel realm, TokenManager tokenManager) {
public AccountService(RealmModel realm, ApplicationModel application, TokenManager tokenManager) {
this.realm = realm;
this.application = application;
this.tokenManager = tokenManager;
}
private Response forwardToPage(String path, String template) {
UserModel user = getUser(false);
if (user != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToForm(template);
} else {
return login(path);
}
}
@Path("")
@GET
public Response accountPage() {
return forwardToPage(null, Pages.ACCOUNT);
}
@Path("social")
@GET
public Response socialPage() {
return forwardToPage("social", Pages.SOCIAL);
}
@Path("totp")
@GET
public Response totpPage() {
return forwardToPage("totp", Pages.TOTP);
}
@Path("password")
@GET
public Response passwordPage() {
return forwardToPage("password", Pages.PASSWORD);
}
@Path("access")
@GET
public Response accessPage() {
UserModel user = getUserFromAuthManager();
if (user != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToAccess();
} else {
return Response.status(Status.FORBIDDEN).build();
}
return forwardToPage("access", Pages.ACCESS);
}
@Path("")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processAccountUpdate(final MultivaluedMap<String, String> formData) {
UserModel user = getUserFromAuthManager();
if (user == null) {
return Response.status(Status.FORBIDDEN).build();
UserModel user = getUser(true);
String error = Validation.validateUpdateProfileForm(formData);
if (error != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).setError(error).forwardToAccount();
}
user.setFirstName(formData.getFirst("firstName"));
user.setLastName(formData.getFirst("lastName"));
user.setEmail(formData.getFirst("email"));
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToAccount();
return Flows.forms(realm, request, uriInfo).setUser(user).setError("accountUpdated")
.setErrorType(FormFlows.MessageType.SUCCESS).forwardToAccount();
}
@Path("totp-remove")
@GET
public Response processTotpRemove() {
UserModel user = getUserFromAuthManager();
UserModel user = getUser(true);
user.setTotp(false);
return Flows.forms(realm, request, uriInfo).setError("successTotpRemoved").setErrorType(FormFlows.ErrorType.SUCCESS)
return Flows.forms(realm, request, uriInfo).setError("successTotpRemoved").setErrorType(FormFlows.MessageType.SUCCESS)
.setUser(user).forwardToTotp();
}
@@ -123,36 +160,26 @@ public class AccountService {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processTotpUpdate(final MultivaluedMap<String, String> formData) {
UserModel user = getUserFromAuthManager();
if (user == null) {
return Response.status(Status.FORBIDDEN).build();
}
FormFlows forms = Flows.forms(realm, request, uriInfo);
UserModel user = getUser(true);
String totp = formData.getFirst("totp");
String totpSecret = formData.getFirst("totpSecret");
String error = null;
FormFlows forms = Flows.forms(realm, request, uriInfo).setUser(user);
if (Validation.isEmpty(totp)) {
error = Messages.MISSING_TOTP;
return forms.setError(Messages.MISSING_TOTP).forwardToTotp();
} else if (!new TimeBasedOTP().validate(totp, totpSecret.getBytes())) {
error = Messages.INVALID_TOTP;
}
if (error != null) {
return forms.setError(error).setUser(user).forwardToTotp();
return forms.setError(Messages.INVALID_TOTP).forwardToTotp();
}
UserCredentialModel credentials = new UserCredentialModel();
credentials.setType(CredentialRepresentation.TOTP);
credentials.setValue(formData.getFirst("totpSecret"));
credentials.setValue(totpSecret);
realm.updateCredential(user, credentials);
user.setTotp(true);
return Flows.forms(realm, request, uriInfo).setError("successTotp").setErrorType(FormFlows.ErrorType.SUCCESS)
return Flows.forms(realm, request, uriInfo).setError("successTotp").setErrorType(FormFlows.MessageType.SUCCESS)
.setUser(user).forwardToTotp();
}
@@ -160,10 +187,7 @@ public class AccountService {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processPasswordUpdate(final MultivaluedMap<String, String> formData) {
UserModel user = getUserFromAuthManager();
if (user == null) {
return Response.status(Status.FORBIDDEN).build();
}
UserModel user = getUser(true);
FormFlows forms = Flows.forms(realm, request, uriInfo).setUser(user);
@@ -172,71 +196,133 @@ public class AccountService {
String passwordConfirm = formData.getFirst("password-confirm");
if (Validation.isEmpty(passwordNew)) {
forms.setError(Messages.MISSING_PASSWORD).forwardToPassword();
return forms.setError(Messages.MISSING_PASSWORD).forwardToPassword();
} else if (!passwordNew.equals(passwordConfirm)) {
forms.setError(Messages.INVALID_PASSWORD_CONFIRM).forwardToPassword();
return forms.setError(Messages.INVALID_PASSWORD_CONFIRM).forwardToPassword();
}
if (Validation.isEmpty(password)) {
forms.setError(Messages.MISSING_PASSWORD).forwardToPassword();
return forms.setError(Messages.MISSING_PASSWORD).forwardToPassword();
} else if (!realm.validatePassword(user, password)) {
forms.setError(Messages.INVALID_PASSWORD_EXISTING).forwardToPassword();
return forms.setError(Messages.INVALID_PASSWORD_EXISTING).forwardToPassword();
}
UserCredentialModel credentials = new UserCredentialModel();
credentials.setType(CredentialRepresentation.PASSWORD);
credentials.setValue(passwordNew);
realm.updateCredential(user, credentials);
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToPassword();
return Flows.forms(realm, request, uriInfo).setUser(user).setError("accountPasswordUpdated")
.setErrorType(FormFlows.MessageType.SUCCESS).forwardToPassword();
}
@Path("")
@Path("login-redirect")
@GET
public Response accountPage() {
UserModel user = getUserFromAuthManager();
if (user != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToAccount();
} else {
return Response.status(Status.FORBIDDEN).build();
public Response loginRedirect(@QueryParam("code") String code,
@QueryParam("state") String state,
@QueryParam("error") String error,
@Context HttpHeaders headers) {
try {
if (error != null) {
logger.debug("error from oauth");
throw new ForbiddenException("error");
}
if (!realm.isEnabled()) {
logger.debug("realm not enabled");
throw new ForbiddenException();
}
UserModel client = application.getApplicationUser();
if (!client.isEnabled() || !application.isEnabled()) {
logger.debug("account management app not enabled");
throw new ForbiddenException();
}
if (code == null) {
logger.debug("code not specified");
throw new BadRequestException();
}
if (state == null) {
logger.debug("state not specified");
throw new BadRequestException();
}
String path = new JaxrsOAuthClient().checkStateCookie(uriInfo, headers);
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
} catch (Exception ignored) {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
logger.debug("unverified access code");
throw new BadRequestException();
}
String key = input.readContent(String.class);
AccessCodeEntry accessCode = tokenManager.pullAccessCode(key);
if (accessCode == null) {
logger.debug("bad access code");
throw new BadRequestException();
}
if (accessCode.isExpired()) {
logger.debug("access code expired");
throw new BadRequestException();
}
if (!accessCode.getToken().isActive()) {
logger.debug("access token expired");
throw new BadRequestException();
}
if (!accessCode.getRealm().getId().equals(realm.getId())) {
logger.debug("bad realm");
throw new BadRequestException();
}
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) {
logger.debug("bad client");
throw new BadRequestException();
}
UriBuilder redirectBuilder = Urls.accountBase(uriInfo.getBaseUri());
if (path != null) {
redirectBuilder.path(path);
}
URI redirectUri = redirectBuilder.build(realm.getId());
NewCookie cookie = authManager.createAccountIdentityCookie(realm, accessCode.getUser(), Urls.accountBase(uriInfo.getBaseUri()).build(realm.getId()));
return Response.status(302).cookie(cookie).location(redirectUri).build();
} finally {
authManager.expireCookie(AbstractOAuthClient.OAUTH_TOKEN_REQUEST_STATE, uriInfo.getAbsolutePath().getPath());
}
}
@Path("social")
@Path("logout")
@GET
public Response socialPage() {
UserModel user = getUserFromAuthManager();
if (user != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToSocial();
} else {
return Response.status(Status.FORBIDDEN).build();
}
public Response logout() {
// TODO Should use single-sign out via TokenService
URI baseUri = Urls.accountBase(uriInfo.getBaseUri()).build(realm.getId());
authManager.expireIdentityCookie(realm, uriInfo);
authManager.expireAccountIdentityCookie(baseUri);
return Response.status(302).location(baseUri).build();
}
@Path("totp")
@GET
public Response totpPage() {
UserModel user = getUserFromAuthManager();
if (user != null) {
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToTotp();
} else {
return Response.status(Status.FORBIDDEN).build();
}
private Response login(String path) {
JaxrsOAuthClient oauth = new JaxrsOAuthClient();
String authUrl = Urls.realmLoginPage(uriInfo.getBaseUri(), realm.getId()).toString();
oauth.setAuthUrl(authUrl);
oauth.setClientId(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
URI accountUri = Urls.accountPageBuilder(uriInfo.getBaseUri()).path(AccountService.class, "loginRedirect").build(realm.getId());
oauth.setStateCookiePath(accountUri.getPath());
return oauth.redirect(uriInfo, accountUri.toString(), path);
}
@Path("password")
@GET
public Response passwordPage() {
UserModel user = getUserFromAuthManager();
if (user == null) {
return Response.status(Status.FORBIDDEN).build();
private UserModel getUser(boolean required) {
UserModel user = authManager.authenticateAccountIdentityCookie(realm, uriInfo, headers);
if (user == null && required) {
throw new ForbiddenException();
}
return Flows.forms(realm, request, uriInfo).setUser(user).forwardToPassword();
}
private UserModel getUserFromAuthManager() {
return authManager.authenticateIdentityCookie(realm, uriInfo, headers);
return user;
}
}
@@ -0,0 +1,43 @@
package org.keycloak.services.resources;
import java.util.Set;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.jboss.resteasy.spi.HttpRequest;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class Cors {
private HttpRequest request;
private ResponseBuilder response;
private Set<String> allowedOrigins;
public Cors(HttpRequest request, ResponseBuilder response) {
this.request = request;
this.response = response;
}
public static Cors add(HttpRequest request, ResponseBuilder response) {
return new Cors(request, response);
}
public Cors allowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
return this;
}
public Response build() {
String origin = request.getHttpHeaders().getHeaderString("Origin");
if (origin == null || allowedOrigins == null || (!allowedOrigins.contains(origin))) {
return response.build();
}
response.header("Access-Control-Allow-Origin", origin);
return response.build();
}
}
@@ -50,6 +50,7 @@ public class KeycloakApplication extends Application {
singletons.add(new SaasService(tokenManager));
singletons.add(new SocialResource(tokenManager, new SocialRequestManager()));
classes.add(SkeletonKeyContextResolver.class);
classes.add(QRCodeResource.class);
}
protected KeycloakSessionFactory createSessionFactory() {
@@ -0,0 +1,52 @@
package org.keycloak.services.resources;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.servlet.ServletException;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@Path("/qrcode")
public class QRCodeResource {
@GET
@Produces("image/png")
public Response createQrCode(@QueryParam("contents") String contents, @QueryParam("size") String size) throws ServletException, IOException, WriterException {
int width = 256;
int height = 256;
if (size != null) {
String[] s = size.split("x");
width = Integer.parseInt(s[0]);
height = Integer.parseInt(s[1]);
}
if (contents == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
QRCodeWriter writer = new QRCodeWriter();
final BitMatrix bitMatrix = writer.encode(contents, BarcodeFormat.QR_CODE, width, height);
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
MatrixToImageWriter.writeToStream(bitMatrix, "png", os);
}
};
return Response.ok(stream).build();
}
}
@@ -1,6 +1,8 @@
package org.keycloak.services.resources;
import org.jboss.resteasy.logging.Logger;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.Constants;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.TokenManager;
import org.keycloak.models.KeycloakSession;
@@ -66,7 +68,14 @@ public class RealmsResource {
logger.debug("realm not found");
throw new NotFoundException();
}
AccountService accountService = new AccountService(realm, tokenManager);
ApplicationModel application = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APPLICATION);
if (application == null || !application.isEnabled()) {
logger.debug("account management not enabled");
throw new NotFoundException();
}
AccountService accountService = new AccountService(realm, application, tokenManager);
resourceContext.initResource(accountService);
return accountService;
}
@@ -88,6 +88,12 @@ public class RequiredActionsService {
}
UserModel user = getUser(accessCode);
String error = Validation.validateUpdateProfileForm(formData);
if (error != null) {
return Flows.forms(realm, request, uriInfo).setError(error).forwardToAction(RequiredAction.UPDATE_PROFILE);
}
user.setFirstName(formData.getFirst("firstName"));
user.setLastName(formData.getFirst("lastName"));
user.setEmail(formData.getFirst("email"));
@@ -121,7 +127,7 @@ public class RequiredActionsService {
UserCredentialModel credentials = new UserCredentialModel();
credentials.setType(CredentialRepresentation.TOTP);
credentials.setValue(formData.getFirst("totpSecret"));
credentials.setValue(totpSecret);
realm.updateCredential(user, credentials);
user.setTotp(true);
@@ -146,15 +152,14 @@ public class RequiredActionsService {
UserModel user = getUser(accessCode);
String password = formData.getFirst("password");
String passwordNew = formData.getFirst("password-new");
String passwordConfirm = formData.getFirst("password-confirm");
FormFlows forms = Flows.forms(realm, request, uriInfo).setUser(user);
if (Validation.isEmpty(passwordNew)) {
forms.setError(Messages.MISSING_PASSWORD).forwardToAction(RequiredAction.UPDATE_PASSWORD);
return forms.setError(Messages.MISSING_PASSWORD).forwardToAction(RequiredAction.UPDATE_PASSWORD);
} else if (!passwordNew.equals(passwordConfirm)) {
forms.setError(Messages.MISSING_PASSWORD).forwardToAction(RequiredAction.UPDATE_PASSWORD);
return forms.setError(Messages.NOTMATCH_PASSWORD).forwardToAction(RequiredAction.UPDATE_PASSWORD);
}
UserCredentialModel credentials = new UserCredentialModel();
@@ -257,7 +262,7 @@ public class RequiredActionsService {
new EmailSender().sendPasswordReset(user, realm, accessCode, uriInfo);
return Flows.forms(realm, request, uriInfo).setError("emailSent").setErrorType(FormFlows.ErrorType.SUCCESS)
return Flows.forms(realm, request, uriInfo).setError("emailSent").setErrorType(FormFlows.MessageType.SUCCESS)
.forwardToPasswordReset();
}
@@ -415,7 +415,8 @@ public class TokenService {
}
logger.info("accessRequest SUCCESS");
AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
return Response.ok(res).build();
return Cors.add(request, Response.ok(res)).allowedOrigins(client.getWebOrigins()).build();
}
protected AccessTokenResponse accessTokenResponse(PrivateKey privateKey, SkeletonKeyToken token) {
@@ -34,6 +34,7 @@ import org.keycloak.services.managers.AccessCodeEntry;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction;
import org.keycloak.services.messages.Messages;
import org.picketlink.idm.model.sample.Realm;
import javax.imageio.spi.ServiceRegistry;
@@ -58,8 +59,8 @@ public class FormFlows {
// TODO refactor/rename "error" to "message" everywhere where it makes sense
private String error;
public static enum ErrorType {SUCCESS, WARNING, ERROR};
private ErrorType errorType;
public static enum MessageType {SUCCESS, WARNING, ERROR};
private MessageType messageType = MessageType.ERROR;
private MultivaluedMap<String, String> formData;
@@ -79,16 +80,17 @@ public class FormFlows {
}
public Response forwardToAction(RequiredAction action) {
switch (action) {
case CONFIGURE_TOTP:
return forwardToForm(Pages.LOGIN_CONFIG_TOTP);
return forwardToActionForm(Pages.LOGIN_CONFIG_TOTP, Messages.ACTION_WARN_TOTP);
case UPDATE_PROFILE:
return forwardToForm(Pages.LOGIN_UPDATE_PROFILE);
return forwardToActionForm(Pages.LOGIN_UPDATE_PROFILE, Messages.ACTION_WARN_PROFILE);
case UPDATE_PASSWORD:
return forwardToForm(Pages.LOGIN_UPDATE_PASSWORD);
return forwardToActionForm(Pages.LOGIN_UPDATE_PASSWORD, Messages.ACTION_WARN_PASSWD);
case VERIFY_EMAIL:
new EmailSender().sendEmailVerification(userModel, realm, accessCode, uriInfo);
return forwardToForm(Pages.LOGIN_VERIFY_EMAIL);
return forwardToActionForm(Pages.LOGIN_VERIFY_EMAIL, Messages.ACTION_WARN_EMAIL);
default:
return Response.serverError().build();
}
@@ -103,7 +105,6 @@ public class FormFlows {
}
private Response forwardToForm(String template, FormService.FormServiceDataBean formDataBean) {
formDataBean.setErrorType(errorType == null ? ErrorType.ERROR : errorType);
// Getting URI needed by form processing service
ResteasyUriInfo uriInfo = request.getUri();
@@ -140,11 +141,24 @@ public class FormFlows {
return Response.status(200).entity("form provider not found").build();
}
private Response forwardToForm(String template) {
public Response forwardToForm(String template) {
FormService.FormServiceDataBean formDataBean = new FormService.FormServiceDataBean(realm, userModel, formData, error);
return forwardToForm(template, formDataBean);
formDataBean.setMessageType(messageType);
return forwardToForm(template, formDataBean);
}
private Response forwardToActionForm(String template, String warningSummary) {
// If no other message is set, notify user about required action in the warning window
// so it's clear that this is a req. action form not a login form
if (error == null){
messageType = MessageType.WARNING;
error = warningSummary;
}
return forwardToForm(template);
}
public Response forwardToLogin() {
@@ -202,8 +216,8 @@ public class FormFlows {
return this;
}
public FormFlows setErrorType(ErrorType errorType) {
this.errorType = errorType;
public FormFlows setErrorType(MessageType errorType) {
this.messageType = errorType;
return this;
}
@@ -35,12 +35,16 @@ public class Urls {
return accountBase(baseUri).path(AccountService.class, "accessPage").build(realmId);
}
private static UriBuilder accountBase(URI baseUri) {
public static UriBuilder accountBase(URI baseUri) {
return realmBase(baseUri).path(RealmsResource.class, "getAccountService");
}
public static URI accountPage(URI baseUri, String realmId) {
return accountBase(baseUri).path(AccountService.class, "accountPage").build(realmId);
return accountPageBuilder(baseUri).build(realmId);
}
public static UriBuilder accountPageBuilder(URI baseUri) {
return accountBase(baseUri).path(AccountService.class, "accountPage");
}
public static URI accountPasswordPage(URI baseUri, String realmId) {
@@ -59,6 +63,10 @@ public class Urls {
return accountBase(baseUri).path(AccountService.class, "processTotpRemove").build(realmId);
}
public static URI accountLogout(URI baseUri, String realmId) {
return accountBase(baseUri).path(AccountService.class, "logout").build(realmId);
}
public static URI loginActionUpdatePassword(URI baseUri, String realmId) {
return requiredActionsBase(baseUri).path(RequiredActionsService.class, "updatePassword").build(realmId);
}
@@ -38,6 +38,22 @@ public class Validation {
return null;
}
public static String validateUpdateProfileForm(MultivaluedMap<String, String> formData) {
if (isEmpty(formData.getFirst("firstName"))) {
return Messages.MISSING_FIRST_NAME;
}
if (isEmpty(formData.getFirst("lastName"))) {
return Messages.MISSING_LAST_NAME;
}
if (isEmpty(formData.getFirst("email"))) {
return Messages.MISSING_EMAIL;
}
return null;
}
public static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
@@ -1,23 +1,20 @@
package org.keycloak.test;
import java.util.Iterator;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.*;
import org.keycloak.representations.idm.ApplicationRepresentation;
import org.keycloak.services.managers.ApplicationManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.resources.KeycloakApplication;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@@ -49,6 +46,9 @@ public class ApplicationModelTest extends AbstractKeycloakServerTest {
application.getApplicationUser().addRedirectUri("redirect-1");
application.getApplicationUser().addRedirectUri("redirect-2");
application.getApplicationUser().addWebOrigin("origin-1");
application.getApplicationUser().addWebOrigin("origin-2");
application.updateApplication();
}
@@ -85,6 +85,7 @@ public class ApplicationModelTest extends AbstractKeycloakServerTest {
UserModel euser = expected.getApplicationUser();
Assert.assertTrue(euser.getRedirectUris().containsAll(auser.getRedirectUris()));
Assert.assertTrue(euser.getWebOrigins().containsAll(auser.getWebOrigins()));
}
public static void assertEquals(List<RoleModel> expected, List<RoleModel> actual) {
@@ -53,10 +53,33 @@ public class UserModelTest extends AbstractKeycloakServerTest {
user.addRequiredAction(RequiredAction.CONFIGURE_TOTP);
user.addRequiredAction(RequiredAction.UPDATE_PASSWORD);
user.addWebOrigin("origin-1");
user.addWebOrigin("origin-2");
UserModel persisted = manager.getRealm(realm.getId()).getUser("user");
assertEquals(user, persisted);
}
@Test
public void webOriginSetTest() {
RealmModel realm = manager.createRealm("original");
UserModel user = realm.addUser("user");
Assert.assertTrue(user.getWebOrigins().isEmpty());
user.addWebOrigin("origin-1");
Assert.assertEquals(1, user.getWebOrigins().size());
user.addWebOrigin("origin-2");
Assert.assertEquals(2, user.getWebOrigins().size());
user.removeWebOrigin("origin-2");
Assert.assertEquals(1, user.getWebOrigins().size());
user.removeWebOrigin("origin-1");
Assert.assertTrue(user.getWebOrigins().isEmpty());
}
@Test
public void testUserRequiredActions() throws Exception {
@@ -102,7 +125,7 @@ public class UserModelTest extends AbstractKeycloakServerTest {
Assert.assertEquals(expected.getLastName(), actual.getLastName());
Assert.assertArrayEquals(expected.getRedirectUris().toArray(), actual.getRedirectUris().toArray());
Assert.assertArrayEquals(expected.getRequiredActions().toArray(), actual.getRequiredActions().toArray());
Assert.assertArrayEquals(expected.getWebOrigins().toArray(), actual.getWebOrigins().toArray());
}
public static void assertEquals(List<RoleModel> expected, List<RoleModel> actual) {