arrow-down
    1. Widgets
  1. IAM
    1. Virtual apps
    1. Projects
    2. Layers
        1. AttachmentUploader
        2. Checkbox
        3. Combobox
        4. ContentSelector
        5. ContentTypeFilter
        6. CustomSelector
        7. Date
        8. DateTime
        9. Double
        10. GeoPoint
        11. HtmlArea
        12. ImageSelector
        13. Long
        14. MediaSelector
        15. Radiobutton
        16. Tag
        17. TextArea
        18. TextLine
        19. Time
      1. Field set
      2. Item set
      3. Option set
      4. Mixins
      5. Localization
    3. Content Types
    4. X-data
    5. Macros
    6. Custom styles
    7. Sites
      1. Regions
      2. Part component
      3. Layout component
      4. Text component
      5. Fragments
      6. Filtering
      7. Component indexing
      8. Visual editor
    8. Page templates
    1. Sandboxes
    2. Code
    3. Building
    4. Configuration
    1. Globals
    2. HTTP
    3. Controllers
    4. Filters
    5. Events
    6. Websocket
    7. Error handler
    8. ID provider
    9. Tasks
    10. Localization
    11. Mappings
    12. Components
    13. Processors
    14. Contributions
    15. Templating
    16. Main controller
    17. Java bridge
      1. Webapp Engine
        1. Image service
        2. Component service
      2. Admin Engine
      3. Asset service
      4. HTTP service
      5. IDprovider service
    1. Task engine
    2. Management Endpoint
    3. Statistics Endpoint
    1. Nodes and repos
    2. Properties
    3. Indexing
    4. Branches
    5. Queries (NoQL)
    6. Queries (DSL)
    7. Filters
    8. Aggregations
    9. Highlighting
    10. Editors
    1. Strategies
    2. Distributions
    3. Docker image
    4. Vhosts
    5. Configuration
    6. Backup & restore
    7. Systemd
    8. Clustering
    1. Admin API
    2. Application API
    3. Auditlog API
    4. Authentication API
    5. Cluster API
    6. Common API
    7. Content API
    8. Context API
    9. Event API
    10. Export API
    11. Grid API
    12. I18N API
    13. IO API
    14. Mail API
    15. Node API
    16. Portal API
    17. Project API
    18. Repo API
    19. Scheduler API
    20. Schema API
    21. Tasks API
    22. Value API
    23. VHost API
    24. Websocket API
  2. Audit Logs
    1. Upgrade Notes
    2. Upgrading Apps

Authentication API

Contents

This API provides built-in authentication functions.

If, while using this API, you are getting authentication errors like "Access denied to user [unknown]" it means that user role in the current context lacks sufficient permissions (for example when executed from inside a service). In this case you must explicitly execute the function in the context of System Administrator role.

Usage

Add the following to your build.gradle file:

dependencies {
  include "com.enonic.xp:lib-auth:${xpVersion}"
}

Add the import statement to your controller:

import authLib from '/lib/xp/auth';

You are now ready to use the API.

Functions

addMembers

Adds members to a principal (user or role).

Parameters

Name Kind Details

principalKey

string

Key of the principal to add members to

members

string[]

A list of the new members that should be added to the principal

Returns

void

changePassword

Changes password for specified user.

Parameters

An object with the following keys and their values:

Name Description

userKey

The key of the user to change password for

password

The new password

Returns

void

createGroup

Creates a group.

Parameters

An object with the following keys and their values:

Name Kind Description

idProvider

string

Key for id provider where the group will be created

name

string

Group name

displayName

string

Group display name

description

string

A description of the principal

Returns

object : The created group.

Example

Creating a group named "group-a"
import {createGroup} from '/lib/xp/auth';

const group = createGroup({
    idProvider: 'myIdProvider',
    name: 'group-a',
    displayName: 'Group A',
    description: "description"
});
Sample response
{
    type: "group",
    key: "group:system:group-a",
    displayName: "Group A",
    description: "description"
}

createRole

Creates a role.

Parameters

An object with the following keys and their values:

Name Kind Description

name

string

The name of the role. The key of the role will be 'role.<name>'.

displayName

string

Role display name

description

string

A description of the role

Returns

object : The created role.

Example

Creating a role named "aRole"
import {createRole} from '/lib/xp/auth';

const role = createRole({
    name: 'aRole',
    displayName: 'Role Display Name',
    description: 'description'
});
Sample response
{
    type: "role",
    key: "role:aRole",
    displayName: "Role Display Name",
    description: "description"
}

createUser

Creates a user.

Parameters

An object with the following keys and their values:

Name Kind Description

idProvider

string

Key for id provider where the user will be created

name

string

User login name

displayName

string

User display name

email

string

Optional user e-mail

Returns

object : The created group.

Example

Creating a user named "userName"
import {createUser} from '/lib/xp/auth';

