keycloak-aplcache

Merge pull request #1163 from patriot1burke/master broker

4/20/2015 4:01:02 PM

Details

diff --git a/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/AbstractClaimMapper.java b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/AbstractClaimMapper.java
new file mode 100755
index 0000000..f7ebf94
--- /dev/null
+++ b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/AbstractClaimMapper.java
@@ -0,0 +1,93 @@
+package org.keycloak.broker.oidc.mappers;
+
+import org.keycloak.broker.oidc.KeycloakOIDCIdentityProvider;
+import org.keycloak.broker.provider.AbstractIdentityProviderMapper;
+import org.keycloak.broker.provider.BrokeredIdentityContext;
+import org.keycloak.models.IdentityProviderMapperModel;
+import org.keycloak.provider.ProviderConfigProperty;
+import org.keycloak.representations.JsonWebToken;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public abstract class AbstractClaimMapper extends AbstractIdentityProviderMapper {
+    public static final String CLAIM = "claim";
+    public static final String CLAIM_VALUE = "claim.value";
+
+    public static Object getClaimValue(JsonWebToken token, String claim) {
+        String[] split = claim.split("\\.");
+        Map<String, Object> jsonObject = token.getOtherClaims();
+        for (int i = 0; i < split.length; i++) {
+            if (i == split.length - 1) {
+                return jsonObject.get(split[i]);
+            } else {
+                Object val = jsonObject.get(split[i]);
+                if (!(val instanceof Map)) return null;
+                jsonObject = (Map<String, Object>)val;
+            }
+        }
+        return null;
+    }
+
+    protected Object getClaimValue(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String claim = mapperModel.getConfig().get(CLAIM);
+        {  // search access token
+            JsonWebToken token = (JsonWebToken)context.getContextData().get(KeycloakOIDCIdentityProvider.VALIDATED_ACCESS_TOKEN);
+            if (token != null) {
+                Object value = getClaimValue(token, claim);
+                if (value != null) return value;
+            }
+
+        }
+        {  // search ID Token
+            JsonWebToken token = (JsonWebToken)context.getContextData().get(KeycloakOIDCIdentityProvider.VALIDATED_ID_TOKEN);
+            if (token != null) {
+                Object value = getClaimValue(token, claim);
+                if (value != null) return value;
+            }
+
+        }
+        return null;
+    }
+
+
+    protected boolean hasClaimValue(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        Object value = getClaimValue(mapperModel, context);
+        String desiredValue = mapperModel.getConfig().get(CLAIM_VALUE);
+        return valueEquals(desiredValue, value);
+    }
+
+    public boolean valueEquals(String desiredValue, Object value) {
+        if (value instanceof String) {
+            if (desiredValue.equals(value)) return true;
+        } else if (value instanceof Double) {
+            try {
+                if (Double.valueOf(desiredValue).equals(value)) return true;
+            } catch (Exception e) {
+
+            }
+        } else if (value instanceof Integer) {
+            try {
+                if (Integer.valueOf(desiredValue).equals(value)) return true;
+            } catch (Exception e) {
+
+            }
+        } else if (value instanceof Boolean) {
+            try {
+                if (Boolean.valueOf(desiredValue).equals(value)) return true;
+            } catch (Exception e) {
+
+            }
+        } else if (value instanceof List) {
+            List list = (List)value;
+            for (Object val : list) {
+                return valueEquals(desiredValue, val);
+            }
+        }
+        return false;
+    }
+}
diff --git a/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/RoleMapper.java b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/RoleMapper.java
index ff30b2f..7f47590 100755
--- a/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/RoleMapper.java
+++ b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/RoleMapper.java
@@ -1,9 +1,7 @@
 package org.keycloak.broker.oidc.mappers;
 
-import org.keycloak.broker.oidc.KeycloakOIDCIdentityProvider;
 import org.keycloak.broker.oidc.KeycloakOIDCIdentityProviderFactory;
 import org.keycloak.broker.oidc.OIDCIdentityProviderFactory;
-import org.keycloak.broker.provider.AbstractIdentityProviderMapper;
 import org.keycloak.broker.provider.BrokeredIdentityContext;
 import org.keycloak.broker.provider.IdentityBrokerException;
 import org.keycloak.models.ClientModel;
@@ -13,59 +11,37 @@ import org.keycloak.models.RealmModel;
 import org.keycloak.models.RoleModel;
 import org.keycloak.models.UserModel;
 import org.keycloak.provider.ProviderConfigProperty;
-import org.keycloak.representations.JsonWebToken;
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
 
 /**
  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
  * @version $Revision: 1 $
  */
-public class RoleMapper extends AbstractIdentityProviderMapper {
+public class RoleMapper extends AbstractClaimMapper {
 
     public static final String[] COMPATIBLE_PROVIDERS = {KeycloakOIDCIdentityProviderFactory.PROVIDER_ID, OIDCIdentityProviderFactory.PROVIDER_ID};
 
     private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();
 
     public static final String ROLE = "role";
-    public static final String CLAIM = "claim";
-
-    public static final String ID_TOKEN_CLAIM = "id.token.claim";
-
-    public static final String ACCESS_TOKEN_CLAIM = "access.token.claim";
-
-    public static final String CLAIM_VALUE = "claim.value";
 
     static {
         ProviderConfigProperty property;
-        property = new ProviderConfigProperty();
-        property.setName(CLAIM);
-        property.setLabel("Claim");
-        property.setHelpText("Name of claim to search for in token.  You can reference nested claims using a '.', i.e. 'address.locality'.");
-        property.setType(ProviderConfigProperty.STRING_TYPE);
-        configProperties.add(property);
-        property = new ProviderConfigProperty();
-        property.setName(CLAIM_VALUE);
-        property.setLabel("Claim Value");
-        property.setHelpText("Value the claim must have.  If the claim is an array, then the value must be contained in the array.");
-        property.setType(ProviderConfigProperty.STRING_TYPE);
-        configProperties.add(property);
-        property = new ProviderConfigProperty();
-        property.setName(ID_TOKEN_CLAIM);
-        property.setLabel("ID Token Claim");
-        property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
-        property.setDefaultValue("true");
-        property.setHelpText("If this claim is in ID Token, apply role.");
-        configProperties.add(property);
-        property = new ProviderConfigProperty();
-        property.setName(ACCESS_TOKEN_CLAIM);
-        property.setLabel("Access Token Claim");
-        property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
-        property.setDefaultValue("true");
-        property.setHelpText("If this claim is in Access Token, apply role.");
-        configProperties.add(property);
+        ProviderConfigProperty property1;
+        property1 = new ProviderConfigProperty();
+        property1.setName(CLAIM);
+        property1.setLabel("Claim");
+        property1.setHelpText("Name of claim to search for in token.  You can reference nested claims using a '.', i.e. 'address.locality'.");
+        property1.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property1);
+        property1 = new ProviderConfigProperty();
+        property1.setName(CLAIM_VALUE);
+        property1.setLabel("Claim Value");
+        property1.setHelpText("Value the claim must have.  If the claim is an array, then the value must be contained in the array.");
+        property1.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property1);
         property = new ProviderConfigProperty();
         property.setName(ROLE);
         property.setLabel("Role");
@@ -90,24 +66,6 @@ public class RoleMapper extends AbstractIdentityProviderMapper {
         }
     }
 
