How to work with users and roles using the Splunk SDK for Java

With the Splunk SDKs, you can manage who can access your Splunk Enterprise system and control what they can do by setting up users and assigning them roles.

This topic contains the following sections:

Users

Splunk Enterprise has a single default user ("admin"), and you can add more. (Splunk Free doesn't support user authentication.) For each new user you add to your Splunk Enterprise system, you can specify:

  • A username and password
  • A full name
  • An email address
  • A default time zone
  • A default app
  • One or more roles to control what the user can do

Roles

Roles specify what the user is allowed to do in Splunk Enterprise. Splunk Enterprise includes predefined roles that you can modify, or you can create new roles. The predefined roles are:

  • admin: This role has the most capabilities.
  • power: This role can edit all shared objects and alerts, tag events, and other similar tasks.
  • user: This role can create and edit its own saved searches, run searches, edit preferences, create and edit event types, and other similar tasks.
  • can_delete: This role has the single capability of deleting by keyword, which is required for using the delete search operator.
  • splunk-system-role: This role is based on admin, but has more restrictions on searches and jobs.

Each role is defined by a combination of these permissions and restrictions:

  • Capabilities, which specify the system settings and resources the user is allowed to view or modify. For example, you could allow users to list data inputs but not edit them. For a full list of capabilities, see Capabilities, below.
  • Restrictions on searches and search jobs. For example, you can set a limit on the number of concurrent search jobs the user can run, or restrict the data that the user can search by setting a search filter.
  • Allowed indexes, to explicitly specify which indexes the user is allowed to search.
  • Indexes to search by default.
  • Other roles to inherit properties from.

When you inherit other roles, their capabilities, restrictions, and properties are not merged with those of the current role, but rather they are maintained separately. For example, if you list capabilities of a role, its inherited capabilities are not listed—you must explicitly request a list of inherited capabilities. When a role is modified, the changes are made automatically where ever the role is inherited.

You can also assign one or more roles to each user. When multiple roles are assigned, the broadest permissions from these roles are given. Specifically, the user's permissions are the union of all capabilities and the intersection of the restrictions.

 

The user and role APIs

The classes for working with users and roles are:

Access these classes through an instance of the Service class. Retrieve a collection, and from there you can access individual items in the collection and create new ones. For example, here's a simplified program for getting a collection of users and creating a new one:

// Connect to Splunk Enterprise
Service service = Service.connect(connectArgs);

// Get the collection of users
UserCollection usercollection = service.getUsers();

// Create a user
User user = service.getUsers().create(username, password, roles);
 

Code examples

This section provides examples of how to use the user and roles APIs, assuming you first connect to a Splunk Enterprise instance:

 

To list users and display properties

This example shows how to use the UserCollection class to retrieve the collection of users that have been added to your Splunk Enterprise system and list them, sorted by the realname field. This example also retrieves a few properties for each user, including their roles.

When retrieving a collection, you can set additional parameters to specify how many entities to return, the sorting order, and so on. For more, see Collection parameters.

// List all users, sorted by real name
Args userArgs = new Args();
userArgs.put("sort_key", "realname");
userArgs.put("sort_dir", "asc");
UserCollection usercoll = service.getUsers(userArgs);

// Display info for each user (real name, username, roles)
System.out.println("There are " + usercoll.size() + " users:\n");
for (User user: usercoll.values()) {
    System.out.println(user.getRealName() + " (" + user.getName() + ")");
    for (String role: user.getRoles()) {
        System.out.println(" - " + role);
    }
}
 

To add a new user and modify properties

This example shows how to use the User class to create a new user. Provide a username and password, and specify one or more roles.

You can set additional properties for the user in different ways:

  • Use the setter methods. The setter methods are the easiest way to set and modify properties, but they aren't available until after the user has been created. The example below shows how to modify properties using setter methods.
  • Create an argument map of key-value pairs. Creating an argument map is the only way to set properties at the same time you create a user, but it requires a little more work to look up properties and provide values in the correct format. For a list of possible properties, see User authentication parameters.

Note that when you set properties, the new values overwrite any existing ones. For example, if you set a role, it replaces any existing roles already assigned to the user.

// Create a new user with multiple roles
String username = "testuser";
String password = "changeme"; 
String[] roles = {"power","user"};
User user = service.getUsers().create(username, password, roles);

// Display the properties of the new user
System.out.println("Properties for " + username + "\n-----------------------");

System.out.println("Username:    " + user.getName());
System.out.println("Full name:   " + user.getRealName());
System.out.println("Default app: " + user.getDefaultApp());
System.out.println("Time zone:   " + user.getTz());
System.out.println("Roles:");
for (String rolename: user.getRoles()) {
    System.out.println(" - " + rolename);
}

// Change some properties and update the server
user.setRealName("Test User");
user.setRoles("can_delete");
user.setDefaultApp("launcher");
user.setTz("US/Pacific");
user.update();

// Display the updated properties
System.out.println("\n\nUpdated properties\n-----------------------");
System.out.println("Username:    " + user.getName());
System.out.println("Full name:   " + user.getRealName());
System.out.println("Default app: " + user.getDefaultApp());
System.out.println("Time zone:   " + user.getTz());
System.out.println("Roles:");
for (String rolename: user.getRoles()) {
    System.out.println(" - " + rolename);
}

To get the current user

This example shows how to find out which user is currently logged in.

// Display the current user
System.out.println("The current user is " + service.getUsername());

To list roles and display properties

This example shows how to use the EntityCollection<Role> class to retrieve the collection of roles that have been configured for Splunk Enterprise and list them along with their capabilities.

When retrieving a collection, you can set additional parameters to specify how many entities to return, the sorting order, and so on. For more, see Collection parameters.

// Get the collection of roles
EntityCollection<Role> rolecoll = service.getRoles();

// Display the name and capabilities (included imported ones) of each role
System.out.println("There are " + rolecoll.size() + " defined roles:\n");
for (Role role: rolecoll.values()) {
    System.out.println("Role: " + role.getName());
    System.out.println("  Capabilities:");
    for (String cape: role.getCapabilities()) {
        System.out.println("   - " + cape);
    }
    if(role.getImportedCapabilities().length >0) {
        System.out.println("  Imported capabilities: ");
        for (String cape: role.getImportedCapabilities()) {
            System.out.println("   - " + cape);
        }
    }
    System.out.println("\n");
}

To create a new role and modify properties

This example shows how to use the Role class to create a new role, then how to import capabilities and properties from existing roles. As always, you can set additional properties when you create the role by also creating an argument map of key-value pairs (see Roles parameters for available parameters). Or, use the setter methods to modify properties, as shown in this example.

Note that when you set properties, the new values overwrite any existing ones. For example, if you set imported roles, these replace any existing roles.

// Create a new role called 'testrole'
Role role = service.getRoles().create("testrole");

// Import properties from the 'user' role and update the server
role.setImportedRoles("user");
role.update(); 

// Display the properties of the new role
System.out.println("\nProperties for 'testrole'");
System.out.println("-------------------------\n");
System.out.println("Allowed indexes:");
for (String index: role.getImportedIndexesAllowed()) {
    System.out.println(" - " + index);
}
System.out.println("Capabilities: ");
for (String cape: role.getCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("Imported capabilities: ");
for (String cape: role.getImportedCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("\n");


// Set new properties

// Set capabilities for the role
String[] editingcape = {"indexes_edit","edit_forwarders","edit_monitor"};
role.setCapabilities(editingcape);

// Set a default app for the role
role.setDefaultApp("search");

// Set a search filter
role.setSearchFilter("source=/var/log/*");

// Make changes to the server
role.update();

// Print the latest properties of the new role
System.out.println("\nUpdated properties\n------------------\n");
System.out.println("Capabilities:");
for (String cape: role.getCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("Imported capabilities:");
for (String cape: role.getImportedCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("Imported roles:");
for (String improle: role.getImportedRoles()) {
    System.out.println(" - " + improle);
}
System.out.println("Default app: " + role.getDefaultApp());
System.out.println("Search filter: " + role.getSearchFilter());

// Set additional properties--these overwrite the existing values
String[] editingcape2 = {"list_forwarders","list_httpauths"};
role.setCapabilities(editingcape2);
role.setImportedRoles("can_delete");
role.update();


// Print the latest properties of the role again
// Note that existing properties are overwritten
System.out.println("\n\nUpdated properties again\n------------------------\n");
System.out.println("Capabilities:");
for (String cape: role.getCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("Imported capabilities:");
for (String cape: role.getImportedCapabilities()) {
    System.out.println(" - " + cape);
}
System.out.println("Imported roles:");
for (String improle: role.getImportedRoles()) {
    System.out.println(" - " + improle);
}
System.out.println("Default app: " + role.getDefaultApp());
System.out.println("Search filter: " + role.getSearchFilter());

Parameters

Here are the available parameters for working with users and roles:

Capabilities

Here are the capabilities you can allow in a role.

Capability Description
admin_all_objectsHas access to objects in the system, such as user objects and search jobs.
change_authentication Can change authentication settings and reload authentication.
change_own_password Can change one's own user password.
delete_by_keyword Can use the "delete" search operator.
edit_deployment_client Can change deployment client settings.
edit_deployment_server Can change deployment server settings.
edit_dist_peer Can add and edit peers for distributed search.
edit_forwarders Can change forwarder settings.
edit_httpauths Can edit and end user sessions.
edit_input_defaults Can change the default hostnames for input data.
edit_monitor Can add inputs and edit settings for monitoring files.
edit_roles Can edit roles and change user/role mappings.
edit_scripted Can create and edit scripted inputs.
edit_search_server Can edit general distributed search settings such as timeouts, heartbeats, and blacklists.
edit_server Can edit general server settings such as the server name and log levels.
edit_splunktcp Can change settings for TCP inputs from another Splunk Enterprise instance.
edit_splunktcp_ssl Can list or edit any SSL-specific settings for Splunk Enterprise TCP inputs.
edit_tcp Can change settings for general TCP inputs.
edit_udp Can change settings for UDP inputs.
edit_user Can create, edit, and remove users.
edit_web_settings Can change settings in the web.conf configuration file.
get_metadata Enables the "metadata" search processor.
get_typeahead Enables typeahead.
indexes_edit Can change index settings such as file size and memory limits.
license_tab Can access and change the license.
list_forwarders Can show forwarder settings.
list_httpauths Can list user sessions.
list_inputs Can list various inputs, including input from files, TCP, UDP, and scripts.
request_remote_tok Can get a remote authentication token.
rest_apps_management Can edit settings in the Python remote apps handler.
rest_apps_view Can list properties in the Python remote apps handler.
rest_properties_get Can get information from configuration files.
rest_properties_set Can edit settings in configuration files.
restart_splunkd Can restart Splunk Enterprise through the server control handler.
rtsearch Can run real-time searches.
schedule_search Can schedule saved searches.
search Can run searches.
use_file_operator Can use the "file" search operator.

Collection parameters

By default, all entities are returned when you retrieve a collection. Using the parameters below, you can specify the number of entities to return, how to sort them, and so on. Set these paramaters using setters from the CollectionArgs class, or create a generic Args map:

ParameterDescription
countA number that indicates the maximum number of entities to return.
offsetA number that specifies the index of the first entity to return.
searchA string that specifies a search expression to filter the response with, matching field values against the search expression. For example, "search=foo" matches any object that has "foo" as a substring in a field, and "search=field_name%3Dfield_value" restricts the match to a single field.
sort_dirAn enum value that specifies how to sort entities. Valid values are "asc" (ascending order) and "desc" (descending order).
sort_keyA string that specifies the field to sort by.
sort_modeAn enum value that specifies how to sort entities. Valid values are "auto", "alpha" (alphabetically), "alpha_case" (alphabetically, case sensitive), or "num" (numerically).

User authentication parameters

The parameters you can use for user authentication correspond to the parameters for the authentication/* endpoints in the REST API.

The following parameters are available for user authentication:

ParameterDescription
authStringA string containing the session key, which is a unique identifier for this session. Read only.
createroleA string that contains the name of a role to create. Once created, you can edit the role to specify what access that user has to Splunk Enterprise.
defaultAppA string that specifies the default app for the user, overriding any default app that is inherited from the user's roles.
defaultAppIsUserOverrideA Boolean that indicates whether the default app for the user overrides the default app for the user role. The value for the default app can come from the user's roles or from the user. Read only.
defaultAppSourceRoleA string that indicates which of the user's roles to use for the default app. Read only.
eai:attributesA string containing values that indicate which resource fields are wildcards, required, and optional. Read only.
emailA string that contains the user's email address.
nameA string that contains the Splunk Enterprise username for logging in to Splunk Enterprise. Usernames must be unique on the system, and cannot include spaces, colons, or forward slashes.
passwordA string that contains the user's password.
realnameA string that contains a full name to associate with the user.
restart_background_jobsA Boolean that indicates whether to restart background search jobs when Splunk Enterprise restarts. When true, a background search job for this user that has not completed is restarted when Splunk Enterprise restarts.
rolesA string that contains a role to assign to the user. When creating a user, at least one role is required. Specify one or more roles with this parameter, or create a new role using the "createrole" parameter.
searchIdA string that contains the search ID associated with this session, if it was created for a search job. This value is blank for a typical session. Read only.
timeAccessedA string that contains the last time this session was accessed. Read only.
typeA string that contains the type of authentication system for this user. Possible values are "LDAP", "Scripted", "Splunk", or "System" ( which is reserved for the Splunk Enterprise system user). Read only.
tzA string that specifies the time zone to use when displaying dates for the user. For valid time zone strings, see List of tz database time zones on Wikipedia.
userNameA string that contains the Splunk Enterprise username associated with this session.

Roles parameters

The parameters you can use for working with roles correspond to the parameters for the authorization/* endpoints in the REST API.

The following parameters are available for roles:

ParameterDescription
capabilitiesA string that contains a list of capabilities assigned to this role. Roles inherit all capabilities from imported roles.
defaultAppA string that contains the name of the app to use as the default app for this role. A user-specific default app overrides this. The app name corresponds to the name of the folder containing the app.
eai:attributesA string containing values that indicate which resource fields are wildcards, required, and optional. Read only.
imported_capabilitiesA string that contains a list of capabilities for this role that were inherited from imported roles. Read only.
imported_rolesA string that contains a list of roles to import attributes from. Importing other roles imports all aspects of that role, such as capabilities and allowed indexes to search. When combining multiple roles, the effective value for each attribute is the value with the broadest permissions.
imported_rtSrchJobsQuotaA number that specifies the maximum number of concurrent real-time searches a user with this role is allowed to run (imported from other roles). This count is independent from the normal search jobs limit. Read only.
imported_srchDiskQuotaA number that specifies the maximum disk space, in MB, that can be used by a user's search jobs (imported from other roles). For example, 100 limits this role to 100 MB total. Read only.
imported_srchFilterA string that contains a search query that restricts the scope of searches run by this role (imported from other roles). Search results for this role only show events that also match this search query. When a user has multiple roles with different search filters, they are combined with an OR. Read only.
imported_srchIndexesAllowedA string that contains a list of indexes this role has permissions to search (imported from other roles). Read only.
imported_srchIndexesDefaultA string that contains a list of indexes that this role defaults to when no index is specified in a search (imported from other roles). Read only.
imported_srchJobsQuotaA number that specifies the maximum number of concurrent searches a user with this role is allowed to run (imported from other roles). Read only.
imported_srchTimeWinA number that specifies the maximum time span of a search, in seconds (imported from other roles). A value of 0 means searches are not limited to any specific time window. Read only.
nameA string that contains the name of the role to create. Only lowercase characters are valid. Do not include spaces, colons, or forward slashes.
rtSrchJobsQuotaA number that specifies the maximum number of concurrent real-time searches a user with this role is allowed to run. This count is independent from the normal search jobs limit.
srchDiskQuotaA number that specifies the maximum disk space, in MB, that can be used by a user's search jobs. For example, 100 limits this role to 100 MB total.
srchFilterA string that contains a search query that restricts the scope of searches run by this role. Search results for this role only show events that also match this search query. When a user has multiple roles with different search filters, they are combined with an OR. The search string can include source, host, index, event type, source type, search fields, *, OR, and AND. For example: "host=web* OR source=/var/log/*". You can use the "srchIndexesAllowed" and "srchIndexesDefault" parameters to limit the search on indexes.
srchIndexesAllowedA string that contains a list of indexes this role has permissions to search. You can use wildcards to specify indexes, but an asterisk (*) does not match internal indexes. For those, include an underscore (_*).
srchIndexesDefaultA string that contains indexes to search when no index is specified for this role. You can use wildcards to specify indexes, but an asterisk (*) does not match internal indexes. For those, include an underscore (_*). A user with this role can search other indexes using "index= ".
srchJobsQuotaA number that specifies the maximum number of concurrent searches a user with this role is allowed to run. If multiple roles are assigned to the user, the maximum of these quotas is applied.
srchTimeWinA number that specifies the maximum time span of a search, in seconds. A value of 0 (the default) means searches are not limited to any specific time window and overrides any search time windows that are from imported roles.