const user = createUser({
    idProvider: 'myIdProvider',
    name: 'user1',
    displayName: 'The One And Only',
    email: 'user1@enonic.com'
});
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "The One And Only",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "myIdProvider"
}

deletePrincipal

Deletes the principal with the specified key.

Parameters

Name Kind Details

principalKey

string

Key of the principal to delete

Returns

boolean : true if the principal was deleted, false otherwise

Example

Deleting a user
import {deletePrincipal} from '/lib/xp/auth';

const deleted = deletePrincipal('user:myIdProvider:userId');

findPrincipals

Search for principals matching the specified criteria.

An object with the following keys and their value. All parameters are optional:

Name Kind Description

type

string

Principal type to look for, one of: 'user', 'group' or 'role'. If not specified all principal types will be included.

idProvider

string

Key of the id provider to look for. If not specified all id providers will be included.

start

string

First principal to return from the search results. It can be used for pagination.

count

string

A limit on the number of principals to be returned

name

string

Name of the principal to look for

searchText

string

Text to look for in any principal field.

Returns

object : The "total" number of principals matching the search, the "count" of principals included, and an array of "hits" containing the principals.

Example

Searching for principals for 'user1'
import {findPrincipals} from '/lib/xp/auth';

const result = findPrincipals({
    idProvider: "user-store",
    start: 0,
    count: 10,
    searchText: "user1"
});
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "The One And Only",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "myIdProvider"
}

findUsers

Search for users matching the specified query.

An object with the following keys and their values:

Name Kind Description

query

string

Query expression

start

number

Optional start index for paging

count

number

Optional number of users to fetch at a time

sort

string

Optional sorting expression

includeProfile

boolean

If set to true, a full profile of each user will be included in the result

Returns

object : An object containg the total number of hits, the number returned and an array of the hits.

Example

Searching for the first person in the Juve family.
import {findUsers} from '/lib/xp/auth';

const findUsersResult = findUsers({
    count: 1,
    query: "displayName LIKE '*Juve'"
});
Sample response
{
    total: 2,
    count: 1,
    hits: [
        {
            type: "user",
            key: "user:system:jorgen-juve",
            displayName: "Jørgen Juve",
            disabled: false,
            email: "jju@enonic.com",
            login: "jorgen-juve",
            idProvider: "system"
        }
    ]
}
If you want to find a user by key, you have to use _id field in the query parameter.
Find a user by key.
import {findUsers} from '/lib/xp/auth';

const findUsersResult = findUsers({
    count: 1,
    query: "_id = 'user:system:jorgen-juve'"
});

generatePassword

Generates a random secure password that may be suggested to a user.

Parameters

None

Returns

string : A suggestion for a secure password

Example

Generate a password and return the password string
import {generatePassword} from '/lib/xp/auth';

const pwd = generatePassword();

getIdProviderConfig

This function returns the ID provider configuration. It is meant to be called from an ID provider controller.

Parameters

None

Returns

object : An object with all the values in the configuration

getMembers

Returns a list of principals that are members of the specified principal.

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve the members of.

Returns

object[] : A list of objects for each member of the principal or empty array if none.

Example

Searching for members of the Content Manager group
import {getMembers} from '/lib/xp/auth';

const result = getMembers('group:system:content-managers');
Sample response
[{type:"user",key:"user:system:user1",displayName:"User 1",disabled:false,email:"user1@enonic.com",login:"user1",idProvider:"system"},
 {type:"user",key:"user:system:user2",displayName:"User 2",disabled:false,email:"user2@enonic.com",login:"user2",idProvider:"system"
 }]

getMemberships

Returns the list of principals which the specified principal is a member of.

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve memberships for

transitive

boolean

Retrieve transitive memberships. Considered false if not specified

Returns

string[] : A list of the principals that the specified principal is a member of

Example

Searching for direct memberships of 'user1'
import {getMemberships} from '/lib/xp/auth';

const result = getMemberships('user:system:user1');
Sample response
[{
    type: "role",
    key: "role:system.admin",
    displayName:"Administrator"
}]
Searching for transitive memberships of 'user1'
import {getMemberships} from '/lib/xp/auth';

const result = getMemberships('user:system:user1', true);
Sample response
[
    "role:system.admin.login",
    "group:system:content-managers",
    "role:cms.expert",
    "role:cms.cm.app"
]

getPrincipal

Returns the principal with the specified key.

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve memberships for

Returns

object : The principal as an object

Retrieving the full principal for 'user1'
import {getPrincipal} from '/lib/xp/auth';

const result = getPrincipal('user:system:user1');
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system"
}

getProfile

Returns the profile of a user.

Parameters

An object with the following keys and their values:

Name Kind Details

principalKey

string

Principal key to retrieve profile for

scope

string

Optional scope setting

Returns

object : Profile data

Example

Retrieving the profile of 'user1'
import {getProfile} from '/lib/xp/auth';

