use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.
the class JettyAdapterSessionStore method restoreRequest.
public boolean restoreRequest() {
HttpSession session = myRequest.getSession(false);
if (session == null)
return false;
synchronized (session) {
String j_uri = (String) session.getAttribute(FormAuthenticator.__J_URI);
if (j_uri != null) {
// check if the request is for the same url as the original and restore
// params if it was a post
StringBuffer buf = myRequest.getRequestURL();
if (myRequest.getQueryString() != null)
buf.append("?").append(myRequest.getQueryString());
if (j_uri.equals(buf.toString())) {
String method = (String) session.getAttribute(JettyHttpFacade.__J_METHOD);
myRequest.setMethod(method);
MultivaluedHashMap<String, String> j_post = (MultivaluedHashMap<String, String>) session.getAttribute(CACHED_FORM_PARAMETERS);
if (j_post != null) {
myRequest.setContentType("application/x-www-form-urlencoded");
MultiMap<String> map = new MultiMap<String>();
for (String key : j_post.keySet()) {
for (String val : j_post.getList(key)) {
map.add(key, val);
}
}
restoreFormParameters(map, myRequest);
}
session.removeAttribute(FormAuthenticator.__J_URI);
session.removeAttribute(JettyHttpFacade.__J_METHOD);
session.removeAttribute(FormAuthenticator.__J_POST);
}
return true;
}
}
return false;
}
use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.
the class FilterSessionStore method buildWrapper.
public HttpServletRequestWrapper buildWrapper(HttpSession session, final KeycloakAccount account) {
if (needRequestRestore) {
final String method = (String) session.getAttribute(SAVED_METHOD);
final byte[] body = (byte[]) session.getAttribute(SAVED_BODY);
final MultivaluedHashMap<String, String> headers = (MultivaluedHashMap<String, String>) session.getAttribute(SAVED_HEADERS);
clearSavedRequest(session);
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
protected MultivaluedHashMap<String, String> parameters;
MultivaluedHashMap<String, String> getParams() {
if (parameters != null)
return parameters;
if (body == null)
return new MultivaluedHashMap<String, String>();
String contentType = getContentType();
if (contentType != null && contentType.toLowerCase().startsWith("application/x-www-form-urlencoded")) {
ByteArrayInputStream is = new ByteArrayInputStream(body);
try {
parameters = parseForm(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return parameters;
}
@Override
public boolean isUserInRole(String role) {
return account.getRoles().contains(role);
}
@Override
public Principal getUserPrincipal() {
return account.getPrincipal();
}
@Override
public String getMethod() {
if (needRequestRestore) {
return method;
} else {
return super.getMethod();
}
}
@Override
public String getHeader(String name) {
if (needRequestRestore && headers != null) {
return headers.getFirst(name.toLowerCase());
}
return super.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
if (needRequestRestore && headers != null) {
List<String> values = headers.getList(name.toLowerCase());
if (values == null)
return Collections.emptyEnumeration();
else
return Collections.enumeration(values);
}
return super.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
if (needRequestRestore && headers != null) {
return Collections.enumeration(headers.keySet());
}
return super.getHeaderNames();
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (needRequestRestore && body != null) {
final ByteArrayInputStream is = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return is.read();
}
};
}
return super.getInputStream();
}
@Override
public void logout() throws ServletException {
servletRequestLogout();
}
@Override
public long getDateHeader(String name) {
if (!needRequestRestore)
return super.getDateHeader(name);
return -1;
}
@Override
public int getIntHeader(String name) {
if (!needRequestRestore)
return super.getIntHeader(name);
String value = getHeader(name);
if (value == null)
return -1;
return Integer.valueOf(value);
}
@Override
public String[] getParameterValues(String name) {
if (!needRequestRestore)
return super.getParameterValues(name);
MultivaluedHashMap<String, String> formParams = getParams();
if (formParams == null) {
return super.getParameterValues(name);
}
String[] values = request.getParameterValues(name);
List<String> list = new LinkedList<>();
if (values != null) {
for (String val : values) list.add(val);
}
List<String> vals = formParams.get(name);
if (vals != null)
list.addAll(vals);
return list.toArray(new String[list.size()]);
}
@Override
public Enumeration<String> getParameterNames() {
if (!needRequestRestore)
return super.getParameterNames();
MultivaluedHashMap<String, String> formParams = getParams();
if (formParams == null) {
return super.getParameterNames();
}
Set<String> names = new HashSet<>();
Enumeration<String> qnames = super.getParameterNames();
while (qnames.hasMoreElements()) names.add(qnames.nextElement());
names.addAll(formParams.keySet());
return Collections.enumeration(names);
}
@Override
public Map<String, String[]> getParameterMap() {
if (!needRequestRestore)
return super.getParameterMap();
MultivaluedHashMap<String, String> formParams = getParams();
if (formParams == null) {
return super.getParameterMap();
}
Map<String, String[]> map = new HashMap<>();
Enumeration<String> names = getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String[] values = getParameterValues(name);
if (values != null) {
map.put(name, values);
}
}
return map;
}
@Override
public String getParameter(String name) {
if (!needRequestRestore)
return super.getParameter(name);
String param = super.getParameter(name);
if (param != null)
return param;
MultivaluedHashMap<String, String> formParams = getParams();
if (formParams == null) {
return null;
}
return formParams.getFirst(name);
}
@Override
public BufferedReader getReader() throws IOException {
if (!needRequestRestore)
return super.getReader();
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public int getContentLength() {
if (!needRequestRestore)
return super.getContentLength();
String header = getHeader("content-length");
if (header == null)
return -1;
return Integer.valueOf(header);
}
@Override
public String getContentType() {
if (!needRequestRestore)
return super.getContentType();
return getHeader("content-type");
}
@Override
public String getCharacterEncoding() {
if (!needRequestRestore)
return super.getCharacterEncoding();
return getCharsetFromContentType(getContentType());
}
};
return wrapper;
} else {
return new HttpServletRequestWrapper(request) {
@Override
public boolean isUserInRole(String role) {
return account.getRoles().contains(role);
}
@Override
public Principal getUserPrincipal() {
if (account == null)
return null;
return account.getPrincipal();
}
@Override
public void logout() throws ServletException {
servletRequestLogout();
}
};
}
}
use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.
the class FilterSessionStore method saveRequest.
@Override
public void saveRequest() {
HttpSession session = request.getSession(true);
session.setAttribute(REDIRECT_URI, facade.getRequest().getURI());
session.setAttribute(SAVED_METHOD, request.getMethod());
MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>();
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
Enumeration<String> values = request.getHeaders(name);
while (values.hasMoreElements()) {
headers.add(name.toLowerCase(), values.nextElement());
}
}
session.setAttribute(SAVED_HEADERS, headers);
if (request.getMethod().equalsIgnoreCase("GET")) {
return;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
int totalRead = 0;
try {
InputStream is = request.getInputStream();
while ((bytesRead = is.read(buffer)) >= 0) {
os.write(buffer, 0, bytesRead);
totalRead += bytesRead;
if (totalRead > maxBuffer) {
throw new RuntimeException("max buffer reached on a saved request");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] body = os.toByteArray();
// Only save the request body if there is something to save
if (body.length > 0) {
session.setAttribute(SAVED_BODY, body);
}
}
use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.
the class ExportUtils method exportFederatedUser.
/**
* Full export of user data stored in federated storage (including role mappings and credentials)
*
* @param id
* @return fully exported user representation
*/
public static UserRepresentation exportFederatedUser(KeycloakSession session, RealmModel realm, String id, ExportOptions options) {
UserRepresentation userRep = new UserRepresentation();
userRep.setId(id);
MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, id);
if (attributes.size() > 0) {
Map<String, List<String>> attrs = new HashMap<>();
attrs.putAll(attributes);
userRep.setAttributes(attrs);
}
List<String> requiredActions = session.userFederatedStorage().getRequiredActionsStream(realm, id).collect(Collectors.toList());
if (requiredActions.size() > 0) {
userRep.setRequiredActions(requiredActions);
}
// Social links
List<FederatedIdentityRepresentation> socialLinkReps = session.userFederatedStorage().getFederatedIdentitiesStream(id, realm).map(ExportUtils::exportSocialLink).collect(Collectors.toList());
if (socialLinkReps.size() > 0) {
userRep.setFederatedIdentities(socialLinkReps);
}
// Role mappings
if (options.isGroupsAndRolesIncluded()) {
Set<RoleModel> roles = session.userFederatedStorage().getRoleMappingsStream(realm, id).collect(Collectors.toSet());
List<String> realmRoleNames = new ArrayList<>();
Map<String, List<String>> clientRoleNames = new HashMap<>();
for (RoleModel role : roles) {
if (role.getContainer() instanceof RealmModel) {
realmRoleNames.add(role.getName());
} else {
ClientModel client = (ClientModel) role.getContainer();
String clientId = client.getClientId();
List<String> currentClientRoles = clientRoleNames.get(clientId);
if (currentClientRoles == null) {
currentClientRoles = new ArrayList<>();
clientRoleNames.put(clientId, currentClientRoles);
}
currentClientRoles.add(role.getName());
}
}
if (realmRoleNames.size() > 0) {
userRep.setRealmRoles(realmRoleNames);
}
if (clientRoleNames.size() > 0) {
userRep.setClientRoles(clientRoleNames);
}
}
// Credentials
List<CredentialRepresentation> credReps = session.userFederatedStorage().getStoredCredentialsStream(realm, id).map(ExportUtils::exportCredential).collect(Collectors.toList());
userRep.setCredentials(credReps);
// Grants
List<UserConsentRepresentation> consentReps = session.users().getConsentsStream(realm, id).map(ModelToRepresentation::toRepresentation).collect(Collectors.toList());
if (consentReps.size() > 0) {
userRep.setClientConsents(consentReps);
}
// Not Before
int notBefore = session.userFederatedStorage().getNotBeforeOfUser(realm, userRep.getId());
userRep.setNotBefore(notBefore);
if (options.isGroupsAndRolesIncluded()) {
List<String> groups = session.userFederatedStorage().getGroupsStream(realm, id).map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
userRep.setGroups(groups);
}
return userRep;
}
use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.
the class ExportUtils method exportRealm.
public static RealmRepresentation exportRealm(KeycloakSession session, RealmModel realm, ExportOptions options, boolean internal) {
RealmRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, internal);
ModelToRepresentation.exportAuthenticationFlows(realm, rep);
ModelToRepresentation.exportRequiredActions(realm, rep);
// Project/product version
rep.setKeycloakVersion(Version.VERSION_KEYCLOAK);
// Client Scopes
rep.setClientScopes(realm.getClientScopesStream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()));
rep.setDefaultDefaultClientScopes(realm.getDefaultClientScopesStream(true).map(ClientScopeModel::getName).collect(Collectors.toList()));
rep.setDefaultOptionalClientScopes(realm.getDefaultClientScopesStream(false).map(ClientScopeModel::getName).collect(Collectors.toList()));
// Clients
List<ClientModel> clients = new LinkedList<>();
if (options.isClientsIncluded()) {
// we iterate over all clients in the stream.
// only those client models that can be translated into a valid client representation will be added to the client list
// that is later used to retrieve related information about groups and roles
List<ClientRepresentation> clientReps = ModelToRepresentation.filterValidRepresentations(realm.getClientsStream(), app -> {
ClientRepresentation clientRepresentation = exportClient(session, app);
clients.add(app);
return clientRepresentation;
}).collect(Collectors.toList());
rep.setClients(clientReps);
}
// Groups and Roles
if (options.isGroupsAndRolesIncluded()) {
ModelToRepresentation.exportGroups(realm, rep);
Map<String, List<RoleRepresentation>> clientRolesReps = new HashMap<>();
List<RoleRepresentation> realmRoleReps = exportRoles(realm.getRolesStream());
RolesRepresentation rolesRep = new RolesRepresentation();
if (!realmRoleReps.isEmpty()) {
rolesRep.setRealm(realmRoleReps);
}
if (options.isClientsIncluded()) {
for (ClientModel client : clients) {
Stream<RoleModel> currentAppRoles = client.getRolesStream();
List<RoleRepresentation> currentAppRoleReps = exportRoles(currentAppRoles);
clientRolesReps.put(client.getClientId(), currentAppRoleReps);
}
if (clientRolesReps.size() > 0) {
rolesRep.setClient(clientRolesReps);
}
}
rep.setRoles(rolesRep);
}
// Scopes
Map<String, List<ScopeMappingRepresentation>> clientScopeReps = new HashMap<>();
if (options.isClientsIncluded()) {
List<ClientModel> allClients = new ArrayList<>(clients);
// Scopes of clients
for (ClientModel client : allClients) {
Set<RoleModel> clientScopes = client.getScopeMappingsStream().collect(Collectors.toSet());
ScopeMappingRepresentation scopeMappingRep = null;
for (RoleModel scope : clientScopes) {
if (scope.getContainer() instanceof RealmModel) {
if (scopeMappingRep == null) {
scopeMappingRep = rep.clientScopeMapping(client.getClientId());
}
scopeMappingRep.role(scope.getName());
} else {
ClientModel app = (ClientModel) scope.getContainer();
String appName = app.getClientId();
List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
if (currentAppScopes == null) {
currentAppScopes = new ArrayList<>();
clientScopeReps.put(appName, currentAppScopes);
}
ScopeMappingRepresentation currentClientScope = null;
for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
if (client.getClientId().equals(scopeMapping.getClient())) {
currentClientScope = scopeMapping;
break;
}
}
if (currentClientScope == null) {
currentClientScope = new ScopeMappingRepresentation();
currentClientScope.setClient(client.getClientId());
currentAppScopes.add(currentClientScope);
}
currentClientScope.role(scope.getName());
}
}
}
}
// Scopes of client scopes
realm.getClientScopesStream().forEach(clientScope -> {
Set<RoleModel> clientScopes = clientScope.getScopeMappingsStream().collect(Collectors.toSet());
ScopeMappingRepresentation scopeMappingRep = null;
for (RoleModel scope : clientScopes) {
if (scope.getContainer() instanceof RealmModel) {
if (scopeMappingRep == null) {
scopeMappingRep = rep.clientScopeScopeMapping(clientScope.getName());
}
scopeMappingRep.role(scope.getName());
} else {
ClientModel app = (ClientModel) scope.getContainer();
String appName = app.getClientId();
List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
if (currentAppScopes == null) {
currentAppScopes = new ArrayList<>();
clientScopeReps.put(appName, currentAppScopes);
}
ScopeMappingRepresentation currentClientTemplateScope = null;
for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
if (clientScope.getName().equals(scopeMapping.getClientScope())) {
currentClientTemplateScope = scopeMapping;
break;
}
}
if (currentClientTemplateScope == null) {
currentClientTemplateScope = new ScopeMappingRepresentation();
currentClientTemplateScope.setClientScope(clientScope.getName());
currentAppScopes.add(currentClientTemplateScope);
}
currentClientTemplateScope.role(scope.getName());
}
}
});
if (clientScopeReps.size() > 0) {
rep.setClientScopeMappings(clientScopeReps);
}
// Finally users if needed
if (options.isUsersIncluded()) {
List<UserRepresentation> users = session.users().getUsersStream(realm, true).map(user -> exportUser(session, realm, user, options, internal)).collect(Collectors.toList());
if (users.size() > 0) {
rep.setUsers(users);
}
List<UserRepresentation> federatedUsers = session.userFederatedStorage().getStoredUsersStream(realm, 0, -1).map(user -> exportFederatedUser(session, realm, user, options)).collect(Collectors.toList());
if (federatedUsers.size() > 0) {
rep.setFederatedUsers(federatedUsers);
}
} else if (options.isClientsIncluded() && options.isOnlyServiceAccountsIncluded()) {
List<UserRepresentation> users = new LinkedList<>();
for (ClientModel app : clients) {
if (app.isServiceAccountsEnabled() && !app.isPublicClient() && !app.isBearerOnly()) {
UserModel user = session.users().getServiceAccount(app);
if (user != null) {
UserRepresentation userRep = exportUser(session, realm, user, options, internal);
users.add(userRep);
}
}
}
if (users.size() > 0) {
rep.setUsers(users);
}
}
// components
MultivaluedHashMap<String, ComponentExportRepresentation> components = exportComponents(realm, realm.getId());
rep.setComponents(components);
return rep;
}
Aggregations