-    public static Object getClaimValue(JsonWebToken token, String claim) {
-        String[] split = claim.split("\\.");
-        Map<String, Object> jsonObject = token.getOtherClaims();
-        for (int i = 0; i < split.length; i++) {
-            if (i == split.length - 1) {
-                return jsonObject.get(split[i]);
-            } else {
-                Object val = jsonObject.get(split[i]);
-                if (!(val instanceof Map)) return null;
-                jsonObject = (Map<String, Object>)val;
-            }
-        }
-        return null;
-    }
-
-
-
-
 
     @Override
     public List<ProviderConfigProperty> getConfigProperties() {
@@ -126,18 +84,18 @@ public class RoleMapper extends AbstractIdentityProviderMapper {
 
     @Override
     public String getDisplayCategory() {
-        return "Role Mapper";
+        return "Role Importer";
     }
 
     @Override
     public String getDisplayType() {
-        return "Role Mapper";
+        return "Role Importer";
     }
 
     @Override
     public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
         String roleName = mapperModel.getConfig().get(ROLE);
-        if (isClaimPresent(mapperModel, context)) {
+        if (hasClaimValue(mapperModel, context)) {
             RoleModel role = getRoleFromString(realm, roleName);
             if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
             user.grantRole(role);
@@ -156,65 +114,10 @@ public class RoleMapper extends AbstractIdentityProviderMapper {
         return role;
     }
 
-    protected boolean isClaimPresent(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
-        boolean searchAccess = Boolean.valueOf(mapperModel.getConfig().get(ACCESS_TOKEN_CLAIM));
-        boolean searchId = Boolean.valueOf(mapperModel.getConfig().get(ID_TOKEN_CLAIM));
-        String claim = mapperModel.getConfig().get(CLAIM);
-        String desiredValue = mapperModel.getConfig().get(CLAIM_VALUE);
-
-        if (searchAccess) {
-            JsonWebToken token = (JsonWebToken)context.getContextData().get(KeycloakOIDCIdentityProvider.VALIDATED_ACCESS_TOKEN);
-            if (token != null) {
-                Object value = getClaimValue(token, claim);
-                if (valueEquals(desiredValue, value)) return true;
-            }
-
-        }
-        if (searchId) {
-            JsonWebToken token = (JsonWebToken)context.getContextData().get(KeycloakOIDCIdentityProvider.VALIDATED_ID_TOKEN);
-            if (token != null) {
-                Object value = getClaimValue(token, claim);
-                if (valueEquals(desiredValue, value)) return true;
-            }
-
-        }
-        return false;
-    }
-
-    public boolean valueEquals(String desiredValue, Object value) {
-        if (value instanceof String) {
-            if (desiredValue.equals(value)) return true;
-        } else if (value instanceof Double) {
-            try {
-                if (Double.valueOf(desiredValue).equals(value)) return true;
-            } catch (Exception e) {
-
-            }
-        } else if (value instanceof Integer) {
-            try {
-                if (Integer.valueOf(desiredValue).equals(value)) return true;
-            } catch (Exception e) {
-
-            }
-        } else if (value instanceof Boolean) {
-            try {
-                if (Boolean.valueOf(desiredValue).equals(value)) return true;
-            } catch (Exception e) {
-
-            }
-        } else if (value instanceof List) {
-            List list = (List)value;
-            for (Object val : list) {
-                return valueEquals(desiredValue, val);
-            }
-        }
-        return false;
-    }
-
     @Override
     public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
         String roleName = mapperModel.getConfig().get(ROLE);
-        if (!isClaimPresent(mapperModel, context)) {
+        if (!hasClaimValue(mapperModel, context)) {
             RoleModel role = getRoleFromString(realm, roleName);
             if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
             user.deleteRoleMapping(role);
diff --git a/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/UserAttributeMapper.java b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/UserAttributeMapper.java
new file mode 100755
index 0000000..72177ad
--- /dev/null
+++ b/broker/oidc/src/main/java/org/keycloak/broker/oidc/mappers/UserAttributeMapper.java
@@ -0,0 +1,100 @@
+package org.keycloak.broker.oidc.mappers;
+
+import org.keycloak.broker.oidc.KeycloakOIDCIdentityProviderFactory;
+import org.keycloak.broker.oidc.OIDCIdentityProviderFactory;
+import org.keycloak.broker.provider.BrokeredIdentityContext;
+import org.keycloak.broker.provider.IdentityBrokerException;
+import org.keycloak.models.ClientModel;
+import org.keycloak.models.IdentityProviderMapperModel;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.RealmModel;
+import org.keycloak.models.RoleModel;
+import org.keycloak.models.UserModel;
+import org.keycloak.provider.ProviderConfigProperty;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class UserAttributeMapper extends AbstractClaimMapper {
+
+    public static final String[] COMPATIBLE_PROVIDERS = {KeycloakOIDCIdentityProviderFactory.PROVIDER_ID, OIDCIdentityProviderFactory.PROVIDER_ID};
+
+    private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();
+
+    public static final String USER_ATTRIBUTE = "user.attribute.name";
+
+    static {
+        ProviderConfigProperty property;
+        ProviderConfigProperty property1;
+        property1 = new ProviderConfigProperty();
+        property1.setName(CLAIM);
+        property1.setLabel("Claim");
+        property1.setHelpText("Name of claim to search for in token.  You can reference nested claims using a '.', i.e. 'address.locality'.");
+        property1.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property1);
+        property = new ProviderConfigProperty();
+        property.setName(USER_ATTRIBUTE);
+        property.setLabel("User Attribute Name");
+        property.setHelpText("User attribute name to store claim.");
+        property.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property);
+    }
+
+    public static final String PROVIDER_ID = "oidc-user-attribute-idp-mapper";
+
+    @Override
+    public List<ProviderConfigProperty> getConfigProperties() {
+        return configProperties;
+    }
+
+    @Override
+    public String getId() {
+        return PROVIDER_ID;
+    }
+
+    @Override
+    public String[] getCompatibleProviders() {
+        return COMPATIBLE_PROVIDERS;
+    }
+
+    @Override
+    public String getDisplayCategory() {
+        return "Attribute Importer";
+    }
+
+    @Override
+    public String getDisplayType() {
+        return "Attribute Importer";
+    }
+
+    @Override
+    public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
+        Object value = getClaimValue(mapperModel, context);
+        if (value != null) {
+            user.setAttribute(attribute, value.toString());
+        }
+    }
+
+    @Override
+    public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
+        Object value = getClaimValue(mapperModel, context);
+        String current = user.getAttribute(attribute);
+        if (value != null && !value.equals(current)) {
+            user.setAttribute(attribute, value.toString());
+        } else if (value == null) {
+            user.removeAttribute(attribute);
+        }
+    }
+
+    @Override
+    public String getHelpText() {
+        return "Import declared claim if it exists in ID or access token into the specified user attribute.";
+    }
+
+}
diff --git a/broker/oidc/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper b/broker/oidc/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
index 98ce5f7..c2245b6 100755
--- a/broker/oidc/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
+++ b/broker/oidc/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
@@ -1 +1,2 @@
-org.keycloak.broker.oidc.mappers.RoleMapper
\ No newline at end of file
+org.keycloak.broker.oidc.mappers.RoleMapper
+org.keycloak.broker.oidc.mappers.UserAttributeMapper
\ No newline at end of file
diff --git a/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/RoleMapper.java b/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/RoleMapper.java
index 3c6d655..7181dfe 100755
--- a/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/RoleMapper.java
+++ b/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/RoleMapper.java
@@ -46,7 +46,7 @@ public class RoleMapper extends AbstractIdentityProviderMapper {
         configProperties.add(property);
         property = new ProviderConfigProperty();
         property.setName(ATTRIBUTE_FRIENDLY_NAME);
-        property.setLabel("Attribute Name");
+        property.setLabel("Friendly Name");
         property.setHelpText("Friendly name of attribute to search for in assertion.  You can leave this blank and specify a name instead.");
         property.setType(ProviderConfigProperty.STRING_TYPE);
         configProperties.add(property);
@@ -147,7 +147,6 @@ public class RoleMapper extends AbstractIdentityProviderMapper {
         return false;
     }
 
-
     @Override
     public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
         String roleName = mapperModel.getConfig().get(ROLE);
diff --git a/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/UserAttributeMapper.java b/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/UserAttributeMapper.java
new file mode 100755
index 0000000..e4d14b6
--- /dev/null
+++ b/broker/saml/src/main/java/org/keycloak/broker/saml/mappers/UserAttributeMapper.java
@@ -0,0 +1,129 @@
+package org.keycloak.broker.saml.mappers;
+
+import org.keycloak.broker.provider.AbstractIdentityProviderMapper;
+import org.keycloak.broker.provider.BrokeredIdentityContext;
+import org.keycloak.broker.provider.IdentityBrokerException;
+import org.keycloak.broker.saml.SAMLEndpoint;
+import org.keycloak.broker.saml.SAMLIdentityProviderFactory;
+import org.keycloak.dom.saml.v2.assertion.AssertionType;
+import org.keycloak.dom.saml.v2.assertion.AttributeStatementType;
+import org.keycloak.dom.saml.v2.assertion.AttributeType;
+import org.keycloak.models.ClientModel;
+import org.keycloak.models.IdentityProviderMapperModel;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.RealmModel;
+import org.keycloak.models.RoleModel;
+import org.keycloak.models.UserModel;
+import org.keycloak.provider.ProviderConfigProperty;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+ * @version $Revision: 1 $
+ */
+public class UserAttributeMapper extends AbstractIdentityProviderMapper {
+
+    public static final String[] COMPATIBLE_PROVIDERS = {SAMLIdentityProviderFactory.PROVIDER_ID};
+
+    private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();
+
+    public static final String ATTRIBUTE_NAME = "attribute.name";
+    public static final String ATTRIBUTE_FRIENDLY_NAME = "attribute.friendly.name";
+    public static final String USER_ATTRIBUTE = "user.attribute.name";
+
+    static {
+        ProviderConfigProperty property;
+        property = new ProviderConfigProperty();
+        property.setName(ATTRIBUTE_NAME);
+        property.setLabel("Attribute Name");
+        property.setHelpText("Name of attribute to search for in assertion.  You can leave this blank and specify a friendly name instead.");
+        property.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property);
+        property = new ProviderConfigProperty();
+        property.setName(ATTRIBUTE_FRIENDLY_NAME);
+        property.setLabel("Friendly Name");
+        property.setHelpText("Friendly name of attribute to search for in assertion.  You can leave this blank and specify a name instead.");
+        property.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property);
+        property = new ProviderConfigProperty();
+        property.setName(USER_ATTRIBUTE);
+        property.setLabel("User Attribute Name");
+        property.setHelpText("User attribute name to store saml attribute.");
+        property.setType(ProviderConfigProperty.STRING_TYPE);
+        configProperties.add(property);
+    }
+
+    public static final String PROVIDER_ID = "saml-user-attribute-idp-mapper";
+
+    @Override
+    public List<ProviderConfigProperty> getConfigProperties() {
+        return configProperties;
+    }
+
+    @Override
+    public String getId() {
+        return PROVIDER_ID;
+    }
+
+    @Override
+    public String[] getCompatibleProviders() {
+        return COMPATIBLE_PROVIDERS;
+    }
+
+    @Override
+    public String getDisplayCategory() {
+        return "Attribute Importer";
+    }
+
+    @Override
+    public String getDisplayType() {
+        return "Attribute Importer";
+    }
+
+    @Override
+    public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
+        Object value = getAttribute(mapperModel, context);
+        if (value != null) {
+            user.setAttribute(attribute, value.toString());
+        }
+    }
+
+    protected String getAttribute(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String name = mapperModel.getConfig().get(ATTRIBUTE_NAME);
+        if (name != null && name.trim().equals("")) name = null;
+        String friendly = mapperModel.getConfig().get(ATTRIBUTE_FRIENDLY_NAME);
+        if (friendly != null && friendly.trim().equals("")) friendly = null;
+        AssertionType assertion = (AssertionType)context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
+        for (AttributeStatementType statement : assertion.getAttributeStatements()) {
+            for (AttributeStatementType.ASTChoiceType choice : statement.getAttributes()) {
+                AttributeType attr = choice.getAttribute();
+                if (name != null && !name.equals(attr.getName())) continue;
+                if (friendly != null && !name.equals(attr.getFriendlyName())) continue;
+                return attr.getAttributeValue().get(0).toString();
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
+        String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
+        Object value = getAttribute(mapperModel, context);
+        String current = user.getAttribute(attribute);
+        if (value != null && !value.equals(current)) {
+            user.setAttribute(attribute, value.toString());
+        } else if (value == null) {
+            user.removeAttribute(attribute);
+        }
+
+    }
+
+    @Override
+    public String getHelpText() {
+        return "Import declared saml attribute if it exists in assertion into the specified user attribute.";
+    }
+
+}
diff --git a/broker/saml/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper b/broker/saml/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
index af14a9c..5051d1d 100755
--- a/broker/saml/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
+++ b/broker/saml/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper
@@ -1 +1,2 @@
-org.keycloak.broker.saml.mappers.RoleMapper
\ No newline at end of file
+org.keycloak.broker.saml.mappers.RoleMapper
+org.keycloak.broker.saml.mappers.UserAttributeMapper
\ No newline at end of file
diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js
index c5479e0..35a959c 100755
--- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js
+++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js
@@ -1436,7 +1436,7 @@ module.controller('IdentityProviderMapperCtrl', function($scope, realm,  identit
     $scope.save = function() {
         IdentityProviderMapper.update({
             realm : realm.realm,
-            client: client.id,
+            alias: identityProvider.alias,
             mapperId : mapper.id
         }, $scope.mapper, function() {
             $scope.changed = false;
diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js
index 6703973..ce209a6 100755
--- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js
+++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js
@@ -1025,6 +1025,10 @@ module.factory('IdentityProviderMapper', function($resource) {
         realm : '@realm',
         alias : '@alias',
         mapperId: '@mapperId'
+    }, {
+        update: {
+            method : 'PUT'
+        }
     });
 });
 
diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/account/AccountTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/account/AccountTest.java
index 1d99e1f..8ba95d2 100755
--- a/testsuite/integration/src/test/java/org/keycloak/testsuite/account/AccountTest.java
+++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/account/AccountTest.java
@@ -1,520 +1,520 @@
-/*
- * 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.testsuite.account;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.keycloak.events.Details;
-import org.keycloak.events.Event;
-import org.keycloak.events.EventType;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.PasswordPolicy;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserCredentialModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.utils.TimeBasedOTP;
-import org.keycloak.representations.idm.CredentialRepresentation;
-import org.keycloak.services.managers.RealmManager;
-import org.keycloak.services.resources.AccountService;
-import org.keycloak.services.resources.RealmsResource;
-import org.keycloak.testsuite.AssertEvents;
-import org.keycloak.testsuite.OAuthClient;
-import org.keycloak.testsuite.pages.AccountLogPage;
-import org.keycloak.testsuite.pages.AccountPasswordPage;
-import org.keycloak.testsuite.pages.AccountSessionsPage;
-import org.keycloak.testsuite.pages.AccountTotpPage;
-import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.pages.AppPage.RequestType;
-import org.keycloak.testsuite.pages.ErrorPage;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.pages.RegisterPage;
-import org.keycloak.testsuite.rule.KeycloakRule;
-import org.keycloak.testsuite.rule.KeycloakRule.KeycloakSetup;
-import org.keycloak.testsuite.rule.WebResource;
-import org.keycloak.testsuite.rule.WebRule;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-
-import javax.ws.rs.core.UriBuilder;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class AccountTest {
-
-    @ClassRule
-    public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakSetup() {
-        @Override
-        public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-            UserModel user = manager.getSession().users().getUserByUsername("test-user@localhost", appRealm);
-
-            ClientModel accountApp = appRealm.getClientNameMap().get(org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
-
-            UserModel user2 = manager.getSession().users().addUser(appRealm, "test-user-no-access@localhost");
-            user2.setEnabled(true);
-            for (String r : accountApp.getDefaultRoles()) {
-                user2.deleteRoleMapping(accountApp.getRole(r));
-            }
-            UserCredentialModel creds = new UserCredentialModel();
-            creds.setType(CredentialRepresentation.PASSWORD);
-            creds.setValue("password");
-            user2.updateCredential(creds);
-        }
-    });
-
-    private static final UriBuilder BASE = UriBuilder.fromUri("http://localhost:8081/auth");
-    private static final String ACCOUNT_URL = RealmsResource.accountUrl(BASE.clone()).build("test").toString();
-    public static String ACCOUNT_REDIRECT = AccountService.loginRedirectUrl(BASE.clone()).build("test").toString();
-
-    @Rule
-    public AssertEvents events = new AssertEvents(keycloakRule);
-
-    @Rule
-    public WebRule webRule = new WebRule(this);
-
-    @WebResource
-    protected WebDriver driver;
-
-    @WebResource
-    protected OAuthClient oauth;
-
-    @WebResource
-    protected AppPage appPage;
-
-    @WebResource
-    protected LoginPage loginPage;
-
-    @WebResource
-    protected RegisterPage registerPage;
-
-    @WebResource
-    protected AccountPasswordPage changePasswordPage;
-
-    @WebResource
-    protected AccountUpdateProfilePage profilePage;
-
-    @WebResource
-    protected AccountTotpPage totpPage;
-
-    @WebResource
-    protected AccountLogPage logPage;
-
-    @WebResource
-    protected AccountSessionsPage sessionsPage;
-
-    @WebResource
-    protected ErrorPage errorPage;
-
-    private TimeBasedOTP totp = new TimeBasedOTP();
-    private String userId;
-
-    @Before
-    public void before() {
-        oauth.state("mystate"); // keycloak enforces that a state param has been sent by client
-        userId = keycloakRule.getUser("test", "test-user@localhost").getId();
-    }
-
-    @After
-    public void after() {
-        keycloakRule.update(new KeycloakSetup() {
-            @Override
-            public void config(RealmManager manager, RealmModel defaultRealm, RealmModel appRealm) {
-                UserModel user = manager.getSession().users().getUserByUsername("test-user@localhost", appRealm);
-
-                UserCredentialModel cred = new UserCredentialModel();
-                cred.setType(CredentialRepresentation.PASSWORD);
-                cred.setValue("password");
-
-                user.updateCredential(cred);
-            }
-        });
-    }
-
-    //@Test
-    public void ideTesting() throws Exception {
-        Thread.sleep(100000000);
-    }
-
-    @Test
-    public void returnToAppFromQueryParam() {
-        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app");
-        loginPage.login("test-user@localhost", "password");
-        Assert.assertTrue(profilePage.isCurrent());
-        profilePage.backToApplication();
-
-        Assert.assertTrue(appPage.isCurrent());
-
-        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app&referrer_uri=http://localhost:8081/app?test");
-        Assert.assertTrue(profilePage.isCurrent());
-        profilePage.backToApplication();
-
-        Assert.assertTrue(appPage.isCurrent());
-        Assert.assertEquals(appPage.baseUrl + "?test", driver.getCurrentUrl());
-
-        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app");
-        Assert.assertTrue(profilePage.isCurrent());
-
-        driver.findElement(By.linkText("Authenticator")).click();
-        Assert.assertTrue(totpPage.isCurrent());
-
-        driver.findElement(By.linkText("Account")).click();
-        Assert.assertTrue(profilePage.isCurrent());
-
-        profilePage.backToApplication();
-
-        Assert.assertTrue(appPage.isCurrent());
-
-        events.clear();
-    }
-
-    @Test
-    public void changePassword() {
-        changePasswordPage.open();
-        loginPage.login("test-user@localhost", "password");
-
-        String sessionId = events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent().getSessionId();
-
-        changePasswordPage.changePassword("", "new-password", "new-password");
-
-        Assert.assertEquals("Please specify password.", profilePage.getError());
-
-        changePasswordPage.changePassword("password", "new-password", "new-password2");
-
-        Assert.assertEquals("Password confirmation doesn't match.", profilePage.getError());
-
-        changePasswordPage.changePassword("password", "new-password", "new-password");
-
-        Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
-
-        events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
-
-        changePasswordPage.logout();
-
-        events.expectLogout(sessionId).detail(Details.REDIRECT_URI, changePasswordPage.getPath()).assertEvent();
-
-        loginPage.open();
-        loginPage.login("test-user@localhost", "password");
-
-        Assert.assertEquals("Invalid username or password.", loginPage.getError());
-
-        events.expectLogin().session((String) null).error("invalid_user_credentials").assertEvent();
-
-        loginPage.open();
-        loginPage.login("test-user@localhost", "new-password");
-
-        Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
-
-        events.expectLogin().assertEvent();
-    }
-
-    @Test
-    public void changePasswordWithLengthPasswordPolicy() {
-        keycloakRule.update(new KeycloakRule.KeycloakSetup() {
-            @Override
-            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                appRealm.setPasswordPolicy(new PasswordPolicy("length"));
-            }
-        });
-
-        try {
-            changePasswordPage.open();
-            loginPage.login("test-user@localhost", "password");
-
-
-            events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent();
-
-            changePasswordPage.changePassword("", "new", "new");
-
-            Assert.assertEquals("Please specify password.", profilePage.getError());
-
-            changePasswordPage.changePassword("password", "new-password", "new-password");
-
-            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
-
-            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
-        } finally {
-            keycloakRule.update(new KeycloakRule.KeycloakSetup() {
-                @Override
-                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                    appRealm.setPasswordPolicy(new PasswordPolicy(null));
-                }
-            });
-        }
-    }
-    
-    @Test
-    public void changePasswordWithPasswordHistoryPolicy() {
-        keycloakRule.update(new KeycloakRule.KeycloakSetup() {
-            @Override
-            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                appRealm.setPasswordPolicy(new PasswordPolicy("passwordHistory(2)"));
-            }
-        });
-
-        try {
-            changePasswordPage.open();
-            loginPage.login("test-user@localhost", "password");
-
-            events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent();
-
-            changePasswordPage.changePassword("password", "password", "password");
-
-            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
-
-            changePasswordPage.changePassword("password", "password1", "password1");
-
-            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
-            
-            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
-            
-            changePasswordPage.changePassword("password1", "password", "password");
-
-            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
-
-            changePasswordPage.changePassword("password1", "password1", "password1");
-
-            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
-            
-            changePasswordPage.changePassword("password1", "password2", "password2");
-
-            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
-
-            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
-            
-        } finally {
-            keycloakRule.update(new KeycloakRule.KeycloakSetup() {
-                @Override
-                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                    appRealm.setPasswordPolicy(new PasswordPolicy(null));
-                }
-            });
-        }
-    }
-
-    @Test
-    public void changeProfile() {
-        profilePage.open();
-        loginPage.login("test-user@localhost", "password");
-
-        events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT).assertEvent();
-
-        Assert.assertEquals("Tom", profilePage.getFirstName());
-        Assert.assertEquals("Brady", profilePage.getLastName());
-        Assert.assertEquals("test-user@localhost", profilePage.getEmail());
-
-        // All fields are required, so there should be an error when something is missing.
-        profilePage.updateProfile("", "New last", "new@email.com");
-
-        Assert.assertEquals("Please specify first name.", profilePage.getError());
-        Assert.assertEquals("", profilePage.getFirstName());
-        Assert.assertEquals("New last", profilePage.getLastName());
-        Assert.assertEquals("new@email.com", profilePage.getEmail());
-
-        events.assertEmpty();
-
-        profilePage.updateProfile("New first", "", "new@email.com");
-
-        Assert.assertEquals("Please specify last name.", profilePage.getError());
-        Assert.assertEquals("New first", profilePage.getFirstName());
-        Assert.assertEquals("", profilePage.getLastName());
-        Assert.assertEquals("new@email.com", profilePage.getEmail());
-
-        events.assertEmpty();
-
-        profilePage.updateProfile("New first", "New last", "");
-
-        Assert.assertEquals("Please specify email.", profilePage.getError());
-        Assert.assertEquals("New first", profilePage.getFirstName());
-        Assert.assertEquals("New last", profilePage.getLastName());
-        Assert.assertEquals("", profilePage.getEmail());
-
-        events.assertEmpty();
-
-        profilePage.clickCancel();
-
-        Assert.assertEquals("Tom", profilePage.getFirstName());
-        Assert.assertEquals("Brady", profilePage.getLastName());
-        Assert.assertEquals("test-user@localhost", profilePage.getEmail());
-
-        events.assertEmpty();
-
-        profilePage.updateProfile("New first", "New last", "new@email.com");
-
-        Assert.assertEquals("Your account has been updated.", profilePage.getSuccess());
-        Assert.assertEquals("New first", profilePage.getFirstName());
-        Assert.assertEquals("New last", profilePage.getLastName());
-        Assert.assertEquals("new@email.com", profilePage.getEmail());
-
-        events.expectAccount(EventType.UPDATE_PROFILE).assertEvent();
-        events.expectAccount(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "new@email.com").assertEvent();
-    }
-
-    @Test
-    public void setupTotp() {
-        totpPage.open();
-        loginPage.login("test-user@localhost", "password");
-
-        events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=totp").assertEvent();
-
-        Assert.assertTrue(totpPage.isCurrent());
-
-        Assert.assertFalse(driver.getPageSource().contains("Remove Google"));
-
-        // Error with false code
-        totpPage.configure(totp.generate(totpPage.getTotpSecret() + "123"));
-
-        Assert.assertEquals("Invalid authenticator code.", profilePage.getError());
-
-        totpPage.configure(totp.generate(totpPage.getTotpSecret()));
-
-        Assert.assertEquals("Mobile authenticator configured.", profilePage.getSuccess());
-
-        events.expectAccount(EventType.UPDATE_TOTP).assertEvent();
-
-        Assert.assertTrue(driver.getPageSource().contains("pficon-delete"));
-
-        totpPage.removeTotp();
-
-        events.expectAccount(EventType.REMOVE_TOTP).assertEvent();
-    }
-
-    @Test
-    public void changeProfileNoAccess() throws Exception {
-        profilePage.open();
-        loginPage.login("test-user-no-access@localhost", "password");
-
-        events.expectLogin().client("account").user(keycloakRule.getUser("test", "test-user-no-access@localhost").getId())
-                .detail(Details.USERNAME, "test-user-no-access@localhost")
-                .detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT).assertEvent();
-
-        Assert.assertTrue(errorPage.isCurrent());
-        Assert.assertEquals("No access", errorPage.getError());
-    }
-
-    @Test
-    public void viewLog() {
-        keycloakRule.update(new KeycloakSetup() {
-            @Override
-            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                appRealm.setEventsEnabled(true);
-            }
-        });
-
-        try {
-            List<Event> expectedEvents = new LinkedList<Event>();
-
-            loginPage.open();
-            loginPage.clickRegister();
-
-            registerPage.register("view", "log", "view-log@localhost", "view-log", "password", "password");
-
-            expectedEvents.add(events.poll());
-            expectedEvents.add(events.poll());
-
-            profilePage.open();
-            profilePage.updateProfile("view", "log2", "view-log@localhost");
-
-            expectedEvents.add(events.poll());
-
-            logPage.open();
-
-            Assert.assertTrue(logPage.isCurrent());
-
-            List<List<String>> actualEvents = logPage.getEvents();
-
-            Assert.assertEquals(expectedEvents.size(), actualEvents.size());
-
-            for (Event e : expectedEvents) {
-                boolean match = false;
-                for (List<String> a : logPage.getEvents()) {
-                    if (e.getType().toString().replace('_', ' ').toLowerCase().equals(a.get(1)) &&
-                            e.getIpAddress().equals(a.get(2)) &&
-                            e.getClientId().equals(a.get(3))) {
-                        match = true;
-                        break;
-                    }
-                }
-                if (!match) {
-                    Assert.fail("Event not found " + e.getType());
-                }
-            }
-        } finally {
-            keycloakRule.update(new KeycloakSetup() {
-                @Override
-                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
-                    appRealm.setEventsEnabled(false);
-                }
-            });
-        }
-    }
-
-    @Test
-    public void sessions() {
-        loginPage.open();
-        loginPage.clickRegister();
-
-        registerPage.register("view", "sessions", "view-sessions@localhost", "view-sessions", "password", "password");
-
-        Event registerEvent = events.expectRegister("view-sessions", "view-sessions@localhost").assertEvent();
-        String userId = registerEvent.getUserId();
-
-        events.expectLogin().user(userId).detail(Details.USERNAME, "view-sessions").assertEvent();
-
-        sessionsPage.open();
-
-        Assert.assertTrue(sessionsPage.isCurrent());
-
-        List<List<String>> sessions = sessionsPage.getSessions();
-        Assert.assertEquals(1, sessions.size());
-        Assert.assertEquals("127.0.0.1", sessions.get(0).get(0));
-
-        // Create second session
-        WebDriver driver2 = WebRule.createWebDriver();
-        try {
-            OAuthClient oauth2 = new OAuthClient(driver2);
-            oauth2.state("mystate");
-            oauth2.doLogin("view-sessions", "password");
-
-            Event login2Event = events.expectLogin().user(userId).detail(Details.USERNAME, "view-sessions").assertEvent();
-
-            sessionsPage.open();
-            sessions = sessionsPage.getSessions();
-            Assert.assertEquals(2, sessions.size());
-
-            sessionsPage.logoutAll();
-
-            events.expectLogout(registerEvent.getSessionId());
-            events.expectLogout(login2Event.getSessionId());
-        } finally {
-            driver2.close();
-        }
-    }
-
-}
+/*
+ * 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.testsuite.account;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.keycloak.events.Details;
+import org.keycloak.events.Event;
+import org.keycloak.events.EventType;
+import org.keycloak.models.ClientModel;
+import org.keycloak.models.PasswordPolicy;
+import org.keycloak.models.RealmModel;
+import org.keycloak.models.UserCredentialModel;
+import org.keycloak.models.UserModel;
+import org.keycloak.models.utils.TimeBasedOTP;
+import org.keycloak.representations.idm.CredentialRepresentation;
+import org.keycloak.services.managers.RealmManager;
+import org.keycloak.services.resources.AccountService;
+import org.keycloak.services.resources.RealmsResource;
+import org.keycloak.testsuite.AssertEvents;
+import org.keycloak.testsuite.OAuthClient;
+import org.keycloak.testsuite.pages.AccountLogPage;
+import org.keycloak.testsuite.pages.AccountPasswordPage;
+import org.keycloak.testsuite.pages.AccountSessionsPage;
+import org.keycloak.testsuite.pages.AccountTotpPage;
+import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
+import org.keycloak.testsuite.pages.AppPage;
+import org.keycloak.testsuite.pages.AppPage.RequestType;
+import org.keycloak.testsuite.pages.ErrorPage;
+import org.keycloak.testsuite.pages.LoginPage;
+import org.keycloak.testsuite.pages.RegisterPage;
+import org.keycloak.testsuite.rule.KeycloakRule;
+import org.keycloak.testsuite.rule.KeycloakRule.KeycloakSetup;
+import org.keycloak.testsuite.rule.WebResource;
+import org.keycloak.testsuite.rule.WebRule;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+
+import javax.ws.rs.core.UriBuilder;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+ */
+public class AccountTest {
+
+    @ClassRule
+    public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakSetup() {
+        @Override
+        public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+            UserModel user = manager.getSession().users().getUserByUsername("test-user@localhost", appRealm);
+
+            ClientModel accountApp = appRealm.getClientNameMap().get(org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
+
+            UserModel user2 = manager.getSession().users().addUser(appRealm, "test-user-no-access@localhost");
+            user2.setEnabled(true);
+            for (String r : accountApp.getDefaultRoles()) {
+                user2.deleteRoleMapping(accountApp.getRole(r));
+            }
+            UserCredentialModel creds = new UserCredentialModel();
+            creds.setType(CredentialRepresentation.PASSWORD);
+            creds.setValue("password");
+            user2.updateCredential(creds);
+        }
+    });
+
+    private static final UriBuilder BASE = UriBuilder.fromUri("http://localhost:8081/auth");
+    private static final String ACCOUNT_URL = RealmsResource.accountUrl(BASE.clone()).build("test").toString();
+    public static String ACCOUNT_REDIRECT = AccountService.loginRedirectUrl(BASE.clone()).build("test").toString();
+
+    @Rule
+    public AssertEvents events = new AssertEvents(keycloakRule);
+
+    @Rule
+    public WebRule webRule = new WebRule(this);
+
+    @WebResource
+    protected WebDriver driver;
+
+    @WebResource
+    protected OAuthClient oauth;
+
+    @WebResource
+    protected AppPage appPage;
+
+    @WebResource
+    protected LoginPage loginPage;
+
+    @WebResource
+    protected RegisterPage registerPage;
+
+    @WebResource
+    protected AccountPasswordPage changePasswordPage;
+
+    @WebResource
+    protected AccountUpdateProfilePage profilePage;
+
+    @WebResource
+    protected AccountTotpPage totpPage;
+
+    @WebResource
+    protected AccountLogPage logPage;
+
+    @WebResource
+    protected AccountSessionsPage sessionsPage;
+
+    @WebResource
+    protected ErrorPage errorPage;
+
+    private TimeBasedOTP totp = new TimeBasedOTP();
+    private String userId;
+
+    @Before
+    public void before() {
+        oauth.state("mystate"); // keycloak enforces that a state param has been sent by client
+        userId = keycloakRule.getUser("test", "test-user@localhost").getId();
+    }
+
+    @After
+    public void after() {
+        keycloakRule.update(new KeycloakSetup() {
+            @Override
+            public void config(RealmManager manager, RealmModel defaultRealm, RealmModel appRealm) {
+                UserModel user = manager.getSession().users().getUserByUsername("test-user@localhost", appRealm);
+
+                UserCredentialModel cred = new UserCredentialModel();
+                cred.setType(CredentialRepresentation.PASSWORD);
+                cred.setValue("password");
+
+                user.updateCredential(cred);
+            }
+        });
+    }
+
+    //@Test
+    public void ideTesting() throws Exception {
+        Thread.sleep(100000000);
+    }
+
+    @Test
+    public void returnToAppFromQueryParam() {
+        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app");
+        loginPage.login("test-user@localhost", "password");
+        Assert.assertTrue(profilePage.isCurrent());
+        profilePage.backToApplication();
+
+        Assert.assertTrue(appPage.isCurrent());
+
+        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app&referrer_uri=http://localhost:8081/app?test");
+        Assert.assertTrue(profilePage.isCurrent());
+        profilePage.backToApplication();
+
+        Assert.assertTrue(appPage.isCurrent());
+        Assert.assertEquals(appPage.baseUrl + "?test", driver.getCurrentUrl());
+
+        driver.navigate().to(AccountUpdateProfilePage.PATH + "?referrer=test-app");
+        Assert.assertTrue(profilePage.isCurrent());
+
+        driver.findElement(By.linkText("Authenticator")).click();
+        Assert.assertTrue(totpPage.isCurrent());
+
+        driver.findElement(By.linkText("Account")).click();
+        Assert.assertTrue(profilePage.isCurrent());
+
+        profilePage.backToApplication();
+
+        Assert.assertTrue(appPage.isCurrent());
+
+        events.clear();
+    }
+
+    @Test
+    public void changePassword() {
+        changePasswordPage.open();
+        loginPage.login("test-user@localhost", "password");
+
+        String sessionId = events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent().getSessionId();
+
+        changePasswordPage.changePassword("", "new-password", "new-password");
+
+        Assert.assertEquals("Please specify password.", profilePage.getError());
+
+        changePasswordPage.changePassword("password", "new-password", "new-password2");
+
+        Assert.assertEquals("Password confirmation doesn't match.", profilePage.getError());
+
+        changePasswordPage.changePassword("password", "new-password", "new-password");
+
+        Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+
+        events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
+
+        changePasswordPage.logout();
+
+        events.expectLogout(sessionId).detail(Details.REDIRECT_URI, changePasswordPage.getPath()).assertEvent();
+
+        loginPage.open();
+        loginPage.login("test-user@localhost", "password");
+
+        Assert.assertEquals("Invalid username or password.", loginPage.getError());
+
+        events.expectLogin().session((String) null).error("invalid_user_credentials").assertEvent();
+
+        loginPage.open();
+        loginPage.login("test-user@localhost", "new-password");
+
+        Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
+
+        events.expectLogin().assertEvent();
+    }
+
+    @Test
+    public void changePasswordWithLengthPasswordPolicy() {
+        keycloakRule.update(new KeycloakRule.KeycloakSetup() {
+            @Override
+            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                appRealm.setPasswordPolicy(new PasswordPolicy("length"));
+            }
+        });
+
+        try {
+            changePasswordPage.open();
+            loginPage.login("test-user@localhost", "password");
+
+
+            events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent();
+
+            changePasswordPage.changePassword("", "new", "new");
+
+            Assert.assertEquals("Please specify password.", profilePage.getError());
+
+            changePasswordPage.changePassword("password", "new-password", "new-password");
+
+            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+
+            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
+        } finally {
+            keycloakRule.update(new KeycloakRule.KeycloakSetup() {
+                @Override
+                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                    appRealm.setPasswordPolicy(new PasswordPolicy(null));
+                }
+            });
+        }
+    }
+    
+    @Test
+    public void changePasswordWithPasswordHistoryPolicy() {
+        keycloakRule.update(new KeycloakRule.KeycloakSetup() {
+            @Override
+            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                appRealm.setPasswordPolicy(new PasswordPolicy("passwordHistory(2)"));
+            }
+        });
+
+        try {
+            changePasswordPage.open();
+            loginPage.login("test-user@localhost", "password");
+
+            events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=password").assertEvent();
+
+            changePasswordPage.changePassword("password", "password", "password");
+
+            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
+
+            changePasswordPage.changePassword("password", "password1", "password1");
+
+            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+            
+            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
+            
+            changePasswordPage.changePassword("password1", "password", "password");
+
+            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
+
+            changePasswordPage.changePassword("password1", "password1", "password1");
+
+            Assert.assertEquals("Invalid password: must not be equal to any of last 2 passwords.", profilePage.getError());
+            
+            changePasswordPage.changePassword("password1", "password2", "password2");
+
+            Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+
+            events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
+            
+        } finally {
+            keycloakRule.update(new KeycloakRule.KeycloakSetup() {
+                @Override
+                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                    appRealm.setPasswordPolicy(new PasswordPolicy(null));
+                }
+            });
+        }
+    }
+
+    @Test
+    public void changeProfile() {
+        profilePage.open();
+        loginPage.login("test-user@localhost", "password");
+
+        events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT).assertEvent();
+
+        Assert.assertEquals("Tom", profilePage.getFirstName());
+        Assert.assertEquals("Brady", profilePage.getLastName());
+        Assert.assertEquals("test-user@localhost", profilePage.getEmail());
+
+        // All fields are required, so there should be an error when something is missing.
+        profilePage.updateProfile("", "New last", "new@email.com");
+
+        Assert.assertEquals("Please specify first name.", profilePage.getError());
+        Assert.assertEquals("", profilePage.getFirstName());
+        Assert.assertEquals("New last", profilePage.getLastName());
+        Assert.assertEquals("new@email.com", profilePage.getEmail());
+
+        events.assertEmpty();
+
+        profilePage.updateProfile("New first", "", "new@email.com");
+
+        Assert.assertEquals("Please specify last name.", profilePage.getError());
+        Assert.assertEquals("New first", profilePage.getFirstName());
+        Assert.assertEquals("", profilePage.getLastName());
+        Assert.assertEquals("new@email.com", profilePage.getEmail());
+
+        events.assertEmpty();
+
+        profilePage.updateProfile("New first", "New last", "");
+
+        Assert.assertEquals("Please specify email.", profilePage.getError());
+        Assert.assertEquals("New first", profilePage.getFirstName());
+        Assert.assertEquals("New last", profilePage.getLastName());
+        Assert.assertEquals("", profilePage.getEmail());
+
+        events.assertEmpty();
+
+        profilePage.clickCancel();
+
+        Assert.assertEquals("Tom", profilePage.getFirstName());
+        Assert.assertEquals("Brady", profilePage.getLastName());
+        Assert.assertEquals("test-user@localhost", profilePage.getEmail());
+
+        events.assertEmpty();
+
+        profilePage.updateProfile("New first", "New last", "new@email.com");
+
+        Assert.assertEquals("Your account has been updated.", profilePage.getSuccess());
+        Assert.assertEquals("New first", profilePage.getFirstName());
+        Assert.assertEquals("New last", profilePage.getLastName());
+        Assert.assertEquals("new@email.com", profilePage.getEmail());
+
+        events.expectAccount(EventType.UPDATE_PROFILE).assertEvent();
+        events.expectAccount(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "new@email.com").assertEvent();
+    }
+
+    @Test
+    public void setupTotp() {
+        totpPage.open();
+        loginPage.login("test-user@localhost", "password");
+
+        events.expectLogin().client("account").detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT + "?path=totp").assertEvent();
+
+        Assert.assertTrue(totpPage.isCurrent());
+
+        Assert.assertFalse(driver.getPageSource().contains("Remove Google"));
+
+        // Error with false code
+        totpPage.configure(totp.generate(totpPage.getTotpSecret() + "123"));
+
+        Assert.assertEquals("Invalid authenticator code.", profilePage.getError());
+
+        totpPage.configure(totp.generate(totpPage.getTotpSecret()));
+
+        Assert.assertEquals("Mobile authenticator configured.", profilePage.getSuccess());
+
+        events.expectAccount(EventType.UPDATE_TOTP).assertEvent();
+
+        Assert.assertTrue(driver.getPageSource().contains("pficon-delete"));
+
+        totpPage.removeTotp();
+
+        events.expectAccount(EventType.REMOVE_TOTP).assertEvent();
+    }
+
+    @Test
+    public void changeProfileNoAccess() throws Exception {
+        profilePage.open();
+        loginPage.login("test-user-no-access@localhost", "password");
+
+        events.expectLogin().client("account").user(keycloakRule.getUser("test", "test-user-no-access@localhost").getId())
+                .detail(Details.USERNAME, "test-user-no-access@localhost")
+                .detail(Details.REDIRECT_URI, ACCOUNT_REDIRECT).assertEvent();
+
+        Assert.assertTrue(errorPage.isCurrent());
+        Assert.assertEquals("No access", errorPage.getError());
+    }
+
+    @Test
+    public void viewLog() {
+        keycloakRule.update(new KeycloakSetup() {
+            @Override
+            public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                appRealm.setEventsEnabled(true);
+            }
+        });
+
+        try {
+            List<Event> expectedEvents = new LinkedList<Event>();
+
+            loginPage.open();
+            loginPage.clickRegister();
+
+            registerPage.register("view", "log", "view-log@localhost", "view-log", "password", "password");
+
+            expectedEvents.add(events.poll());
+            expectedEvents.add(events.poll());
+
+            profilePage.open();
+            profilePage.updateProfile("view", "log2", "view-log@localhost");
+
+            expectedEvents.add(events.poll());
+
+            logPage.open();
+
+            Assert.assertTrue(logPage.isCurrent());
+
+            List<List<String>> actualEvents = logPage.getEvents();
+
+            Assert.assertEquals(expectedEvents.size(), actualEvents.size());
+
+            for (Event e : expectedEvents) {
+                boolean match = false;
+                for (List<String> a : logPage.getEvents()) {
+                    if (e.getType().toString().replace('_', ' ').toLowerCase().equals(a.get(1)) &&
+                            e.getIpAddress().equals(a.get(2)) &&
+                            e.getClientId().equals(a.get(3))) {
+                        match = true;
+                        break;
+                    }
+                }
+                if (!match) {
+                    Assert.fail("Event not found " + e.getType());
+                }
+            }
+        } finally {
+            keycloakRule.update(new KeycloakSetup() {
+                @Override
+                public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+                    appRealm.setEventsEnabled(false);
+                }
+            });
+        }
+    }
+
+    @Test
+    public void sessions() {
+        loginPage.open();
+        loginPage.clickRegister();
+
+        registerPage.register("view", "sessions", "view-sessions@localhost", "view-sessions", "password", "password");
+
+        Event registerEvent = events.expectRegister("view-sessions", "view-sessions@localhost").assertEvent();
+        String userId = registerEvent.getUserId();
+
+        events.expectLogin().user(userId).detail(Details.USERNAME, "view-sessions").assertEvent();
+
+        sessionsPage.open();
+
+        Assert.assertTrue(sessionsPage.isCurrent());
+
+        List<List<String>> sessions = sessionsPage.getSessions();
+        Assert.assertEquals(1, sessions.size());
+        Assert.assertEquals("127.0.0.1", sessions.get(0).get(0));
+
+        // Create second session
+        WebDriver driver2 = WebRule.createWebDriver();
+        try {
+            OAuthClient oauth2 = new OAuthClient(driver2);
+            oauth2.state("mystate");
+            oauth2.doLogin("view-sessions", "password");
+
+            Event login2Event = events.expectLogin().user(userId).detail(Details.USERNAME, "view-sessions").assertEvent();
+
+            sessionsPage.open();
+            sessions = sessionsPage.getSessions();
+            Assert.assertEquals(2, sessions.size());
+
+            sessionsPage.logoutAll();
+
+            events.expectLogout(registerEvent.getSessionId());
+            events.expectLogout(login2Event.getSessionId());
+        } finally {
+            driver2.close();
+        }
+    }
+
+}