const result = getProfile('user:system:user1');
Sample response
{
    nickName: "User Nick"
}

getUser

Returns the logged-in user. If not logged-in, this will return undefined or null.

Parameters

None

Returns

object : User data

Example

Retrieving the profile of 'user1'
import {getUser} from '/lib/xp/auth';

const result = getUser();
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system"
}

hasRole

Checks if the logged-in user has the specified role.

Parameters

Name Kind Details

role

string

The role to check for

Returns

boolean : true if the current user has the role, false otherwise

Example

Checking a role
import {hasRole} from '/lib/xp/auth';

const hasRole = hasRole('system.admin');

login

Logs in a user through the specified idProvider, with username and password.

Parameters

An object with the following keys and their values:

Name Kind Details

user

string

Mandatory name of the user to log in

password

string

Password for the user. Ignored if skipAuth is set to true, mandatory otherwise.

idProvider

string

Name of id provider where the user is stored. If not specified it will try all available id providers, in alphabetical order.

skipAuth

boolean

Skip authentication. Default is false if not specified.

sessionTimeout

number

Session timeout (in seconds). By default, the value of session.timeout from com.enonic.xp.web.jetty.cfg

scope XP XP 7.3.0 7.3.0

string

Defines the scope of the login. Valid values are SESSION, REQUEST and NONE (starting from version XP XP 7.8.0 7.8.0 ). When scope is set to SESSION the login is persistent. If scope is set to REQUEST the login is only valid for the current request. Scope NONE allows to check correctness of username and password without logging into the system. Default is SESSION if not specified.

Returns

object : The logged-in user

Example

Logging in a user
import {login} from '/lib/xp/auth';

const loginResult = login({
    user: 'user1',
    password: 'myPwd1',
    idProvider: 'myIdProvider'
});
Sample response
{
    authenticated:true,
    user:{
        type:"user",
        key:"user:system:user1",
        displayName:"The One And Only",
        disabled:false,
        email:"user1@enonic.com",
        login:"user1",
        idProvider:"myIdProvider"
    }
}

logout

Logs out the currently logged-in user.

Parameters

None

Returns

void

modifyGroup

Updates an existing group.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

Principal key of the group to modify

editor

function

Group editor function

Returns

object : The updated group

Example

Changing a group
import {modifyGroup} from '/lib/xp/auth';

// Callback to edit the group.
function groupEditor(c) {
    c.displayName = 'Modified display name';
    c.description = 'descriptionX';
    return c;
}

// Modify group with specified key.
const group = modifyGroup({
    key: 'group:system:group-a',
    editor: groupEditor
});
Sample response
{
    type: "group",
    key: "group:system:group-a",
    displayName: "Modified display name",
    description: "descriptionX"
}

modifyProfile

Updates an existing user profile.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

Principal key of the user

scope

string

Optional scope setting

editor

function

Profile editor function

Returns

object : The updated profile

Changing a profile
import {modifyProfile} from '/lib/xp/auth';

// Callback to edit the profile.
function profileEditor(c) {
    if (!c) {
        c = {};
    }
    c.nickName = "User Nick";
    return c;
}

// Modify profile with specified key.
const profileModified = modifyProfile({
    key: 'user:system:user1',
    editor: profileEditor
});
Sample response
{
    nickName: "User Nick"
}

modifyRole

Updates an existing role.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

The role key

editor

function

Role editor function

Returns

object : The updated role

Changing a role
import {modifyRole} from '/lib/xp/auth';

// Callback to edit the profile.
function roleEditor(c) {
    c.displayName = 'Nothing Role';
    c.description = 'This role does not give access to anything!';
    return c;
}

// Modify role with specified key.
const theRole = modifyRole({
    key: 'role:aRole',
    editor: roleEditor
});
Sample response
{
    type: "role",
    key: "role:aRole",
    displayName: "Nothing Role",
    description: "This role does not give access to anything!"
}

modifyUser

Updates an existing user.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

The user key

editor

function

User editor function

Returns

object : The updated user

Changing a user
import {modifyUser} from '/lib/xp/auth';

// Callback to edit the profile.
function userEditor(c) {
    c.displayName = 'User 1-A';
    c.email = 'user1a@enonic.com';
    return c;
}

// Modify user with specified key.
const theUser = modifyUser({
    key: 'user:system:user1',
    editor: userEditor
});
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "User 1-A",
    disabled: false,
    email: "user1a@enonic.com",
    login: "user1",
    idProvider: "myIdProvider"
}

removeMembers

Removes members from a principal (group or role).

Parameters

Name Kind Details

principalKey

string

The principal key of a group or a role to remove members from

members

string[]

Principal keys to remove as members

Returns

void

Remove members from specified principal.
authLib.removeMembers('role:roleId', ['user:system:user1', 'group:system:group-a']);

Contents

Contents

AI-powered search

Juke AI