---
language: "en"
---
# TrustBuilder.io

Welcome to TrustBuilder.io product documentation.

Find help administering, integrating and using TrustBuilder.io CIAM solution. This documentation portal provides administrators, developers, policy-designers, helpdesk with detailed documentation.

## Popular topics

* [Directory](https://docs.trustbuilder.com/tb-io/user-admin-guide.md)

* [Access management](https://docs.trustbuilder.com/tb-io/access-management.md)

* [Workflows](https://docs.trustbuilder.com/tb-io/workflows.md)

* [Service Providers management](https://docs.trustbuilder.com/tb-io/service-providers.md)

* [Read the last product releases](https://docs.trustbuilder.com/tb-io/all-release-notes.md)

## Other documentation

[TrustBuilder MFA documentation ↗](http://docs.trustbuilder.com/mfa)

---
language: "en"
---
# Defining Access flows

Access Flows define the identification and authentication requirements for accessing applications. They specify which **Identity Providers (IdPs)** are accepted before a user can access a **Service Provider (SP)**, and in some cases, the order in which authentication must take place.

An Access Flow consists of two key elements:

* The **Authentication Scheme** defining how users authenticate to access a Service Provider.

  There are different scheme types:

  * [Authentication level](https://docs.trustbuilder.com/tb-io/access-flows.md#authentication-level)

    The authentication methods available are based on the required security level.

  * [Multi-factor](https://docs.trustbuilder.com/tb-io/access-flows.md#multi-factor)

    Requires users to authenticate with multiple methods.

  * [Policy-driven](https://docs.trustbuilder.com/tb-io/access-flows.md#policy-driven)

    Authentication is based on predefined policies.

* The **Authentication Method**: This groups one or more Identity Providers that serve as the identity source for users.

**IDHub Default Scheme**

There is always the pre-defined Access flow (*IDHub Default Scheme*). It is applied to access the TrustBuilder applications, such as the Administration Portal or Self-Service portal.

This Access Flow is critical for accessing the Administration Portal. If you plan to modify it or link the Administration Portal to another Access Flow proceed with caution to avoid losing access.

## Configuring an Access Flow

### Authentication level

The Authentication Level scheme determines the authentication methods available based on the required security level.  
<https://youtu.be/KXs2dXXvR-4>

Methods are ordered from most secure (top) to least secure (bottom). The user will authenticate using only one of the available methods. The available methods depend on whether the Service Provide requires an authentication context and whether a default method is configured in the access flow.

* If the SP**requires an authentication context** :

  Only authentication methods or Identity Providers (IdPs) with a matching context (SAML2 or OpenID Connect) will be available for users.

* If the SP **does NOT require an authentication context** :

  Available methods depend on the Default Method Comparison and whether a default method is defined.

1. Login to TrustBuilder Admin Portal.

2. Go to **Access Management** \> **Access Flows**.

3. Click on **+ Add Access Flow**.

4. Click on **Add Authentication Scheme**.

   * Enter a name for the Authentication Scheme.

   * Select a **Scheme Type** : **Authentication level.**

   * Click **Save**.

5. Click on **Add Authentication Method**.

   * Enter the display name of this authentication method (visible on the access flow interface).

   * If a Service Provider requires context, enter the matching value:

     * SAML2 Context *(AuthnContextClassRef)* : [an official SAML 2.0 reference](https://docs.oasis-open.org/security/saml/v2.0/saml-authn-context-2.0-os.pdf).

     * OpenID Context *(Authentication Context Class Reference - ACR)* : [an OpenID Connect (OIDC) concept](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues).

   * Select one or several Identity Providers.

   * Click **Save** .

     Wait a few seconds for the graphical representation of the Access Flow to appear.

6. Repeat previous step to add more Authentication methods.

7. Order authentication methods from most secure to least secure:

   * The method at the top of this list define maximum security, the most secure.

   * The method at the bottom of the list define minimum security, the least secure.

8. Click on **Link Service Provider**.

   * Select a Service Provider to be linked to this access flow.

   * Click on **Next**.

   * Select the**Default Method Comparison** which determines how the authentication method's strength is evaluated.

     ![info](/__attachments/a_a375735788fda1d4f10298d9f0ec0b943e58ed90870947297014557c6c0b3979/atlassian-info?cb=feab5cd71111204d6b52545f3027dd0c) *If a default authentication method is defined for the SP, it serves as the reference method for the security level.*

   * **Default method** *(Optional)*: Select an authentication method.

   * Click **Save**.

9. Repeat previous step to link more Service Providers to this access flow.

If you select a Service Provider already used in another Access Flow, it will be removed from the previous one and added to the current flow. This change applies immediately and may impact user access.  
**Known limitation:**The OpenID Context field is mandatory, even if no OpenID Context is needed. Enter a value to proceed.  

|                                                                  **Default method defined**                                                                  | **Default Method Comparison** |                               **Behavior**                               |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------|--------------------------------------------------------------------------|
| ✅ Yes                                                                                                                                                        | MINIMUM                       | Allows any method equal to or more secure than the default method.       |
| ✅ Yes                                                                                                                                                        | MAXIMUM                       | Only the most secure method (top of the list) is allowed.                |
| ✅ Yes                                                                                                                                                        | BETTER                        | Requires a method more secure than the default method.                   |
| ✅ Yes                                                                                                                                                        | EXACT                         | Requires exactly the default method.                                     |
| ![cross mark](https://docs.trustbuilder.com/__attachments/a_90c8aa1de764905484edda76fe2783d9f6be7a753bcc5091ccf894d6be1042db/atlassian-cross_mark?cb=a9c671cfc7809253be52d640dbbf1019) No | MINIMUM                       | All methods are allowed (no reference defined, so all meet the minimum). |
| ![cross mark](https://docs.trustbuilder.com/__attachments/a_90c8aa1de764905484edda76fe2783d9f6be7a753bcc5091ccf894d6be1042db/atlassian-cross_mark?cb=a9c671cfc7809253be52d640dbbf1019) No | MAXIMUM                       | Only the most secure method (top of the list) is allowed.                |
| ![cross mark](https://docs.trustbuilder.com/__attachments/a_90c8aa1de764905484edda76fe2783d9f6be7a753bcc5091ccf894d6be1042db/atlassian-cross_mark?cb=a9c671cfc7809253be52d640dbbf1019) No | BETTER                        | Only methods more secure than the least secure method are allowed.       |
| ![cross mark](https://docs.trustbuilder.com/__attachments/a_90c8aa1de764905484edda76fe2783d9f6be7a753bcc5091ccf894d6be1042db/atlassian-cross_mark?cb=a9c671cfc7809253be52d640dbbf1019) No | EXACT                         | Authentication fails (there is no reference method to match)             |

### Multi-factor

Requires users to authenticate with multiple methods.

<https://youtu.be/TGSGyxvSV74>

1. Login to TrustBuilder Admin Portal.

2. Go to **Access Management** \> **Access Flows**.

3. Click on **+ Add Access Flow**.

4. Click on **Add Authentication Scheme**.

   * Enter a name for the Authentication Scheme.

   * Select a **Scheme Type** : **Multi-factor**.

   * Click **Save**.

5. Click on **Add Authentication Method**.

   * Enter the display name of this authentication method (visible on the access flow interface).

   * If a Service Provider requires context, enter the matching value:

     * SAML2 Context *(AuthnContextClassRef)* : [an official SAML 2.0 reference](https://docs.oasis-open.org/security/saml/v2.0/saml-authn-context-2.0-os.pdf).

     * OpenID Context *(Authentication Context Class Reference - ACR)* : [an OpenID Connect (OIDC) concept](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues).

6. Select one or several Identity Providers.

7. Click **Save** .

   Wait a few seconds for the graphical representation of the Access Flow to appear.

8. Repeat previous step to link more Identity Providers.

9. **Define the order**in which authentication methods will be shown to users:

   * the method at the top of the list will appear first.

   * the one at the bottom will appear last.

10. Click on **Link Service Provider**.

    * Select a Service Provider to be linked to this access flow.

    * Click **Save**.

11. Repeat previous step to link more Service Providers.

If you select a Service Provider already used in another Access Flow, it will be removed from the previous one and added to the current flow. This change applies immediately and may impact user access.  
**Known limitation:**The OpenID Context field is mandatory, even if no OpenID Context is needed. Enter a value to proceed.

### Policy driven

Authentication is based on predefined policies, allowing for more refined rules.

1. Login to TrustBuilder Admin Portal.

2. Go to **Access Management** \> **Access Flows**.

3. Click on **+ Add Access Flow**.

4. Click on **Add Authentication Scheme**.

   * Enter a name for the Authentication Scheme.

   * Select a **Scheme Type** : **Policy Driven**.

   * Select the policy to apply to the access flow.

   * Click **Save**.

5. Click on **Add Authentication Method**.

   * Enter the **display name** of this authentication method (visible on the access flow interface).

   * Enter a **context value** .

     This should match the `requires_acr` value in the rule's obligation.

     ![info](/__attachments/a_a375735788fda1d4f10298d9f0ec0b943e58ed90870947297014557c6c0b3979/atlassian-info?cb=feab5cd71111204d6b52545f3027dd0c) Only the most secure authentication method (the one at the top of the list) with a matching OpenID Connect context will be shown to users.

   * Select one or several Identity Providers.

   * Click **Save** .

     Wait a few seconds for the graphical representation of the Access Flow to appear.

6. Repeat previous step to link more Identity Providers.

7. Click on **Link Service Provider**.

   * Select a Service Provider to be linked to this access flow.

   * Click **Save** .

     ⚠️ By default, each Service Provider uses the `MINIMUM` method comparison, which allows the context to override it. Do not change this value to avoid authentication fail.

8. Repeat previous step to link more Service Providers.

If you select a Service Provider already used in another Access Flow, it will be removed from the previous one and added to the current flow. This change applies immediately and may impact user access.

## Managing Access Flows

### Editing an access flow

1. Go to **Access Management** \> **Access Flows** .

   The list of existing access flows appears.

2. Click on the Access Flow you want to edit.

3. Make the necessary changes:

   * Some changes take effect immediately (e.g., reordering authentication candidates).

   * Others require saving to apply (e.g., linking an IdP or SP)

The access flow is successfully edited.  
If you select a Service Provider already used in another Access Flow, it will be removed from the previous one and added to the current flow. This change applies immediately and may impact user access.

### Deleting an access flow

1. Go to **Access Management** \> **Access Flows** .

   The list of existing access flows appears.

2. Click on the **trash icon** ![image-20250221-142955.png](https://docs.trustbuilder.com/__attachments/a_3248a3d9e810288e6930c40d92b373dc8cc65c4fb14f5e7b1c64a92b3ee7daf3/image-20250221-142955.png?cb=f0e959c87fe4ee4b2dc51ee6c1b730cb) of the access flow you want to delete.

3. Click on **Yes, delete** to confirm your choice.

   ![image-20250221-143212.png](https://docs.trustbuilder.com/__attachments/a_9b787648c2288800ffcfff6e51927691d1b3a5487f317218da3fe7c25ccb15ba/image-20250221-143212.png?cb=aa47cd1e9213d440f03b30456ff3e81f)

The access flow is successfully deleted.

---
language: "en"
---
# Access Management

* [Defining Policies \& Rules](https://docs.trustbuilder.com/tb-io/defining-policies.md)
* [Defining Access flows](https://docs.trustbuilder.com/tb-io/access-flows.md)
* [Managing Certificates](https://docs.trustbuilder.com/tb-io/managing-certificates.md)
* [Defining Workflows](https://docs.trustbuilder.com/tb-io/workflows.md)
* [User Sessions](https://docs.trustbuilder.com/tb-io/user-sessions.md)
* [Adaptive Authentication](https://docs.trustbuilder.com/tb-io/adaptive-authentication.md)
* [Dynamic Authorization](https://docs.trustbuilder.com/tb-io/dynamic-authorization.md)
* [Client-level access](https://docs.trustbuilder.com/tb-io/client-level-access.md)

---
language: "en"
---
# Active directory adapter

The Active Directory Adapter allows TrustBuilder to perform various operations against an Active Directory server.

## Configuration

The adapter configuration specifies the adapter instance (adapter id), the global load-balancing settings and the configuration of one or more servers.  

|        Parameter        |                                                                                                                                                                                                                                          Description                                                                                                                                                                                                                                          |   Required    |
|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|
| AdapterUniqueID         | Unique name assigned to this adapter; the name is used to reference the adapter in the workflow. The ID has following requirements: * START with a letter or _ (underscore) * FOLLOWED by a combination of following characters: Letter, Number, '.' (dot), '-' (dash), '_' (underscore)                                                                                                                                                                                                      | **x**         |
| Type                    | The type of server to connection to. Possible values are RO and RW (default is RW). * RO: Read-Only * RW: Read-Write                                                                                                                                                                                                                                                                                                                                                                          | **x**         |
| **Host Settings:**      |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |               |
| Address                 | URL or IP of the backend LDAP Server                                                                                                                                                                                                                                                                                                                                                                                                                                                          | **x**         |
| Port                    | TCP Port of the backend LDAP Server                                                                                                                                                                                                                                                                                                                                                                                                                                                           | **x**         |
| **Transport Settings:** |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |               |
| ConnectionPool          | Allow the use of a connection pool. The poolsize is set at the JVM level                                                                                                                                                                                                                                                                                                                                                                                                                      |               |
| protocol                | SSL protocol version to be used for connection to the backend. Valid options are: **none, default,** ***sslv3,*** ***tlsv1 or was*** * no SSL (protocol = *none*) * default SSL settings (protocol = *default*) * explicit SSL settings (protocol =*sslv3* or *tlsv1*) * WebSphere setting (protocol = *was*) *If the selected protocol is* ***none*** *. None of the following Security Settings are required. However if you do place them in the security element, they should be correct* | **x**         |
| DN                      | DN to authenticate with, this user must have sufficient rights. It will only be used when no credentials are passed in the request.                                                                                                                                                                                                                                                                                                                                                           | **x** ^1^     |
| Password                | Type the password of the DN . This will be automatically encrypted when saving the adapter.                                                                                                                                                                                                                                                                                                                                                                                                   | **x** ^**1**^ |

^*1*^*if the selected protocol is none. None of the following Security Settings are required. However if you do place them in the security element, they should be correct Workflow Settings*

### Workflow Settings

A request for the adapter is prepared by specifying the following properties/scripts in the adapter activity: \* Input Property: the variable containing the instructions the adapter have to execute \* Output Property: the variable the adapter will store the response in after execution \* Before Adapter Script: script that will be executed before calling the adapter \* After Adapter Script: script that will be executed after the adapter fulfilled its task

#### Request - API

Common Request Attributes

The following list gives an overview of the attributes used in the request-API; examples on how to use these attributes can be found in the examples throughout this chapter.  

|    Option     |                                                                                                                                                                                                                                           Description                                                                                                                                                                                                                                           |
|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| baseDN        | Use baseDN as the starting point for the search action                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| Credentials   | Username and password overriding these specified in the "adapter configuration"                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Scope         | Specifies the search scope: * **LDAP_BASE** <!-- --> * **LDAP_ONE** <!-- --> * **LDAP_UNKNOWN** Search the entire subtree rooted at the named object. If the named object is not a Directory Context, search only the object. If the named object is a Directory Context, search the subtree rooted at the named object, including the named object itself. The search will not cross naming system boundaries. The NamingEnumeration that results from search() using <!-- --> * **LDAP_SUB:** |
| Filter        | Search filters enable you to define search criteria and provide more efficient and effective searches                                                                                                                                                                                                                                                                                                                                                                                           |
| Attributes    | The set of attributes that should be returned as a result of a search action. All the attributes are returned if not specified.                                                                                                                                                                                                                                                                                                                                                                 |
| Bindings      | The data that must be added/updated as part of an ADD/MODIFY-action; a data type (LDAP_STRING or LDAP_BINARY) per attribute can be given along.                                                                                                                                                                                                                                                                                                                                                 |
| IncludeValues | If set to yes: Retrieve attributes only (no values). This is useful when you just want to see if an attribute is present in an entry and are not interested in the specific values.                                                                                                                                                                                                                                                                                                             |
| defaultType   | Indicates the data type of the attributes as a result of a search action; LDAP_STRING is default behavior if not specified. * **LDAP_STRING**: Return as strings * **LDAP_BINARY**: return as base64 encoded binary                                                                                                                                                                                                                                                                             |

##### Authenticate

**LdapAuthenticateRequest** Tries an LDAP-bind with the specified DN and corresponding password.

    tb.ldapAuthenticateRequest(dn, password); 

**LdapAuthenticateSearchRequest** The search-request, resulting in one DN, is followed by an authenticate-request by combining: 1. The DN as a result of the search action, 2. the pasword given along in the parameter "password: "

    var credentials = {'user':'dn','password':"itsme"};
    tb.ldapAuthenticateSearchRequest({
     baseDn: 'dn',
     password: 'itsme',
     scope: LDAP_ONE,
     filter: "cn=filter",
     credentials:credentials,
    });

##### Search

**LdapSearchRequest** The LdapSearchRequest allows to search for entries in the LDAP-directory by specifying a base DN, a scope (one of base, one or sub) and an LDAP filter.

    var ldapreq = {
        dn : "<DN>",
        credentials:{user: "cn=<user>",password: "<password>"},
        filter : "(objectClass = inetOrgPerson)", //This will search for every inetOrgPerson object
     };

    tb.ldapSearchRequest(ldapreq); 

**LdapAddRequest** The ldapAddRequest allows to add objects to the specified DN.

    var credentials = {'user':'who','password':"itsme"};
    var bindings = [ { "name" : "a", "type" : LDAP_STRING, "values" : [ "x1" ] },
     { "name" : "b", "type" : LDAP_BINARY, "values" : [ "something base64 encoded" ] },
     { "name" : "c", "values" : [ "z1", "", "z2" ] } ];

    tb.ldapAddRequest({
     dn: 'dn',
     bindings: bindings,
     credentials: credentials
     });

##### Password

**LdapChangePasswordRequest**

The LdapChangePasswordRequest allows clients to change the password of given DN after verifying the current password. The actual operation is performed using the adapter's adminstrator credentials.

    tb.ldapChangePasswordRequest(dn,oldPassword,newPassword) 

**LdapSetPasswordRequest**

The LdapSetPasswordRequest allows clients to set the password of given DN. The actual operation is performed using the adapter's adminstrator credentials.

    tb.ldapSetPassword(dn,password) 

##### Delete

**LdapDeleteRequest**

The ldapDeleteRequest is used to delete a given object from the LDAP. The bind uses the adapter's adminstrator credentials, if a bindDN/bindPassword is not specified.

    tb.ldapDeleteRequest(dn-to-delete,bindDN,bindPassword) 

##### Modify

**LdapModifyRequest**

The LdapModifyRequest allows the client to modify one or more attributes of a given DN. Three modify actions are supported: \* ADD: adding values to a multi-valued attribute or setting the value of an empty single-valued attribute \* MODIFY: changing the value(s) of an attribute \* DELETE: deleting values from a multi-valued attribute or clearing a single-valued attribute.

These operations may be combined into a single request as illustrated below.

    tb.ldapModifyRequest({
        dn: 'dn',
        scope: scope,
        filter : "(objectClass = inetOrgPerson)",
        modifications => COMPLETE EXAMPLE.
     });

#### Response - API

**Common Properties**

The response API can be applied to the variable specified in the output property (see Workflow Settings): 1. to verify whether the action performed by the adapter was successful, 2. to query for the data returned by the adapter.

All responses have four properties in common:

* **status** Status flag indicating whether the response is ok (0) or not (1).

* **substatus** Response specific number indicating what the problem was, eg. http status code

* **message** Response specific message in case there was a problem (can be null)

* **rc** Return Code, a human readable code based on the substatus

The status flag indicates whether a request was valid yes or no; consequently, the message or return code (rc) can be used to give the end-user a reasonable explanation or send the information to the underlying logging system.

**Adapter Specific Properties**

The response from the active directory is the same as for the ldap adapter. please refer to that adapter for specific properties.

#### Response Codes

All response codes are inherited from the ldap adapter so you can find the extensive list there. Additional Notes

**Connection Pool** There is no option to specify the size of the connection pool. The JNDI interface only allows to set the connection pool size at the JVM level.

**SSL** In case the configuration specifies an explicit SSL protocol, the necessary stores (both in case of mutual SSL), store format (JKS or PKCS12) and password file must be set. Note that the chosen protocol may or may not be supported by a specific provider. The default SSL settings typically use the JVM security settings defined in system properties, but this need not be so. For instance, WebSphere allows administrators to configure the mapping of LDAP URLs onto SSL configurations (if no settings are defined at the JVM level),

**Load Balancing** A server is either of type RW (read-write) or of type RO (read-only), with RW the default type. Read-write servers accept all request types, whereas read-only servers only accept non-destructive operations (authenticate and search requests). In order not to complicate the load-balancer algorithm, the LdapAdapter uses a secondary load-balancer for write requests if not all servers accept write requests. The adapter then delegates requests to the proper load-balancer. Note that when two load-balancers are used, each balancer keeps track of server penalties independently to one another.

#### Example

**Connection Settings** For this example we are searching for a specific user against the active directory. We use for this purpose his windows login name (sAMAccountName). The Active directory adapter is configured to point to the Active Directory Server

**Workflow Settings** We have created for this example a very basic workflow that is searching for a fixed user. From the Endpoint the workflow is going to the AD Adapter. The before script is used to make the request to the adapter. The Script function is used to validate the response for errors and create a result to the endpoint.

**Making the request** In the before Adapter script we made a function ldapwinadSearch. This function is going to search for the user 'test' under a specific DN in the ldap. The user has different attributes in ldap, for Windows most common used is the sAMAccountName. If we view the LDIF of this user we see also the objectclasses. We left out some key/values in the example for readability.

    LDIF of user test
    dn: CN=test,CN=Users,DC=bat,DC=po,DC=securit,DC=biz
    objectClass: top
    objectClass: person
    objectClass: organizationalPerson
    objectClass: user
    cn: test
    instanceType: 4
    objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=bat,DC=po,DC=securit,DC=biz
    accountExpires: 9223372036854775807
    displayName: test
    distinguishedName: CN=test,CN=Users,DC=bat,DC=po,DC=securit,DC=biz
    givenName: test
    name: test
    objectGUID:: c5NSTNQMU0WC2RQQSsTahA==
    objectSid:: AQUAAAAAAAUVAAAAjHzyk5Op+wC7OboCXgQAAA==
    primaryGroupID: 513
    pwdLastSet: 129796511806093750
    sAMAccountName: test
    sAMAccountType: 805306368
    userPrincipalName: test@bat.po.securit.biz

So we create the ldapwinadSearch function to search the user 'test' :

    //ldapwinadSearch
    function ldapwinadSearch(workItem) {
        var ldapreq = {
            dn: "CN=Users,DC=bat,DC=po,DC=securit,DC=biz",
            filter: "sAMAccountName=test", //This will search for every inetOrgPerson object
            scope: LDAP_SUB
        };
        workItem.request = tb.ldapSearchRequest(ldapreq);
    }

This function will send the workItem.request variable to the AD adapter This request will be visible in the TRACE logging :

    Logging
    [WebContainer : 8] TRACE b.s.t.a.server.SingleServerPool - Sending request to winad034 [1]
    [WebContainer : 8] TRACE b.s.t.adapter.ldap.JndiServer - Searching for sAMAccountName=test within base CN=Users,DC=bat,DC=po,DC=securit,DC=biz [1]
    [WebContainer : 8] TRACE b.s.t.adapter.ldap.JndiServer - Binding with CN=Administrator,CN=Users,DC=bat,DC=po,DC=securit,DC=biz [1]
    [WebContainer : 8] TRACE b.s.t.adapter.ldap.JndiServer - Binding via pool [1]
    [WebContainer : 8] TRACE b.s.t.a.server.SingleServerPool - Request successfully completed [1]

**Handling the response** The AD Adapter now searches for the user, the response must be parsed by a script function. This can be a After Adapter Script', Condition or Script. We handle the response in this example as a After Adapter Script with the ldapwinadAfterSearch function.

    function ldapwinadAfterSearch(workItem) {
        var returned = workItem.response;
        log(returned, "Aftersearch");
        workItem.entryReturned = workItem.response.getEntries();
        workItem.entryUsed = workItem.entryReturned[0];
        log(workItem.entryReturned[0], "EntryReturned");
        switch (workItem.response.status) {
            case 0:
                switch (workItem.response.substatus) {
                    case 0:
                        break;
                    case 2:
                        log("A challenge was sent by the Ldap server");
                        break;
                }
                break;
            default:
                log("Active Directory LDAP has encountered an error");
                break;
        }
    }

The log function is here helping to debug the returned object. In the logfile this will give something like :

    Logging
    [WebContainer : 8] TRACE Engine.ScriptLogger - [ Aftersearch ] LdapResponse (
        status = 0, substatus = 0
        message =
        entry (
            objectClass (value = top, value = person, value = organizationalPerson, value = user)
            cn (value = test)
            givenName (value = test)
            distinguishedName (value = CN=test,CN=Users,DC=bat,DC=po,DC=securit,DC=biz)
            instanceType (value = 4)
      displayName (value = test)
            uSNCreated (value = 20534)
            uSNChanged (value = 34980)
            name (value = test)
            objectGUID (value = sLSEJ)
            userAccountControl (value = 66048)
            badPwdCount (value = 1)
            codePage (value = 0)
            countryCode (value = 0)
      primaryGroupID (value = 513)
            objectSid (value = ?^)
            logonCount (value = 2)
            sAMAccountName (value = test)
            sAMAccountType (value = 805306368)
            userPrincipalName (value = test@bat.po.securit.biz)
            objectCategory (value = CN=Person,CN=Schema,CN=Configuration,DC=bat,DC=po,DC=securit,DC=biz)
        )

We are putting the first returned DN in the workItem.entryUsed variable. For this we first used the function getEntries() and from here we selected the first entry. ( workItem.entryReturned\[0\] ) The next script function is used to create the output based on the adapter status and giving back the DN of the user found.

    [WebContainer : 8] TRACE Engine.ScriptLogger - [ EntryReturned ] [ CN=test,CN=Users,DC=bat,DC=po,DC=securit,DC=biz ] [1]

    winadOutput
    function winadOutput(workItem) {
        var entry = workItem.entryUsed;
        var bodygood = "<h1>WinAD OK " + entry + " </h1>";
        var bodybad = "<h1>WinAD NOT OK</h1>";
        var respcookies = null;
        var respheaders = null;
        if (workItem.response.status == 0) {
            workItem.output = tb.generateResponse(bodygood,/*defaults:, null , null, 200*/);
        }
        else {
            workItem.output = tb.generateResponse(bodybad, respheaders, respcookies, 501);
        }
    }

In this function we set the DN entry found in the body after the a small message. If the adapter had no errors (status ==0) we show the ok page. Otherwise we show a bad page with a response error. In the logfile this will be shown as output :

    Logging
    [WebContainer : 8] TRACE Engine.WorkItem - set ___OUTPUT___=EndpointResponse (
        status = 200, substatus = 0
        Status = 200
        <h1>WinAD OK [ CN=test,CN=Users,DC=bat,DC=po,DC=securit,DC=biz ] </h1>
    ) [1]

This will complete the workflow and the output is returned.

**Mock response function**

    function searchDevice(){
        return {
            status:0,
            substatus:0,
            getEntries: function(){
                return [{
                    dn: 'cn=koen,o=securit',
                    getAttributeValue: function(item){
                        switch (item){
                            case 'tfDevicePIN': return '123';
                            case 'sitDN': return 'cn=koen,o=securit';
                            case 'tfRegCode': return '123';
                            case 'tfDeviceToken': return '123';
                            case 'tfDevicePlatform': return 'ios';
                        }
                    }
                }];
            }
        }
    }

---
language: "en"
---
# Active Directory IDP

Active Directory IDP types provide a connection to an Active Directory.

The Active Directory can be used for authentications (as an authentication method), and after the authentication with another IDP. The Active Directory can also be queried for additional user data *(for attribute lookup for example)*.  
**About Attributes Lookup**

This has to be configured on a different Identity Provider *(Let's say: "IDP A")*. When configured, this Active directory can be used as a user information database. After a successful authentication to IDP A, the Active Directory will be queried for this user with the Technical Account (provided), requesting all the attributes which are configured on the Identity overview page of the Active Directory IDP.

## Configure a custom Active Directory IDP

From the admin portal, go to **Integrations** \> **Identity Providers** \> **Custom AD IDP**.  

|           Field            |                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
|----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Display Name               | The display name of the Identity Provider If a known name is used (such as Facebook, Google, LinkedIn) the corresponding logo will automatically be provided.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Description                | The Identity Provider description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Enable auto-provisionning  | TrustBuilder automatically creates a user account when a new user authenticates successfully. It is enabled by default. Disable it if you want to control user provisioning in another way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| Provisioning Workflow      | Select a workflow that will be executed after the Authentication is complete. The workflows can be used, for instance, to provision users in a user database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Type                       | "Active Directory"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Subject                    | Primary attribute that is used to identify the Subject                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Manage Certificates        | You can manage certificates from the Certificates configuration page. You can also add or import certificates from the Identity provider configuration. * Context → Defines what the certificate is used for. * Key - Signing: Used to sign messages to the IDP * Key - Encryption: Used to decrypt the messages (assertions) sent from the IDP * Key - TLS: Used to initiate a secure connection (TLS) to the IDP * Trust - Signing: Used to verify the signature of messages sent by the IDP * Trust - TLS: Used to accept a secure connection (TLS) from the IDP * Certificate Alias → The alias of the certificate to use for this context. * Used From → Defines from when this certificate may be used. In some cases these periods may overlap for the same context (eg. during a certificate renewal), but in other cases they may never overlap (Key - Signing, Key - TLS). * Used Until → Defines until when this certificate may be used. See Certificates |
| Active Directory Server    | IP Address (or hostname) to connect to the Active Directory Server                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Port Number                | Port number to connect to the Active Directory Server                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Encryption Type            | TLS: Use the TLS protocol to initiate a connection to the Active Directory Server Start_TLS: Use the STARTTLS protocol to initiate a connection to the Active Directory Server                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| Netbios Domain Name        | The (sub)domain name (without the extension) that will be used to look up the user for.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| Technical Account User     | Required for Attribute Lookup: an admin user account name to access more sensitive data on the active directory                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| Technical Account Password | Required for Attribute Lookup: an admin user account password to access more sensitive data on the active directory                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Attribute Name for Subject | The attribute name that will be queried in the Active Directory for the authenticating user, that will be returned as the subject value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Page Setting               | Select the template to be used to display a 'log in with Active Directory'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

---
language: "en"
---
# Adapters

## Available adapters

* [Active directory adapter](https://docs.trustbuilder.com/tb-io/active-directory-adapter.md)
* [Certificate adapter](https://docs.trustbuilder.com/tb-io/certificate-adapter.md)
* [Custom adapter](https://docs.trustbuilder.com/tb-io/custom-adapter.md)
* [Digipass DB adapter](https://docs.trustbuilder.com/tb-io/digipass-db-adapter.md)
* [Gemalto adapter](https://docs.trustbuilder.com/tb-io/gemalto-adapter.md)
* [Http adapter](https://docs.trustbuilder.com/tb-io/http-adapter.md)
* [JDBC adapter](https://docs.trustbuilder.com/tb-io/jdbc-adapter.md)
* [LDAP adapter](https://docs.trustbuilder.com/tb-io/ldap-adapter.md)
* [OAth adapter (TOTPAdapter)](https://docs.trustbuilder.com/tb-io/oath-adapter-totpadapter.md)
* [OAuth adapter](https://docs.trustbuilder.com/tb-io/oauth-adapter.md)
* [OCSP adapter](https://docs.trustbuilder.com/tb-io/ocsp-adapter.md)
* [Push adapter](https://docs.trustbuilder.com/tb-io/push-adapter.md)
* [Radius adapter](https://docs.trustbuilder.com/tb-io/radius-adapter.md)
* [SAML adapter](https://docs.trustbuilder.com/tb-io/saml-adapter.md)
* [Smpp adapter](https://docs.trustbuilder.com/tb-io/smpp-adapter.md)
* [Smtp adapter](https://docs.trustbuilder.com/tb-io/smtp-adapter.md)
* [TAM adapter](https://docs.trustbuilder.com/tb-io/tam-adapter.md)
* [Transactional adapter](https://docs.trustbuilder.com/tb-io/transactional-adapter.md)

### Loadbalancing

The adapter may specify multiple servers. Servers with equal priorities are grouped into server pools. When executing a request, the adapter will use the load-balancing settings from each individual server pool, until a successful response has been received or until all server pools have been exhausted. (Lower priority numbers indicate higher priorities.)

Load Balancing settings

The load balancing settings specify timeouts for connections and requests, the number of request attempts and eventual penalties in case a server fails to respond correctly. In the absence of failures, the load-balancer proceeds in a round-robin way. In case of failure the behavior of the load-balancer depends on the type of error. If, say, an authenticate request does not succeed because the HTTP server does not accept the credentials, the load-balancing algorithm considers the response as technically correct, and returns this response. (We assume that the various servers are properly synchronized and that e.g. failure to authenticate against one server implies failure to authenticate against all servers.) Failure to connect because a server is temporarily down, however, will cause the load-balancer to try another server (or other servers), up to the maximum number of request attempts. The offending server is penalized, which may cause it to be skipped a number of times if servers with a lower penalty are available. Since the load-balancing algorithm is adapter type agnostic, is uses callbacks to the adapter to interpret the status of a server response and to generate a proper response in case of failure.

### General information

Some adapters may specify multiple servers in their configuration. when specifying multiple servers, loadbalancing settings can be configured. these adapters are:

* LDAP

* HTTP

* Radius

* GEMALTO

* OCSP

#### Priorities

Servers with equal priorities are grouped into server pools. Lower priority numbers indicate higher priorities.

When executing a request, the adapter will use the load-balancing settings from each individual server pool, until a successful response has been received or until all server pools have been exhausted. The server configured last in the adapter configuration will be checked first. The load balancing settings specify timeouts for connections and requests, the number of request attempts and eventual penalties in case a server fails to respond correctly. In the absence or failures, the load-balancer proceeds in a round-robin way. In case of failure the behavior of the load-balancer depends on the type of error. If, say, an authenticate request does not succeed because the HTTP server does not accept the credentials, the load-balancing algorithm considers the response as technically correct, and returns this response. (We assume that the various servers are properly synchronized and that e.g. failure to authenticate against one server implies failure to authenticate against all servers.) Failure to connect because a server is temporarily down, however, will cause the load-balancer to try another server (or other servers), up to the maximum number of request attempts. The offending server is penalized, which may cause it to be skipped a number of times if servers with a lower penalty are available. Since the load-balancing algorithm is adapter type agnostic, is uses callbacks to the adapter to interpret the status of a server response and to generate a proper response in case of failure.

The XML example below lists the available load-balancing settings. Example Load-Balancing Settings

    <stb:LoadBalancing>
     <stb:ConnectionTimeout>3000</stb:ConnectionTimeout>
     <stb:RequestTimeout>5000</stb:RequestTimeout>
     <stb:RequestAttempts>2</stb:RequestAttempts>
     <stb:ServerRequestAttempts>1</stb:ServerRequestAttempts>
     <stb:PenaltyLimit>100</stb:PenaltyLimit>
     <stb:ConnectionFailureWeight>50</stb:ConnectionFailureWeight>
     <stb:ConnectionFailureThreshold>4</stb:ConnectionFailureThreshold>
     <stb:HighLoadThreshold>1000</stb:HighLoadThreshold>
     <stb:HighLoadWeight>2</stb:HighLoadWeight>
    </stb:LoadBalancing>

Server Pool and ServerRequestAttempts

If a server pool contains 3 servers and the number of requests per server is 2, then the load-balancer will attempt at most 6 requests for that pool. If the maximum number of requests for the server pool is smaller, say 4, then at most 4 attempts will be made. In the degenerate case of a pool with a single server, only the RequestAttempts value will be used.

Load-balancing Settings reference  

|         Parameter          |                                                                          Description                                                                          | Required |
|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
| ConnectionTimeout          | Timeout to connect (milliseconds)                                                                                                                             |          |
| RequestTimeout             | Timeout to read the response (milliseconds)                                                                                                                   |          |
| RequestAttempts            | Maximum number of request per server pool if set to 0 there is no limit this number must be at least equal to the number of servers configured in the adapter |          |
| ServerRequestAttempts      | Maximum number of requests per sever                                                                                                                          | **x**    |
| PenaltyLimit               | Limit for server penalties if set to 0 there is no limit                                                                                                      |          |
| ConnectionFailureThreshold | Number of times for connection or request to timeout before increasing the server penalty                                                                     |          |
| ConnectionFailureWeight    | The step to use to increase the amount up to the penalty limit                                                                                                |          |
| HighLoadThreshold          | If the request takes longer than this amount, increase the server penalty (milliseconds)                                                                      |          |
| HighLoadWeight             | The step to use to increase the amount up to the server penalty if the server responds slowly                                                                 |          |

#### Key \& Truststores

The following adapters can be configured to use SSL for communication to a third-party backend system:

* HTTP

* LDAP

The use of SSL requires the creation of a trust and/or keystore:

* Trust store: stores public certificates

* Key store: stores either private keys or the combination of private key with their corresponding certificate

Some important remarks:

1. Both the stores can co-exist,

2. the keystore is used as truststore if no explicit truststore is defined.

From security point of view, it is recommended to make a clear distinction between a truststore and a keystore:

* A truststore does only contain public certificates making it ideal to share with other people.

* A keystore on the other hand does contain private keys, which must be kept private.

#### Configuration

**Type**

Both the key- and truststore are Java Keystores (JKS), a repository of security certificates, which can be created by broad range of free and commercial tools

**Location**

The location of the stores depends on the parameter "SecurityProtocol" selected in the adapter:

**Where**

* Default: uses the configuration as configured in the underlying application server

* WAS: uses the key- and truststore as configured in WebSphere

* NONE: no SSL is used

* TLSV1, SSLV3: uses the key- and/or truststore as defined in the TrustBuilder config.xml

##### Usage

**Certificate Validation**

If required a specific adapter can allow you to specify a certificate to validate against, if not the truststore is being used as a validation mechanism. Ie. if a certificate in the truststore can be used to validate the connection it will be allowed.

**Mutual SSL**

As for the validation against the certificate, if a private key is needed this can be identified in the specific adapter and looked up in the keystore defined either in the config.xml or externally.

**Classpath**

It is possible to use the stores in your classpath. To use the key/truststore in your classpath you must include the leading / in front of you keystore file in the config.

#### Available adapters

The template beneath is used to describe the functionality for each adapter and how it can be used.

**Functionality** A short description describing the function of the adapter

**Prerequisites** Things to do before the adapter can be used

**Connection Settings** Details the parameters required to connect to a third-party resource

**Workflow Settings** Details the parameters that must be set to use the adapter in a workflow.

**Request - API** List of methods made available by the adapter

**Response - API** The response returned by the adapter as a result of a request

**Response Codes** List of possible response codes

**Additional Notes** Some side remarks

---
language: "en"
---
# Adaptive Authentication

A login session refers to the period of time during which a user is logged into a system or website. It begins when the user enters their login credentials and ends when they log out or the session expires. During a login session, the user is able to access resources and perform actions that are restricted to logged-in users.

In contrast to traditional IAM solutions, TrustBuilder maintains an evolving lifecycle of a session. Moreover, TrustBuilder maintains the lifecycle server-side and does ++not++ need cookies.

## Types of sessions

There are several layers where sessions can be created when users log in:

### **Service Provider Session**

An application, a platform or a Service Provider in general may maintain a session for its users. While such Service Provider uses TrustBuilder to authenticate users, it may also keep track of users that have logged in. For example a regular web application may keep a user session by setting a session cookie in the user's browser. When the Service Provider keeps a Persistent Cookie, the cookie survives any browser session to give the user the experience of "Keep me logged on".

#### **Client App Session**

A mobile app or a Client App in general may maintain a session to remember a user who signed in to the app by keeping the user's login in Local Storage, for example in the form of an id token and refresh token. The user can reactivate such 'session' using a smartphone's PIN, face-id or fingerprint.

#### **Identity Provider Session**

An identity provider can play 3 roles:

1. provide identity information during registration or to supply Derived Attributes at a later stage

2. provide an external authentication factor

3. provide a token as proof that the user has been authenticated in a federated way.

Identity providers providing high levels of assurance (identity assurance and/or authentiucation assurance) typically do not maintain a session of the user.

In case of social identity providers, such Facebook or Google, a session may be maintained so that when a user already has a valid sign-in, they will not be prompted again to sign in. A social identity provider may maintain a session using a session cookie, a persistent cookie, a token in Local Storage (e.g. SAML or OIDC) or other mechanism.

#### **TrustBuilder Session**

While the layers above provide user convenince in a certain context, TrustBuilder also maintains a session on the Authentication Server. This server-side session layer makes the SSO experience possible for inbound SSO implementations.

While cookies may provide convenience, they are vulnerable for so-called man-in-the-middle attacks. This is one of the reasons why TrustBuilder does ++not++ set cookies.

Long lived tokens are also vulnerable to token stealing. This is one of the reasons why TrustBuilder reserves long lived tokens, ie. id tokens, for the client app only and they must never leave the client app and be passed around.

## Adaptive Authentication

Adaptive authentication typically only requires a second factor of authentication when it is deemed necessary, based on the level of risk associated with a login attempt. For example, if a user is logging in from a known location, using a device that has been previously used to access the account, and at a time when the user would typically be accessing the account, the login attempt may be considered low-risk and only a single factor (e.g. a password) may be required.

However, if the login attempt is from an unknown location, from an unknown device, or is taking place outside of the user's typical access patterns, the system may determine that the login attempt is high-risk, and require additional factors of authentication, such as a one-time code sent to a mobile phone, or a biometric scan, to confirm the user's identity before allowing access.

By implementing adaptive authentication, the user experience is improved as they are not frequently asked for a second factor when it is not needed.

## Assessing risk with Device Fingerprint

A system can know what device a user is using by using various methods such as browser fingerprints, device fingerprints, or device identification numbers.

A browser fingerprint is a collection of information about the browser and device being used, such as the browser version, installed fonts, and screen resolution, which can be used to identify a specific device.

A device fingerprint is a unique identifier that is created by combining various hardware and software characteristics of a device, such as the device's IP address, MAC address, and browser settings.

A device identification number, such as IMEI or serial number, can also be used to identify a device. IMEI stands for International Mobile Equipment Identity, it is a unique number assigned to every mobile phone.

Additionally, the system can also use cookies, local storage or browser storage to store the device information. Once the user returns to the website, the system can read the stored information to identify the device.

It's worth noting that these methods can be circumvented by the user if they use anonymity tools such as VPNs, Proxies, browser plugins or browser in private mode, so the system must also take into account other factors such as the location, behavior and IP address to determine the level of risk associated with a login attempt.

## Assessing risk with IP Address

IP addresses can be used as a factor in determining the level of risk associated with a login attempt, but their relevance can vary depending on the context and the method used to obtain them.

In general, IP addresses can be useful in determining a user's location and identifying whether or not a login attempt is taking place from a known location. However, the accuracy of location information based on IP addresses can be limited, especially with the increasing use of VPNs, proxies, and other anonymity tools that can make it difficult to determine the true location of a device.

Also, IP addresses can be easily spoofed, which means that an attacker can use a different IP address to make it appear as if they are logging in from a different location.

Therefore, while IP addresses can be a useful factor in adaptive authentication, they should not be relied upon as the sole method of determining the level of risk associated with a login attempt. It is important to consider other factors, such as the device being used, the time of day, and the user's behavior, to make a more accurate risk assessment.

---
language: "en"
---
# Additional Configuration

* [Configuring notifications](https://docs.trustbuilder.com/tb-io/configuring-notifications.md)
* [Hosted Login](https://docs.trustbuilder.com/tb-io/hosted-login.md)
* [Manage templates](https://docs.trustbuilder.com/tb-io/manage-templates.md)

---
language: "en"
---
# Workflows admin tabs

* [Configuration Adapters Tab](https://docs.trustbuilder.com/tb-io/configuration-adapters-tab.md)
* [Services Tab](https://docs.trustbuilder.com/tb-io/services-tab.md)
* [Workflows Tab](https://docs.trustbuilder.com/tb-io/workflows-tab.md)
* [Tests Tab](https://docs.trustbuilder.com/tb-io/tests-tab.md)
* [Scripts Tab](https://docs.trustbuilder.com/tb-io/scripts-tab.md)
* [Templates Tab](https://docs.trustbuilder.com/tb-io/templates-tab.md)
* [Logging Tab](https://docs.trustbuilder.com/tb-io/logging-tab.md)
* [Properties Tab](https://docs.trustbuilder.com/tb-io/properties-tab.md)
* [Key and Trust Store Tab](https://docs.trustbuilder.com/tb-io/key-and-trust-store-tab.md)
* [Components Tab](https://docs.trustbuilder.com/tb-io/components-tab.md)
* [Libraries Tab](https://docs.trustbuilder.com/tb-io/libraries-tab.md)
* [Export and Download](https://docs.trustbuilder.com/tb-io/export-and-download.md)

---
language: "en"
---
# Release Notes

The following page refers to TrustBuilder.io releases. Please, see [Releases FAQ](https://docs.trustbuilder.com/tb-io/releases-faq.md) to know more.

[Visit our status page](https://status.trustbuilder.com/) to stay informed of outages and scheduled maintenance for the TrustBuilder.io platform. On the status page, click on **Subscribe to updates** to receive alerts whenever we create, update or resolve an incident.  
Starting from the 2024.8.0 release, version names follows a new format: **Year.ReleaseNumber.HotfixNumber**. This change reflects updates to the architecture and new components.
Production environment  

## **2026.5.1**

*July 23, 2026 in preview*

* Added "*Last authenticated* " information for each IdP in the "Provision" tab of a User profile page. **Enabled on demand**

* Users page**:** User profiles can now be opened in a new browser tab using the right-click context menu.

## 2026.4.0

*June 18, 2026*

* Removed `optimizeConsentTable` operation.

  Contact [++*TrustBuilder Support*++](https://support.customer.trustbuilder.com/) for consent table optimization

* Improved UI of the editor view of Authorization Rules.

## 2026.3.0

*May 5, 2026*

* The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` has been removed. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

* The [Trustbuilder.io API documentation](https://api.trustbuilder.io/api/documentation) interface has been redesigned. The previous Swagger UI has been replaced with a more structured and user-friendly interface.

  ![image-20260417-081235.png](https://docs.trustbuilder.com/__attachments/a_1c2c1eab8404822b20a710383934f4de00c2d023b7ea1a4b429c2acfa69fc38b/image-20260417-081235.png?cb=949c7ee3d520ea6e84c3c6b1b2226f7b)

  ![info](https://docs.trustbuilder.com/__attachments/a_a1e7a018bd8ddf5b2ec89228ef449cc718fc4afeccaa8c0cddce706f846ab898/atlassian-info?cb=feab5cd71111204d6b52545f3027dd0c) *No changes have been made to the API itself, only the documentation interface has been updated.*
* Bug fix

## 2026.2.1

*March 26, 2026*

* Bug fix that prevented users with delegation rights from viewing user details within their scope.

The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` is deprecated and will be removed in a future release. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

## 2026.1.0

*January 29, 2026*

* **Access flows**: SP and IdP descriptions are now displayed in the access flow overview on the configuration page.

  ![Access flows improvements.png](https://docs.trustbuilder.com/__attachments/a_36367b9280e444cc244d654d5776f43f00e346ae7c9d2531f9823fba13c43f22/Access%20flows%20improvements.png?cb=00b81d26d4e9411fc27920406b85803d)
* **Logs improvement**

* **Bug fixes**

The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` is deprecated and will be removed in a future release. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

## **2025.9.2**

*December 4, 2024*

* **IdPs configuration** :auto-provisioning can now be disabled.

  ![20251117-1013-51.5245380-20251117-101355.gif](https://docs.trustbuilder.com/__attachments/a_3dbeb0608b7d12b807e58d4340bb1e6bba967757003698815ee556893a2e78b7/20251117-1013-51.5245380-20251117-101355.gif?cb=42e16342d1df8636292049f175c202f8)
* **SAML IdPs** : added support of `<samlp:Scoping>` in AuthnRequests to ensure eHerkenning and eIDAS compliance. Admins can now declare *Scoping IdPs*.

  ![image-20251117-105905.png](https://docs.trustbuilder.com/__attachments/a_b280309d153b925fc65e2322d9cf3672e00b532c80afa3aaac7bf6155d9d353f/image-20251117-105905.png?cb=b13b83af84d202afa2305bac14b98b99)
* **OAuth2 JWT tokens**: an option for exposing the scope claim as a space-separated string has been added (for compliance with RFC 9068). The array of values (old behavior) remains the default.

  ![image-20251117-130757.png](https://docs.trustbuilder.com/__attachments/a_595020569da3331cd6ea22ddbb9100bcb8999705fdb8e0ab66291e9776d1f15e/image-20251117-130757.png?cb=2675713bfc333216a01dc15faf873b7f)
* **Logs** now include more information when a user is not found during login.

* **Bug fixes**:

  * Security Fix

  * Attribute rules using *ENUMERATION* values are now correctly saved and displayed in the admin portal *(Service Provider \> Attribute Rule)*.

  * Added a new `GET users/{user_id}/blocks` endpoint to fix an issue where the user's blocked status was not updated correctly in the admin portal.

    ⚠️ This new endpoint is the definitive way to retrieve the blocked status for a single user. The `is_blocked` old field in `GET/POST/PUT/PATCH users/{user_id}` is deprecated and will be removed in a future release.

  * The search behavior in user tab filter has been modified for text attributes:

    * `Equals` (default) was case-insensitive and is now case-sensitive.

    * `Contains` doesn't change and is still case-insensitive.

## 2025.8.1

*October 30, 2025*

* Improved error handling to prevent system exceptions during authentication failures.

* Improved support of multi-valued JSON user attributes in OAuth ID token claims

* Bug fixes

## 2025.7.2

*September 11, 2025*

* User attribute names must now be unique

* Improvement of consent management: expired consents are no longer stored.

## 2025.6.1

*July 31, 2025*

* Security: The HSTS Header `max-age` is now set to 1 year (=31 536 000 seconds)

* API: Updated endpoints to match REST standards, returning a 201 (CREATED) status code for a POST creation, instead of 200 (OK). This applies to /users and /persona-definitions.

* Improved handling of missing user consent

* Bug fixes

## 2025.5.0

*July 1, 2025*

* Menu updates in Admin Portal:

  * *Identity Management* has been renamed to *Directory*

  * *Identity Providers* has been moved to a new section called *Integrations*

    ![Nouveau menu.png](/__attachments/a_538fdd326e1301c8fad34a5aece6c338b7fbf14cc7728277dbe46ecb14fc1bd2/Nouveau%20menu.png?cb=4362d8f0100532bbbc1d7b0c3369d8ba)
* Improved policy-driven access flow when a derived attribute is used

* Bug fixes

## 2025.4.0

*June 5, 2025*

* Administrators can now block and unblock users.

  ![Block user.gif](https://docs.trustbuilder.com/__attachments/a_8f7d473bcefa62bd8da9d52e4627849830a4d1567b274c961906f14b19dc4ca9/Block%20user.gif?cb=b2225fa36e14d87dc7c8cc7b778ef1c2)
* HSTS header is now optional in Gateway

* FIDO2 authentication - Feature enabled on demand: support of French and Dutch languages in registration and login pages.

* Change the management of session cookie to avoid conflicts.

* Bug and security fixes

## 2025.3.0

*May 15, 2025*

* **FIDO2 authentication - Feature enabled on demand:**

  Improved behavior at user deletion: all user security keys are now automatically deleted

* **Self-Service Portal**: Users can now rename their security keys.

  ![key renaming in release note.gif](https://docs.trustbuilder.com/__attachments/a_1fdb88143209fcb0457d487238a0b560506ffcc8d5896f065eb8a0b4b58da5cb/key%20renaming%20in%20release%20note.gif?cb=ee929509a054cd183272a88f631c10c7)
* Performance improvement

* Bug fixes

## 2025.2.0

*February 20, 2025*

* \[Beta\] FIDO2 authentication - **Feature enabled on demand**

  * FIDO2 Registration policy is now visible and can be edited

  * The username is now captured and stored during registration to improve the authentication experience.

* Self-Service portal

  * Users can view the status of their security keys.

  * Multi-language support has been added.

* Improve logging on Authentication and Authorization events

* Remove Service Catalog support on IDP and SP creation pages

* Bug fixes

  * Add missing confirmation messages when clicking Save.

  * Other bug fixes

## 2025.1.1

*January 30, 2025*

* Database optimizations

## 2025.1.0

*January 23, 2024*

* Bug fixes

  * Buttons sometimes not be visible on pop-ups

  * Persona invitation link not followed after login

  * E-mail verification field might revert to FALSE.

  * Other bug fixes.

* \[Beta\] FIDO2 authentication - **Feature enabled on demand**

  * Improved error messages when registering a key via the Self-Service Portal

## 2024.9.1

*December 19, 2024*

* Fixed an issue with user and persona events handling.

## 2024.9.0 (11.2.26)

*December 12, 2024*

* \[Beta\] Support of FIDO2 security key as a new authentication method - **Feature enabled on demand**

  [*More information*](https://docs.trustbuilder.com/tb-io/trustbuilder-fido2.md)

* Sign-up option is a configurable feature on login page

  [*More information*](https://docs.trustbuilder.com/tb-io/how-to-enable-disable-user-self-registration.md)

* Bug fixes

## 2024.8.0 *(11.2.25)*

*November 14, 2024*

* Request ID can be provided to the user to report a problem with authorization

* User self-registration can be disabled in the administration

* User caching can be disabled in the administration

* Performance improvements

* Bug fixes

## 11.2.24

*October 3, 2024*

* Self-Service portal \> shows active persona information

* Performance improvements

* Bug fixes

## 11.2.23

*July 23, 2024*

* Admin Portal: added Delegated Administration feature

  [*More information*](https://docs.trustbuilder.com/tb-io/delegated-administration.md)

* Self-Service Portal:

  * Added user personas management capability

  * Users can now delegate their personas to other users

  * Users can now see and manage requests

    [*More information*](/tb-io/self-service-portal.md)

* Performance improvements

* Bug fixes

## 11.2.22

*May 30, 2024*

* Admin Portal \> Added entitlements parameter to personas

* Refactored endpoint for tenant queries

* Bug fixes

## 11.2.21

*May 02, 2024*

* Improved UX on viewing user profile

* Accessibility improvements

* Performance improvements

* Better explanation of some errors to users

* Bug fixes

## 11.2.20

*March 28, 2024*

* Identity Manager \> enforces attribute definitions marked as unique to ensure the uniqueness of values in user profiles

* Identity Manager \> improves the behavior when adding a unique property to an existing attribute definition

* Policy Engine \> custom attributes are now supported in policy rules on user level

* Admin Portal \> allows to set a persona as preferred from the list of personas

* Logs improvements

* Bug fixes

## 11.2.19

*February 9, 2024*

* Policy Engine \> persona attributes are now supported in policy rules

* Admin Portal \> now allows to filter users by custom attributes in users overview

* Admin Portal \> improved the UI of rules configuration interface

* Access Management \> improved the authentication process to remain robust and error-free (ACR handling)

* Identity Manager \> now allows to define a display name to persona definition

* Session Manager \> improved persona selection to use the right attributes

* Bug fixes

## 11.2.18

*January 25, 2024*

* Bug fix

## 11.2.17

*January 4, 2024*

* Admin Portal \> now allows to filter users by persona in users overview

* Admin Portal \> added pagination to user profiles overview

* Identity Manager \> improved the behavior of user profiles creation with required custom attributes

* Identity Manager \> now allows to add custom top-level attributes to user profiles

* Admin portal \> improved JSON mode switching behavior

* Admin Portal and Self-Service Portal \> improved the returned error messages in persona editor

* APIs \> changed the base URL of TrustBuilder.IO API (preview and production environments) - [More information](https://docs.trustbuilder.com/tb-io/trustbuilder-io-api.md)

* Logs improvements

* Bug fixes

## 11.2.13

*October 26, 2023*

* Admin Portal \> improved the behavior after deleting a persona definition

* Admin Portal \> IP ranges can now be added to Admin Portal access restrictions

* Self-Service Portal \> now allows to edit email and username

* Bug fixes

## 11.2.12

*October 7, 2023*

* Policy editor \> now supports the entire range of attributes

* Admin Portal and Self-Service Portal \> now allows to search for an attribute when adding a filter

* Fixes a refresh token issue relative to PKCE Authorization grant

* Bug fixes

## 11.2.11

*October 5, 2023*

* Admin Portal \> Improve user administration screens

* Identity Manager \> Event on persona deletion

* Policy Engine now supports the use of persona attributes

* Bug fixes

## 11.2.10

*August 31, 2023*

* Identity Manager \> API now allows to add custom attributes at top-level

* Bug fixes

## 11.2.9

*July 19, 2023*

* Admin Portal \> Native integration of TrustBuilder MFA

* Identity Manager \> Native bi-directional synchronization with TrustBuilder MFA

* Identity Manager \> Users \> auto-provisioning of roles to TrustBuilder MFA based on Administrator Persona

* Admin Portal \> Policy \> now allows to create a rule while editing a policy

* Admin Portal \> Rule \> now allows deletion of an expressions

* Admin Portal \> filtering is now case-insensitive

* Admin Portal \> has restructured menu

* Bug fixes

## 11.2.8

*July 6, 2023*

* Admin Portal \> Access Flows now allows policies to be linked

* Admin Portal \> Identity Providers now includes AppleID configuration

* Policy Engine now protects against accidental deletion of policies that are in use

* Admin Portal \> Policies now allows rules to be created while adding it to a policy

* Admin Portal \> Policies now allows policies and rules to contain a `description`

* Admin Portal \> Rules now supports `has_value` and `is_empty` in visual mode

* Hosted Login `tb-login` now allows forgot-password to be linked to external systems, e.g. other IAM

## 11.2.7

*May 23, 2023*

* Identity Manager introduces `PATCH` for deletion of attributes

* Admin Portal \> Policies now allows the rules to be combined visually

* Admin Portal \> Policies now provides more guidance in JSON editor

* Admin Portal now shows the TB.io version number of the tenant

## 11.2.6

*May 9, 2023*

* Admin Portal \> Rules allows `obligations` to be added in visual mode

* Admin Portal \> Rules allows `equals` and `not_equals` expression in visual mode

* Admin Portal \> Users allows the filtering to be reset

* Policy Engine now uses the term `DENY_OVERRIDES` instead of `ORDERED_DENY_OVERRIDES`

* Hosted Login now supports Swedish, French, and German

* TB.Connect bug fixes in SAML and OIDC handlers

## 11.2.5

*April 27, 2023*

* Policy Engine introduces the `elem_match` operator in rule expressions and renames `deny_overrides`

* Session Manager enforces `status`, `valid_from` and `valid_till` during persona selection

* Identity Manager enables attribute deletion and persona attribute setting through the `PATCH` endpoint

* Hosted Login adds support for Swedish, French, German

* Admin Portal \> Users allows sorting by any column

* Admin Portal and Self-Service Portal show the `scope` on the persona tile

* Bug fixes

* Security fix in Self-Service Portal

## 11.2.4

*April 12, 2023*

* Hosted Login enables language selection

* Hosted Login defaults to `user_name` if `given_name` and `family_name` or not set

* Admin Portal enables user list to be sorted

* Admin Portal enables `scope` of a persona to be edited

* Admin Portal resolves concurrent user editing conflicts between multiple users admins

* Bug fixes

## 11.2.3

*March 29, 2023*

* Extends Identity Management API with `PATCH` endpoints on user and persona

* Adds filtering by custom attributes to user overview

* Shows `updated_at` and `created_at` in the user overview

* Prevents that Persona definitions contain duplicate attributes or undefined attributes

* Extends the Policy Engine language with `not`, `not_equals`, `not_in`, `older_than`, `not_older_than`

* Relaxes uniqueness constraint on attribute displayname to uniqueness per category

* TB.Connect:

  * Extends the Application Catalogue with any OAuth2 SP

  * Receives session information with HTTP 200 response from Session Manager

  * Fixed issue with missing claims after token exchange

* Bug fixes

## 11.2.2

*March 13, 2023*

* Extends the Policy Engine rule expression language with `$session.persona`

* Session Manager provides an endpoint to store persona selection

* Allows description and metadata to be added to policies and rules

* Allows policy name to be changed in the visual editor

* Allows customization of the persona selection screen

* Adds filtering by native attributes to user overview

* Enhances the login screen to make self-registration configurable

* Renames the attribute `member_of` into `entitlements`

* Publishes event on event bus at "add/update tenant"

* Auto-creates a TB.Connect instance when creating a new tenant in TB.io

* Bug fixes

## 11.2.1

*February 14, 2023*

* Introduces `persona` selection in Session Lifecycle Management without login/logout

* Extends Policy Engine API and Admin Portal with "delete policy" and "delete rule"

* Extends Policy Engine rule expression language

* Adds managed `id_at_customer` to the user profile at top level

* Self-Service Portal enables password manager to autofill password

* Self-Service Portal makes registration an optional button on login screen

* Publishes event on event bus at "add/update persona" and "update user"

* Enables TB.Connect to support automated provisioning triggered through events

* Enables TB.Connect to handle `persona` obligation

* Improves error reporting

* Bug fixes

## 11.2.0

*February 3, 2023*

* Introduces Policy Administration Point with XACML-based declarative language

* Introduces Session Lifecycle Management

* Introduces authentication driven by declarative policies

* Introduces authentication obligations as `acr` and `amr`

* Admin Portal Enables "get, add, change policy" and "get, add, change, find, reorder rule"

* Introduces Rule Library

* Extends Policy Engine API with "get, add, change policy" and "get, add, change rule"

* Extends Policy Engine API with "reorder rules" and "add existing rule"

* Extends Identity Manager API with "delete persona"

* Admin Portal Improves persona admin section and adds paging to user overview

* Self-Service Portal introduces storybook for UX customization

* Self-Service Portal extends search capability

* Self-Service Portal sets CDN URL via template variables on Hosted Login

* Self-Service Portal extends Web Components for Lazy Migration

* Self-Service Portal adds translation-key model to Web Components

* TB.Connect synchronizes start, continue and end sessions with Session Manager

* Enables TB.Connect to handle `acr` and `amr` obligation

* Improves error reporting for tenant manager

* Bug fixes

## 11.1.2

*January 12, 2022*

* Identity Manager becomes the master in user management and makes TB.Connect the slave

* Identity Manager publishes event on event bus on "add user"

* Bug fixes

## 11.1.1

*December 19, 2022*

* Extends Identity Manager API with "get persona by attribute"

* Bug fixes

## 11.1.0

*October 7, 2022*

* Introduces Persona Lifecycle Management

* Adds API and enables Admin Portal to "get, add, change, delete a persona definition"

* Adds API and enables Admin Portal to "get, add, change persona"

* Extends API and enables Admin Portal with "get user by attribute"

* Extends API and enables Admin Portal with "list and filter user profiles"

* Enables custom attributes to be added to a persona type

* Enables TB.Connect to use Persona attributes in Access Flows

* Bug fixes

## 11.0.0

*July 15, 2022*

* Introduces Identity Management on top of credentials management in TB.Connect

* Adds API to "get, add, change user profile"

* Adds API to "get, add, change, delete attribute definition"

* Adds Tenant Management API to "create tenant"

* Adds Configuration Management API to "configure tenant"

* Admin Portal and Self-Service Portal introduces the use of Web Components

* Admin Portal enables "get, add, change user profile" and "list and filter user profiles"

* Enables TB.Connect to use User Profile attributes in Access Flows

Preview environment  
**2026.5.1**

*July 20, 2026 in preview*

* Added "*Last authenticated* " information for each IdP in the "Provision" tab of a User profile page. **Enabled on demand**

* Users page**:** User profiles can now be opened in a new browser tab using the right-click context menu.

**2026.4.0**

*June 11, 2026 in preview*

* Removed `optimizeConsentTable` operation.

  *Contact* [++*TrustBuilder Support*++](https://support.customer.trustbuilder.com/)*for consent table optimization*

* Improved UI of the editor view of Authorization Rules.

**2026.3.0**

*April 23, 2026 in preview*

* The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` has been removed. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

* The [++Trustbuilder.io API documentation++](https://api.preview.trustbuilder.io/api/documentation) interface has been redesigned. The previous Swagger UI has been replaced with a more structured and user-friendly interface.

  ![image-20260417-081235.png](https://docs.trustbuilder.com/__attachments/a_1c2c1eab8404822b20a710383934f4de00c2d023b7ea1a4b429c2acfa69fc38b/image-20260417-081235.png?cb=949c7ee3d520ea6e84c3c6b1b2226f7b)

  ![info](https://docs.trustbuilder.com/__attachments/a_a1e7a018bd8ddf5b2ec89228ef449cc718fc4afeccaa8c0cddce706f846ab898/atlassian-info?cb=feab5cd71111204d6b52545f3027dd0c) *No changes have been made to the API itself, only the documentation interface has been updated.*
* Bug fix

**2026.2.1**

*March 19, 2026 in preview*

* Bug fix that prevented users with delegation rights from viewing user details within their scope.

The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` is deprecated and will be removed in a future release. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

**2026.1.0**

*January 22, 2026 in preview*

* Access flows: SP and IdP descriptions are now displayed in the access flow overview on the configuration page.

  ![Access flows improvements.png](https://docs.trustbuilder.com/__attachments/a_36367b9280e444cc244d654d5776f43f00e346ae7c9d2531f9823fba13c43f22/Access%20flows%20improvements.png?cb=00b81d26d4e9411fc27920406b85803d)
* Logs improvement

* Bug fixes

The `is_blocked` field in `GET/POST/PUT/PATCH /users/{user_id}` is deprecated and will be removed in a future release. Use `GET /users/{user_id}/blocks` to retrieve a user's blocked status.

**2025.9.2**

*December 1, 2025 in preview*

Security Fix

**2025.9.1**

*November 27, 2025 in preview*

* **IdPs configuration** :auto-provisioning can now be disabled.

  ![20251117-1013-51.5245380-20251117-101355.gif](https://docs.trustbuilder.com/__attachments/a_3dbeb0608b7d12b807e58d4340bb1e6bba967757003698815ee556893a2e78b7/20251117-1013-51.5245380-20251117-101355.gif?cb=42e16342d1df8636292049f175c202f8)
* **SAML IdPs** : added support of `<samlp:Scoping>` in AuthnRequests to ensure eHerkenning and eIDAS compliance. Admins can now declare *Scoping IdPs*.

  ![image-20251117-105905.png](https://docs.trustbuilder.com/__attachments/a_b280309d153b925fc65e2322d9cf3672e00b532c80afa3aaac7bf6155d9d353f/image-20251117-105905.png?cb=b13b83af84d202afa2305bac14b98b99)
* **OAuth2 JWT tokens**: an option for exposing the scope claim as a space-separated string has been added (for compliance with RFC 9068). The array of values (old behavior) remains the default.

  ![image-20251117-130757.png](https://docs.trustbuilder.com/__attachments/a_595020569da3331cd6ea22ddbb9100bcb8999705fdb8e0ab66291e9776d1f15e/image-20251117-130757.png?cb=2675713bfc333216a01dc15faf873b7f)
* **Logs** now include more information when a user is not found during login.

* **Bug fixes**:

  * Attribute rules using *ENUMERATION* values are now correctly saved and displayed in the admin portal *(Service Provider \> Attribute Rule)*.

  * Added a new `GET users/{user_id}/blocks` endpoint to fix an issue where the user's blocked status was not updated correctly in the admin portal.

    ⚠️ This new endpoint is the definitive way to retrieve the blocked status for a single user. The `is_blocked` old field in `GET/POST/PUT/PATCH users/{user_id}` is deprecated and will be removed in a future release.

  * The search behavior in user tab filter has been modified for text attributes:

    * `Equals` (default) was case-insensitive and is now case-sensitive.

    * `Contains` doesn't change and is still case-insensitive.

**2025.8.1**

*October 23, 2025 in preview*

* Bug fixes

**2025.8.0**

*October 16, 2025 in preview*

* Improved error handling to prevent system exceptions during authentication failures.

* Improved support of multi-valued JSON user attributes in OAuth ID token claims

* Bug fixes

**2025.7.2**

*September 4, 2025 in preview*

* User attribute names must now be unique

* Improvement of consent management: expired consents are no longer stored

**2025.6.0**

*July 22, 2025 in preview*

* Security: The HSTS Header `max-age` is now set to 1 year (=31 536 000 seconds)

* API: Updated endpoints to match REST standards, returning a 201 (CREATED) status code for a POST creation, instead of 200 (OK). This applies to /users and /persona-definitions.

* Improved handling of missing user consent

* Bug fixes

**2025.5.0**

*June 24, 2025 in preview*

* Menu updates in Admin Portal:

  * *Identity Management* has been renamed to *Directory*

  * *Identity Providers* has been moved to a new section called *Integrations*

    ![Nouveau menu.png](/__attachments/a_538fdd326e1301c8fad34a5aece6c338b7fbf14cc7728277dbe46ecb14fc1bd2/Nouveau%20menu.png?cb=4362d8f0100532bbbc1d7b0c3369d8ba)
* Improved policy-driven access flow when a derived attribute is used

* Bug fixes

**2025.4.0**

*May 27, 2025 in preview*

* Administrators can now block and unblock users.

  ![Block user.gif](https://docs.trustbuilder.com/__attachments/a_8f7d473bcefa62bd8da9d52e4627849830a4d1567b274c961906f14b19dc4ca9/Block%20user.gif?cb=b2225fa36e14d87dc7c8cc7b778ef1c2)
* HSTS header is now optional in Gateway

* FIDO2 authentication - *Feature enabled on demand*: support of French and Dutch languages in registration and login pages.

* Change the management of session cookie to avoid conflicts.

* Bug and security fixes

**2025.3.0**

*March 25 2025 in preview*

* **FIDO2 authentication - Feature enabled on demand:**

  Improved behavior at user deletion: all user security keys are now automatically deleted

* **Self-Service Portal**: Users can now rename their security keys.

  ![key renaming in release note.gif](https://docs.trustbuilder.com/__attachments/a_1fdb88143209fcb0457d487238a0b560506ffcc8d5896f065eb8a0b4b58da5cb/key%20renaming%20in%20release%20note.gif?cb=ee929509a054cd183272a88f631c10c7)
* Performance improvement

* Bug fixes

**2025.2.0**

*February 18, 2025 in preview*

* \[Beta\] FIDO2 authentication - **Feature enabled on demand**

  * FIDO2 Registration policy is now visible and can be edited

  * The username is now captured and stored during registration to improve the authentication experience.

* Self-Service portal

  * Users can view the status of their security keys.

  * Multi-language support has been added.

* Improve logging on Authentication and Authorization events

* Remove Service Catalog support on IDP and SP creation pages

* Bug fixes

  * Add missing confirmation messages when clicking Save.

  * Other bug fixes

**2025.1.1**

*January 28, 2025 in preview*

* Database optimizations

**2025.1.0**

*January 16, 2025 in preview*

* Bug fixes

  * Buttons sometimes not be visible on pop-ups

  * Persona invitation link not followed after login

  * E-mail verification field might revert to FALSE.

  * Other bug fixes.

* \[Beta\] FIDO2 authentication - **Feature enabled on demand**

  * Improved error messages when registering a key via the Self-Service Portal

**2024.9.1**

*December 18, 2024 in preview*

* Fixed an issue with user and persona events handling.

**2024.9.0 (11.2.26)**

*December 05, 2024 in preview*

* \[Beta\] Support of FIDO2 security key as a new authentication method - **Feature enabled on demand**

  [*More information*](https://docs.trustbuilder.com/tb-io/trustbuilder-fido2.md)

* Sign-up option is a configurable feature on login page

  [*More information*](https://docs.trustbuilder.com/tb-io/how-to-enable-disable-user-self-registration.md)

* Bug fixes

**2024.8.0** ***(11.2.25)***

*November 07, 2024 in preview*

* Request ID can be provided to the user to report a problem with authorization

* User self-registration can be disabled in the administration

  [*More information*](https://docs.trustbuilder.com/tb-io/how-to-enable-disable-user-self-registration.md)

* User caching can be disabled in the administration

* Performance improvements

* Bug fixes

**11.2.24**

*September 26, 2024 in preview*

* Self-Service portal \> shows active persona information

* Performance improvements

* Bug fixes

**11.2.23**

*July 17, 2024 in preview*

* Admin Portal: added Delegated Administration feature

  [*More information*](https://docs.trustbuilder.com/tb-io/delegated-administration.md)

* Self-Service Portal:

  * Added user personas management capability

  * Users can now delegate their personas to other users

  * Users can now see and manage requests

    [*More information*](/tb-io/self-service-portal.md)

* Performance improvements

* Bug fixes

**11.2.22**

*May 23, 2024 in preview*

* Admin Portal \> Added entitlements parameter to personas

* Refactored endpoint for tenant queries

* Bug fixes

**11.2.21**

*April 25, 2024 in preview*

* Improved UX on viewing user profile

* Accessibility improvements

* Performance improvements

* Better explanation of some errors to users

* Bug fixes

**11.2.20**

*March 26, 2024 in preview*

* Identity Manager \> enforces attribute definitions marked as unique to ensure the uniqueness of values in user profiles

* Identity Manager \> improves the behavior when adding a unique property to an existing attribute definition

* Policy Engine \> custom attributes are now supported in policy rules on user level

* Admin Portal \> allows to set a persona as preferred from the list of personas

* Logs improvements

* Bug fixes

**11.2.19**

*February 9, 2024 in preview*

* Policy Engine \> persona attributes are now supported in policy rules

* Admin Portal \> now allows to filter users by custom attributes in users overview

* Admin Portal \> improved the UI of rules configuration interface

* Access Management \> improved the authentication process to remain robust and error-free (ACR handling)

* Identity Manager \> now allows to define a display name to persona definition

* Session Manager \> improved persona selection to use the right attributes

* Bug fixes

**11.2.18**

*January 17, 2024 in preview*

* Bug fix

**11.2.17**

*December 28, 2023 in preview*

* Logs improvements

* Bug fixes

**11.2.16**

*December 14, 2023 in preview*

* Admin Portal \> now allows to filter users by persona in users overview

* Bug fixes

**11.2.15**

*November 28, 2023 in preview*

* Admin Portal \> added pagination to user profiles overview

* Identity Manager \> improved the behavior of user profiles creation with required custom attributes

* Bug fixes

**11.2.14**

*November 9, 2023 in preview*

* Identity Manager \> now allows to add custom top-level attributes to user profiles

* Admin portal \> improved JSON mode switching behavior

* Admin Portal and Self-Service Portal \> improved the returned error messages in persona editor

* APIs \> changed the base URL of TrustBuilder.IO API (preview and production environments) - [More information](https://docs.trustbuilder.com/tb-io/trustbuilder-io-api.md)

* Bug fixes

**11.2.13**

*October, 2023 in preview*

* Admin Portal \> improved the behavior after deleting a persona definition

* Admin Portal \> IP ranges can now be added to Admin Portal access restrictions

* Self-Service Portal \> now allows to edit email and username

* Bug fixes

**11.2.12**

*October, 2023 in preview*

* Policy editor \> now supports the entire range of attributes

* Admin Portal and Self-Service Portal \> now allows to search for an attribute when adding a filter

* Fixes a refresh token issue relative to PKCE Authorization grant

* Bug fixes

**11.2.11**

*October, 2023 in preview*

* Admin Portal \> Improve user administration screens

* Identity Manager \> Event on persona deletion

* Policy Engine now supports the use of persona attributes

* Bug fixes

**11.2.10**

*August, 2023 in preview*

* Identity Manager \> API now allows to add custom attributes at top-level

* Bug fixes

**11.2.9**

*July, 2023 in preview*

* Admin Portal \> Native integration of TrustBuilder MFA

* Identity Manager \> Native bi-directional synchronization with TrustBuilder MFA

* Identity Manager \> Users \> auto-provisioning of roles to TrustBuilder MFA based on Administrator Persona

* Admin Portal \> Policy \> now allows to create a rule while editing a policy

* Admin Portal \> Rule \> now allows deletion of an expressions

* Admin Portal \> filtering is now case-insensitive

* Admin Portal \> has restructured menu

* Bug fixes

**11.2.8**

*July, 2023 in preview*

* Admin Portal \> Access Flows now allows policies to be linked

* Admin Portal \> Identity Providers now includes AppleID configuration

* Policy Engine now protects against accidental deletion of policies that are in use

* Admin Portal \> Policies now allows rules to be created while adding it to a policy

* Admin Portal \> Policies now allows policies and rules to contain a `description`

* Admin Portal \> Rules now supports `has_value` and `is_empty` in visual mode

* Hosted Login `tb-login` now allows forgot-password to be linked to external systems, e.g. other IAM

**11.2.7**

*May, 2023 in preview*

* Identity Manager introduces `PATCH` for deletion of attributes

* Admin Portal \> Policies now allows the rules to be combined visually

* Admin Portal \> Policies now provides more guidance in JSON editor

* Admin Portal now shows the TB.io version number of the tenant

**11.2.6**

*May, 2023 in preview*

* Admin Portal \> Rules allows `obligations` to be added in visual mode

* Admin Portal \> Rules allows `equals` and `not_equals` expression in visual mode

* Admin Portal \> Users allows the filtering to be reset

* Policy Engine now uses the term `DENY_OVERRIDES` instead of `ORDERED_DENY_OVERRIDES`

* Hosted Login now supports Swedish, French, and German

* TB.Connect bug fixes in SAML and OIDC handlers

**11.2.5**

*April, 2023 in preview*

* Policy Engine introduces the `elem_match` operator in rule expressions and renames `deny_overrides`

* Session Manager enforces `status`, `valid_from` and `valid_till` during persona selection

* Identity Manager enables attribute deletion and persona attribute setting through the `PATCH` endpoint

* Hosted Login adds support for Swedish, French, German

* Admin Portal \> Users allows sorting by any column

* Admin Portal and Self-Service Portal show the `scope` on the persona tile

* Bug fixes

* Security fix in Self-Service Portal

**11.2.4**

*April, 2023 in preview*

* Hosted Login enables language selection

* Hosted Login defaults to `user_name` if `given_name` and `family_name` or not set

* Admin Portal enables user list to be sorted

* Admin Portal enables `scope` of a persona to be edited

* Admin Portal resolves concurrent user editing conflicts between multiple users admins

* Bug fixes

**11.2.3**

*March, 2023 in preview*

* Extends Identity Management API with `PATCH` endpoints on user and persona

* Adds filtering by custom attributes to user overview

* Shows `updated_at` and `created_at` in the user overview

* Prevents that Persona definitions contain duplicate attributes or undefined attributes

* Extends the Policy Engine language with `not`, `not_equals`, `not_in`, `older_than`, `not_older_than`

* Relaxes uniqueness constraint on attribute displayname to uniqueness per category

* TB.Connect:

  * Extends the Application Catalogue with any OAuth2 SP

  * Receives session information with HTTP 200 response from Session Manager

  * Fixed issue with missing claims after token exchange

* Bug fixes

**11.2.2**

*March, 2023 in preview*

* Extends the Policy Engine rule expression language with `$session.persona`

* Session Manager provides an endpoint to store persona selection

* Allows description and metadata to be added to policies and rules

* Allows policy name to be changed in the visual editor

* Allows customization of the persona selection screen

* Adds filtering by native attributes to user overview

* Enhances the login screen to make self-registration configurable

* Renames the attribute `member_of` into `entitlements`

* Publishes event on event bus at "add/update tenant"

* Auto-creates a TB.Connect instance when creating a new tenant in TB.io

* Bug fixes

**11.2.1**

*February, 2023 in preview*

* Introduces `persona` selection in Session Lifecycle Management without login/logout

* Extends Policy Engine API and Admin Portal with "delete policy" and "delete rule"

* Extends Policy Engine rule expression language

* Adds managed `id_at_customer` to the user profile at top level

* Self-Service Portal enables password manager to autofill password

* Self-Service Portal makes registration an optional button on login screen

* Publishes event on event bus at "add/update persona" and "update user"

* Enables TB.Connect to support automated provisioning triggered through events

* Enables TB.Connect to handle `persona` obligation

* Improves error reporting

* Bug fixes

**11.2.0**

*February, 2023 in preview*

* Introduces Policy Administration Point with XACML-based declarative language

* Introduces Session Lifecycle Management

* Introduces authentication driven by declarative policies

* Introduces authentication obligations as `acr` and `amr`

* Admin Portal Enables "get, add, change policy" and "get, add, change, find, reorder rule"

* Introduces Rule Library

* Extends Policy Engine API with "get, add, change policy" and "get, add, change rule"

* Extends Policy Engine API with "reorder rules" and "add existing rule"

* Extends Identity Manager API with "delete persona"

* Admin Portal Improves persona admin section and adds paging to user overview

* Self-Service Portal introduces storybook for UX customization

* Self-Service Portal extends search capability

* Self-Service Portal sets CDN URL via template variables on Hosted Login

* Self-Service Portal extends Web Components for Lazy Migration

* Self-Service Portal adds translation-key model to Web Components

* TB.Connect synchronizes start, continue and end sessions with Session Manager

* Enables TB.Connect to handle `acr` and `amr` obligation

* Improves error reporting for tenant manager

* Bug fixes

**11.1.2**

*January, 2022 in preview*

* Identity Manager becomes the master in user management and makes TB.Connect the slave

* Identity Manager publishes event on event bus on "add user"

* Bug fixes

**11.1.1**

*December, 2022 in preview*

* Extends Identity Manager API with "get persona by attribute"

* Bug fixes

**11.1.0**

* Introduces Persona Lifecycle Management

* Adds API and enables Admin Portal to "get, add, change, delete a persona definition"

* Adds API and enables Admin Portal to "get, add, change persona"

* Extends API and enables Admin Portal with "get user by attribute"

* Extends API and enables Admin Portal with "list and filter user profiles"

* Enables custom attributes to be added to a persona type

* Enables TB.Connect to use Persona attributes in Access Flows

* Bug fixes

**11.0.0**

* Introduces Identity Management on top of credentials management in TB.Connect

* Adds API to "get, add, change user profile"

* Adds API to "get, add, change, delete attribute definition"

* Adds Tenant Management API to "create tenant"

* Adds Configuration Management API to "configure tenant"

* Admin Portal and Self-Service Portal introduces the use of Web Components

* Admin Portal enables "get, add, change user profile" and "list and filter user profiles"

* Enables TB.Connect to use User Profile attributes in Access Flows

---
language: "en"
---
# AMQConsumerService

Classname: `be.securit.trustbuilder.service.AMQConsumerService`

This service (from here on referred to as consumer) is used for receiving and handling messages.

## Properties

* **Username**: Username for accessing the queuingserver.

* **Password**: Password for accessing the queuingserver.

* **Host**: Host of the queuingserver this consumer will receive messages from.

* **Port**: Port of the queuingserver this consumer will receive messages from.

* **Queue**: The queue this consumer is accepting messages from.

* **Exchange**: The exchange the aforementioned queue is getting messages from.

* **Topics**: The topics the queue associated with this consumer will accept from the exchange. (special case: If the same queue is already bound to another consumer or other consumers, the topics this queue will listen to will be the union of the topics for each consumer)

* **Workflow**: The workflow that will handle the messages.

---
language: "en"
---
# AMQProducerService

Classname: `be.securit.trustbuilder.service.AMQProducerService`

This service (from here on referred to as producer) is used for sending a message with a certain topic to an exchange, which will deliver it to the consumer(s) (configured by AMQProducerServices) listening to that topic. The delivering and handling of the message is done asynchronously.

## Properties

* **Username**: Username for accessing the queuingserver.

* **Password**: Password for accessing the queuingserver.

* **Host**: Host of the queuingserver this producer will send messages to.

* **Port**: Port of the queuingserver this producer will send messages to.

* **Exchange**: The exchange this producer will send messages to.

* **Topics**: The topics this producer is allowed to send messages with.

### Functions

* **send(message, topic)**: Send a message; message can be any JavaScript object, topic must be a String. Returns an object containing a status key and a message key. Below you can find the different possible status values and corresponding information:

  * 0: OK.

  * 1: This producer is not allowed to send messages with this topic.

  * 2: Internal error.

---
language: "en"
---
# API Service Provider

## Introduction

The API Type of Service Provider is a bit of an exception compared to the other types.

It's primary use is for Machine-to-Machine communication, so it does not have a user (human) to complete the signing in.

Instead, the User Authentication has already taken place before the API is called, and TrustBuilder will validate the Bearer Token, and check if the caller has authenticated and (possibly) proper authorization.

Therefore, there is no Identity Provider to link. The Authentication Scheme is also not applied.

## Fields

|         Field         |                                                                        Description                                                                        |
|-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
| Display Name          | User defined name of the Service Provider                                                                                                                 |
| URL                   | Not used                                                                                                                                                  |
| Description           | User defined description of the Service Provider                                                                                                          |
| Authentication Scheme | Irrelevant for this type of Service Provider                                                                                                              |
| Type                  | API\*                                                                                                                                                     |
| Location              | Path that indicates where the Service Provider is located.                                                                                                |
| Hostname              | Hostname of the server (if another server than the Admin Portal Server is used). Subdomain and domainname. If not provided, this server hostname is used. |

---
language: "en"
---
# APIs

* [TrustBuilder.IO API](https://docs.trustbuilder.com/tb-io/trustbuilder-io-api.md)
* [TrustBuilder IDHub API](https://docs.trustbuilder.com/tb-io/trustbuilder-idhub-api.md)
* [TrustBuilder MFA API](https://docs.trustbuilder.com/tb-io/trustbuilder-mfa-api.md)

---
language: "en"
---
# Event logs

All of the operational applications will have the capability of generating functional events. These events are all added to an event queue, and are then handled by a listener.

For an initial concept, the listener has a very straightforward duty: it will dispatch the events to a selected workflow. A different workflow can be selected for each event type.

The configuration of the Auditing Events can be done from the admin portal \> **Insights** \> **Event handling tab**.

## Event Overview

|      Event Type       |                                                                        Description                                                                         |
|-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Authentication Events | Authentication events are triggered each time a user successfully or unsuccessfully authenticates, using any Identity Provider configured in TrustBuilder. |
| Authorization Events  | Authorization events are triggered each time a user successfully or unsuccessfully tries to access any Service Provider configured in TrustBuilder.        |
| Log-out events        | The Log-out events are generated when a users logs-out.                                                                                                    |
| Session Events        | Creates an event every time a session is updated.                                                                                                          |
| Administration Events | Creates an event for administration actions.                                                                                                               |

### Format

The events are passed in a JSON-like format to the selected workflow. Date and time are represented in the epoch format. The data for each of the events is described in the Event Type pages, which are linked in the table above.

## Auditing Configuration

From the Admin Portal, go to Auditing \> Event Handling. This page allows you to configure which auditing events are handled by which workflow.

Events are generated and put on an Event Queue. There is a listener that will process all these events, and dispatch them to the appropriate workflow.  

|    **Field**     |                                                                                                                                                                                                                                                                                                                                                                                                                              **Description**                                                                                                                                                                                                                                                                                                                                                                                                                               |
|------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Event Type       | Describes to which event types the application will listen.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Workflow Handler | Select which workflow will handles events of this type.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Enabled          | Can be toggled to enable or disable listening to a specific event type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Batch            | Can be toggled to group multiple events of the same type into a batch. More information below. For environments with a lot of traffic, it could be desirable not to kick off a new workflow with each event. For these circumstances, we've added the possibility to group the events into batches, so they can be handled more efficiently, while remaining available in near real-time. Currently the settings are set as follows: * **Maximum Batch Size** : 100 This means that the maximum amount of events (of this event type) that will be grouped into one batch will be 100. As soon as the hundredth event is added, the whole batch will be sent to the workflow. * **Idle Time-out** : 1000 milliseconds This means that after 1000 milliseconds (1 second) of not receiving a new event of this type, all the grouped events will be pushed to the workflow. |

## Events types

### Authentication events

|--------------------------|----------------|
| **Trigger**              | **Event Code** |
| Authentication Succeeded | ORCH-1010      |
| Authentication Failed    | ORCH-1020      |
| **Data**                                 ||
| * timestamp (in milliseconds) * eventType = "Authentication event" * eventCode * statusMessage (in case of failure) * source (IP Address) * subject * statusCode * SessionID * authenticationMethod * idp * attributes { Key / Value pairs } (Only those received from the IDP) ||

### Authorization events

There are two types of Authorization Events that correspond to the policies that can be set on the Service Provider pages.

* Authentication Rules (coarse grained)

* Authorization Rules (fine grained)

|       **Authentication Rules**        ||
|-----------------------|----------------|
| **Trigger**           | **Event Code** |
| Authorization Allowed | ORCH-2010      |
| Authorization Denied  | ORCH-2020      |
| Step-up               | ORCH-2030      |
| Reauthenticate        | ORCH-2040      |
| **Data**                              ||
| * timestamp (in milliseconds) * eventType = "Coarse grained authorization event" * eventCode * statusCode * source (IP Address) * subject * SessionID * authenticatedAuthenticationMethod (method with which you are authenticated for that SP) * idpName (possible in case of reauthenticate) * stepUpAuthenticationMethod (in case of step-up) * stepUpAuthenticationMethodComparion (in case of step-up) * spName * attributes { Key / Value pairs } (to be sent to SP) ||

|     **Application Rules**      ||
|----------------|----------------|
| **Trigger**    | **Event Code** |
| Allow          | ORCH-2110      |
| Deny           | ORCH-2120      |
| Step-up        | ORCH-2130      |
| Reauthenticate | ORCH-2140      |
| **Data**                       ||
| * timestamp (in milliseconds) * eventType = "Fine grained authorization event" * eventCode * statusCode * source (IP Address) * subject * SessionID * authenticationMethod (in case of step-up) * authenticationMethodComparison (in case of step-up) * location * httpHeaders * requestURI * requestHostname * httpMethod * requestType(WEB, PUBLIC_WEB or API) ||

### Log-out events

|------------------------------------------|----------------|
| **Trigger**                              | **Event Code** |
| INITIAL_LOGOUT_REQUEST                   | ORCH-3010      |
| INTERMEDIATE_LOGOUT_REQUEST              | ORCH-3110      |
| INTERMEDIATE_LOGOUT_SUCCESSFUL           | ORCH-3210      |
| INTERMEDIATE_LOGOUT_PARTIALLY_SUCCESSFUL | ORCH-3220      |
| INTERMEDIATE_LOGOUT_FAILED               | ORCH-3230      |
| COMPLETE_LOGOUT_SUCCESSFUL               | ORCH-3310      |
| COMPLETE_LOGOUT_PARTIALLY_SUCCESSFUL     | ORCH-3320      |
| **Data**                                                 ||
| * timestamp (in milliseconds) * eventType = "Logout event" * eventCode * statusCode * source (IP Address) * subject (if present) * SessionID * partner * requestId (identifier to match request and response) ||

### Session events

|----------------|----------------|
| **Trigger**    | **Event Code** |
| SESSION_UPDATE | ORCH-4000      |
| **Data**                       ||
| * timestamp (in milliseconds) * session * eventType = "Session update" * eventCode ||

### Administration events

#### Admin access

|           **Administration Access**            ||
|--------------------------------|----------------|
| **Trigger**                    | **Event Code** |
| Successful Administrator login | ADMN-1010      |
| Administrator logged out       | ADMN-1020      |
| Failed Administration login    | ADMN-1030      |
| **Json**                                       ||
| * Event Type = "AdminAccess" * Event Code * Timestamp * Username * User IP Address ||

#### User changes

|           **Configuration Change**           ||
|------------------------------|----------------|
| **Trigger**                  | **Event Code** |
| Configuration Object Created | ADMN-3010      |
| Configuration Object Updated | ADMN-3020      |
| Configuration Object Deleted | ADMN-3030      |
| **Json**                                     ||
| * eventType = "Administration" * eventCode * timestamp * subType (USER_DATA_CREATION / USER_DATA_MODIFICATION / USER_DATA_REMOVAL) * objectType (PRINCIPAL / ...) * adminUserId * In case of creation or removal * data * In case of update, for each attribute: * oldData * newData * dataDiff (<https://tools.ietf.org/html/rfc6902> ) ||

|     **User CRUD event**      ||
|--------------|----------------|
| **Trigger**  | **Event Code** |
| User Created | USER-1010      |
| User Edited  | USER-1020      |
| User Removed | USER-1030      |
| **Json**                     ||
| * Timestamp * Event type = "UserEvent" * Event Code * UserID ||

#### Config Change Events

|           **Configuration Change**           ||
|------------------------------|----------------|
| **Trigger**                  | **Event Code** |
| Configuration Object Created | ADMN-4010      |
| Configuration Object Updated | ADMN-4020      |
| Configuration Object Deleted | ADMN-4030      |
| **Json**                                     ||
| * eventType = "Administration" * eventCode * timestamp * subType (CONFIGURATION_CREATION / CONFIGURATION_MODIFICATION / CONFIGURATION_REMOVAL) * objectType (IDP / SP / ...) * adminUserId * In case of creation or removal * data * In case of update, for each attribute: * oldData * newData * dataDiff (<https://tools.ietf.org/html/rfc6902> ) ||

#### Server Events

|       **Server Restart**       ||
|----------------|----------------|
| **Trigger**    | **Event Code** |
| Server stopped | ADMN-2010      |
| Server started | ADMN-2020      |
| **Json**                       ||
| * Event Type = "ServerRestart" * Event Code * Timestamp * Server IP ||

---
language: "en"
---
# AZN Concepts

The *authorization engine* allows administrators to specify which resources may be accessed by a given user. This access is conditional. The condition is defined by means of one or more rules that are associated with the resources. If no rule exists for a particular resource, then access is automatically denied.

The authorization engine supports *attribute-based authorization*. This means that the engine takes a resource as input, as well as a list of attributes with relevant information about the user, and applies the rules to the resource and the attributes. The user attributes may not only contain attributes identifying the user, but they may also include additional data, such as contextual information. The attributes are represented as a JSON-like object.

The authorization engine is available as a service within TrustBuilder. When the rules have been defined, they may be exported to the TrustBuilder server hosting the authorization service.

The authorization administration tool supports the administrator in this process. First, the user interface allows administrators to declare a list of relevant resources. Then rules may be linked to these resources. Finally, the rules may be exported to the appropriate TrustBuilder servers.

## Resources

Each resource has the following attributes:

* a non-empty domain, which provides a scope for one or more resources;

* a non-empty name, which must be unique within the domain;

* a flag specifying if the domain-resource combination will be matched literally.

When the auhorization service starts up, it registers the resources with rules (technically a *rule suite*). If multiple resources with the same domain-name-flag combination exist, only the last registered resource will be retained.

### Resource matching

When the authorization engine attempts to validate access to an input resource, it first tries to locate the rules linked to an 'exact match' resource equal to the input resource. If no such matching resource is found, the engine searches for rules linked to a 'non-exact-match' resource with longest matching prefix.

**Example**

Registered resources:

1. A - exact

2. AB - not exact.

Resources to validate:

* A matches resource 1. Access is decided by the rules.

* AB matches resource 2. Access is decided by the rules.

* ABC matches resource 2. Access is decided by the rules.

* AD matches no resource. Access is denied.

### Rule suites

Rules linked to a resource are grouped into a *rule suite*. Rule suites support more sophisticated use cases, but in the context of the current authorization tool, we equate a rule suite with an ordered list of rules. Resources are thus actually linked to rule suites, not to individual rules.

Multiple resources may be linked to the same rule suite, but a resource may only be linked to one rule suite at a time. This implies that rules within a rule suite can be applied to multiple resources, allowing us to share business logic across resources.

The rule suite may also define optional *policy information points* (PIP's). PIP's allow the rules to use additional data retrieved from external services, based on the input data.

### Rules

Each rule has the following structure:

* an optional condition (a null condition is considered to be true);

* an assertion that must be true if the condition holds;

* an optional list of hints, which return extra information (e.g. the client should step up to another authentication level).

#### Semantics of rules

The first two elements of a rule translate into the following logical statement.

    if the condition is true then the assertion must be true 

In other words, the rule only fails if the condition is true while the assertion is false.

**Note** A rule may also fail in case of errors, e.g. when trying to perform operations on data of the wrong type.

#### Semantics of rule suites

From the semantics of rules, we derive the semantics of rule suites.

A rule suite succeeds if:

1. all the rules succeed;

2. at least one rule has a true condition.

The second requirement states that access to a resource must always be granted *explicitly*: it is not enough that no rule fails. As a corollary, rule suites with an empty rule list always fail.

When the rule suite succeeds, a *score* of 1 is returned. Otherwise the score is 0.

#### Lazy evaluation

The execution of a rule or of a rule suite stops as soon as the score can be determined with certainty. For instance, when a rule fails, we know that the rule suite will fail as well.

#### Conditions and assertions

A rule condition and assertion have the same structure. They both consist of a sequence of tests. These tests are combined in four ways: *AND* , *OR* , *NOT AND* , *NOT OR*.

Each test consists of a function with zero or more parameters. Each parameter is a *constant* (like a string or a number), a reference to a *variable*, or a JSON-like document containing a reference to a variable as one of its values.

#### Functions

The following functions are currently supported.

**One-parameter functions**  

|  Function  |                     Description                     |
|------------|-----------------------------------------------------|
| isBoolean  | Tests if the value is a Boolean                     |
| isDocument | Tests if the value a document (JSON-like object)    |
| isEmpty    | Tests if the value is an empty list or string       |
| isError    | Tests if the value is an error (document)           |
| isNil      | Tests if the value is nil                           |
| isNotEmpty | Tests if the value is a not an empty list or string |
| isNotNil   | Tests if the value is not nil                       |
| isNumber   | Tests if the value is a number                      |
| isSequence | Tests if the value is a list (JSON-like array)      |
| isString   | Tests if the value is a string                      |

**Two-parameter functions**  

|       Function       |                                              Description                                              |
|----------------------|-------------------------------------------------------------------------------------------------------|
| =                    | Tests if the first number equals the second number                                                    |
| \<                   | Tests if the first number is less than the second number                                              |
|                      | Tests if the first number is less than or equal to the second number                                  |
|                      | Tests if the first number is greater than or equal to the second number                               |
|                      | Tests if the first number is greater than the second number                                           |
| contains:            | Tests if the left (interval specified by a list of two numbers) contains the right value              |
| containsAll:         | Tests if the left (interval specified by a list of two numbers) contains the right interval           |
| ContainsAny:         | Tests if the left (interval specified by a list of two numbers) overlaps the right interval           |
| ContainsNone:        | Tests if the left (interval specified by a list of two numbers) does not intersect the right interval |
| ContainsNot:         | Tests if the left (interval specified by a list of two numbers) does not contain the right value      |
| ContainsNotString:   | Tests if the left (interval specified by a list of two strings) does not contain the right value      |
| containsString:      | Tests if the first string contains the second string                                                  |
| endsWith:            | Tests if the first string ends with the second string                                                 |
| endsNotWith:         | Tests if the first string does not end with the second string                                         |
| equals:              | Tests if the first string equals the second string                                                    |
| equalsIgnoreCase:    | Tests if the first string equals the second string, ignoring case                                     |
| equalsNot:           | Tests if the first string does not equal the second string                                            |
| equalsNotIgnoreCase: | Tests if the first string does not equal the second string, ignoring case                             |
| includes:            | Tests if the left (list) includes the right value                                                     |
| includesAll:         | Tests if the left (list) includes all the right values (list)                                         |
| includesAny:         | Tests if the left (list) includes any of the right values (list)                                      |
| includesNone:        | Tests if the left (list) includes none of the right values (list)                                     |
| includesNot:         | Tests if the left (list) does not include the right value                                             |
| matches:             | Tests if the left (string) matches the right (regular expression)                                     |
| matchesIgnoreCase:   | Tests if the left (string) matches the right (regular expression), ignoring case                      |
| startsWith:          | Tests if the first string starts with the second string                                               |
| startsNotWith:       | Tests if the first string does not start with the second string                                       |

**Three-parameter functions**  

|   Function    |                                                           Description                                                           |
|---------------|---------------------------------------------------------------------------------------------------------------------------------|
| isNear:range: | Tests if the first value (a geo-point of the form {'lat': xyz, 'lon' : xyz}) is within \*range\* meters of the second geo-point |

#### Rule hints

In addition to the score, a rule may also return a list of hints. By default, the hints are only generated when the rule fails, unless a flag instructs the rule to generate the hint regardless of the rule score.

### Variables

### Pre-defined variables

Each rule has access to two pre-defined variables.  

| Variable |                                                      Description                                                       |
|----------|------------------------------------------------------------------------------------------------------------------------|
| resource | This variable contains the qualified resource (domain/resource name) that the client wishes to access.                 |
| in       | This value contains a JSON-like document containing attributes that may provide (contextual) information about a user. |

#### User-defined variables

In addition to the pre-defined variables, user-defined variables may be added in two ways:

* to capture the result of a *Policy Information Point* (aka PIP) request (the variable name is the name of the PIP);

* to *memoize* the score of a rule (variable defined by the optional *result* attribute of the rule).

#### Accessing variables

Rules can access a variable by using the following syntax:

    $A.x.y.z 

where A refers to a variable, and the optional path *x.y.z* describes a path in a document if the variable holds a document.

**Example 1**

Suppose to test that the *resource* variable contains the a path starting with *prod/users/*, then we can use the following function.

    $resource startsWith: prod/users/

**Example 2**

Suppose that the input variable *in* contains the following document.

    {
        "user-id" : "John Doe",
        "department" : "HR"
    }

Then we can test if the user works in the HR department with the following function.

    $in.department equals: HR

### PIPs

Policy information points allow the rules to retrieve additional information related to the input data. PIP's have the following attributes:

* a non-empty (variable) name;

* a TrustBuilder workflow or component id;

* a JSON-like document providing the input to the workflow.

The name acts like a variable and may not overlap with other pre-defined or user-defined variables. The variable will hold the result of the workflow call. In this workflow, external services may be accessed to compute the proper response, which is also a JSON-like document.

The value of the PIP variable is computed at most once within the execution of a rule suite, according to the following rules: \* if the variable is not needed to calculate the score, the external call will not be performed, i.e. computation is strictly on demand; \* once the value has been computed, it is cached for the duration of the rule suite execution.

---
language: "en"
---
# AZN Configuring the authorization service

## AZN Configuring the authorization service

The authorization engine functions as a service within TrustBuilder. This means that the engine service must first be configured within a TrustBuilder configuration file, as in the following example.

    <stb:Service stb:id="AZN" stb:type="be.securit.trustbuilder.azn.engine.service.AuthorizationService" stb:singleton="true" stb:synchronised="false">
        <stb:property stb:name="index">../rulesuites</stb:property>
    </stb:Service>

The *index* property can be used in two ways:

* as a reference to a text file listing the rule suites to be loaded (extensional definition);

* as a reference to a directory containing the rule suites to be loaded (intentional definition).

In the first scenario, the file should contain simply a list of file names, one per line. In the second case, the directory should only contain XML files describing rule suites. The administration tool uses the second variant.

---
language: "en"
---
# AZN Policies in TrustBuilder Administrator

The TrustBuilder administration tool allows the user to edit resources and rule suites by selecting the *Policies* tab.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/368/medium/d90a9b6e-80e7-4465-b9ce-6743859f7c93.png?1521081193](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/368/medium/d90a9b6e-80e7-4465-b9ce-6743859f7c93.png?1521081193)

## Prerequisites

The login user must have the *TBAGPolicies* role.

### Editing policies

Clicking the policies tab allows the user to enable / disable the authorization engine, and to define resources and rule suites.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/367/medium/19b6908a-f8ad-4627-8029-12391d8a90c0.png?1521081192](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/367/medium/19b6908a-f8ad-4627-8029-12391d8a90c0.png?1521081192)

### Enabling / disabling the authorization engine

The top-right check box enables / disables the authorization engine. This action updates the authorization service section in the TrustBuilder configuration file.

### Managing resources

The *Resources* tab of the policies page allows the user to manage the list of resources. Resources may be created, edited and removed. Only resources linked to a rule suite will be taken into account by the authorization engine.

When creating a resource, a properties pane appears on the right. Clicking *Save* creates the new resource. Clicking the *Edit* button of a resource opens the properties pane again.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/363/medium/3bf7f421-4503-44a2-89aa-2cd19e37e0d8.png?1521081188](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/363/medium/3bf7f421-4503-44a2-89aa-2cd19e37e0d8.png?1521081188)

### Adding rule suites

The *Rule Suites* tab allows administrators to add, edit and remove rule suites.

When creating a rule suite, a properties pane appears on the right. Clicking *Save* creates the new rule suite. Clicking the *Edit* button of the new rule suite opens the properties pane again.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/371/medium/9ce583ad-501c-4bae-92b2-e4b2b4a792cc.png?1521081195](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/371/medium/9ce583ad-501c-4bae-92b2-e4b2b4a792cc.png?1521081195)

The new rule suite can now be linked to the appropriate resource(s) on the resources tab.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/361/medium/c3d46714-7592-49e2-9e3a-7bc731e49bd4.png?1521081187](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/361/medium/c3d46714-7592-49e2-9e3a-7bc731e49bd4.png?1521081187)

Clicking the rule suite's *Rule* button opens a page where the user can add rules and Policy Information Points.

#### Adding Policy Information Points to a rule suite

The *Policy Information Point* (aka *PIP*) tab allows the user to retrieve external information based on the input of the rule suite and store this information in a variable.

When creating a PIP (or editing an existing PIP), a properties pane appears on the right. This pane allows the user to name the variable and set the input data for the PIP request. The input data are entered as a list of key-value pairs and converted into a simple JSON-like document.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/370/medium/ae43f296-e5bf-4c41-89e7-523d9d558af5.png?1521081194](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/370/medium/ae43f296-e5bf-4c41-89e7-523d9d558af5.png?1521081194)

Once the PIP is defined, the user can specify the TrustBuilder workflow that must execute the request.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/365/medium/e3941114-c5b2-487f-a4e6-f885805ebf6c.png?1521081191](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/365/medium/e3941114-c5b2-487f-a4e6-f885805ebf6c.png?1521081191)

The *Payload* column on this page shows the generated JSON document.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/372/medium/e2dd4283-69bf-4e56-8c3b-d986dc120980.png?1521081196](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/372/medium/e2dd4283-69bf-4e56-8c3b-d986dc120980.png?1521081196)

#### Adding rules to a rule suite

The *Rules* tab allows the user to manage the rules in the selected rule suite.

When creating a rule (or editing an existing rule), a properties pane appears on the right. This pane allows the user to name the rule, and, optionally, to specify a name for the variable memoizing the result of the rule execution.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/373/medium/a68356ab-117c-4c02-b91c-23c05093177e.png?1521081197](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/373/medium/a68356ab-117c-4c02-b91c-23c05093177e.png?1521081197)

The *Define* button allows the user to specify the rule conditions, assertions and hints.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/369/medium/87e4aaf8-fcad-41da-a843-d6f73d2835de.png?1521081194](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/369/medium/87e4aaf8-fcad-41da-a843-d6f73d2835de.png?1521081194)

**Note**

As in other screens of the administration tool, the tabular view of the rule list uses a filter to constrain (per column) the elements to be displayed (the input fields below the table header). If this filter is 'on' when a new rule is created or when an existing rule is edited, the saved rule may not show up in the list if it does not satisfy *all* the constraints of the filter.

**Conditions**

The *Conditions* tab allows the user to specify an optional condition for the rule execution. This consists of one or more tests (basic conditions), using one of the following logical combinations:

* AND

* OR

* NOT AND

* NOT OR.

Each test consists of a function applied to one or more parameters. The functions are grouped by category (string functions, number functions, ...).

To add a test, the user selects a function from the list on the right. The user interface adjusts the number of input fields according to the parameters of the function. For readability, the first parameter is placed to the left of the function.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/362/medium/4c3c69cf-0d27-46d4-954f-122c0ca33bb7.png?1521081188](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/362/medium/4c3c69cf-0d27-46d4-954f-122c0ca33bb7.png?1521081188)

**Note** Only tests with valid parameters (non-empty after trim) are retained (e.g. after save).

**Assertions**

The *Assertions* tab allows the user to specify the assertions for the rule. This consists of **one** or more tests (basic assertions), using one of the following logical combinations:

* AND

* OR

* NOT AND

* NOT OR.

![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/364/medium/67bf1fed-7ee7-416b-9daf-bf222cd70ad6.png?1521081190](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/364/medium/67bf1fed-7ee7-416b-9daf-bf222cd70ad6.png?1521081190)

The assertions editor works in a similar way as the conditions editor.

**Hints**

The *Hints* tab allows the user to optionally specify one or more hints. Each hint consists of a simple JSON-like document and is constructed similarly to the PIP input data, i.e. by means of a list of key-value pairs.

By default, a hint is only generated when the rule fails (score 0). When the *Always Generate Hint* option is set, the hint will also be generated if the rule is executed, but does not fail.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/366/medium/129bacf9-9e64-4d0a-81f7-c41076d1c1ce.png?1521081191](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/408/366/medium/129bacf9-9e64-4d0a-81f7-c41076d1c1ce.png?1521081191)

### Values in condition and assertion input fields

Values in input fields are converted into internal data types according to the following scheme:

* Try to interpret the value as a boolean (*true* or *false*).

* If the value is a double quoted string, then the value is the string between quotes. Thus "abc" becomes *abc* , "$a.b.c" becomes the string *$a.b.c* and ""abc"" becomes *"abc"*.

* Try to interpret the value as a number.

* Try to interpret the value as a document.

* Try to interpret the value as a sequence.

* Try to interpret the value as a variable (accessor).

* Use the value as is (a string).

### Values in PIP and hint data

The input fields in PIP and hint data are converted into keys and values of JSON objects using the standard JSON parser. Thus value "123" becomes the number *123* , while "abc" remains the string *abc* . The administration tool also stores variable references as strings within the JSON object. When the authorization engine parses that JSON data, it tries to interpret a value of the form *"$A.x.y"* as a variable.

---
language: "en"
---
# AZN Script Interface

In the following examples we suppose that the authorization service has been registered with the name "AZN".

## Example authorization workflow script

Given a document of user-attributes, then the following JavaScript function in a workflow details how to validate access to a resource. The HTML request body should be a JSON string containing the following fields:

* a request field of the form *domain/resource*

* a unique transaction id (for logging);

* a JSON-like structure containing the user-attributes.

The result is again a JSON string.

    function evalDocument(workItem) {
        var service = tb.getService("AZN");
        var request = workItem.input;
        var payload = request.body;

        if (payload !== null) {
            var json = service.parseDocument(payload);

            if (json !== null) {
                var resource = json.resource;
                var document = json.document;
                var transactionId = json.transactionId;

                if (resource !== null && document !== null && transactionId !== null) {
                    var response = service.evalDocument(resource, document, transactionId, true);

                    workItem.output = tb.generateResponse(service.printDocument(response), null, null, 200);

                    return;
                }
            }
        }

        workItem.output = tb.generateResponse('{"error": 2103}', null, null, 200);
    }

### Function parseDocument

The *parseDocument* function of the authorization service parses a JSON string into a document. This document is optimized for use by the authorization engine, but supports the standard JavaScript property access. If the string can not be parsed correctly, the result is *null*.

**Examples**

    var doc = service.parseDocument('{"a": 3, "b": [1, 2]}');
    var i = doc.b[1]; // should be 2
    var error = service.parseDocument('{"a": 1, "b": [1, 2]'); // should be null because it is not a valid JSON syntax.

#### Function evalDocument

The *evalDocument* function of the authorization service validates if a user (with attributes described by the document parameter) has access to a given resource (of the form *domain/resource-id*). Scripts should not pass plain Javascript objects as documents to the authorization service.

**Example**

    dev/user
    dev/user/create
    test/user/create

Here the domains are *dev* and *test* , and the resource ids are *user* and *user/create*.

Two additional parameters must be supplied to the function:

* transactionId (a unique string used for logging);

* a boolean parameter specifying whether the validation should be binary (true or false) or weighted.

In binary mode, the result is either 0 (failure) or 1 (success). In weighted mode, the score can be a number between 0 and 1.

The result is a JSON-like document containing at least a score and an error code:

* an error code;

* a score between 0 and 1;

* an optional list of hints containing JSON-like documents.

**Example**

    {
        "error": 0,
        "score": 0,
        "hints": [ { "type": "step-up", "level": 5 } ]
    }

The result indicates that no error occurred. The score is zero, indicating failure to authorize. The hints fields contains a step-up suggestion, indicating that the user should step up to a stronger authentication level. The contents of the hints is specified by the authorization rules.

#### Function printDocument

The *printDocument* function of authorization service converts a document into a JSON string. In case of errors, *null* is returned.

### Example geo-location PIP workflow

The following workflow script illustrates a simple PIP service. Given a user id, the service calculates or retrieves the default (averaged) location of the user. This information is returned to the rule engine, where it can be used to calculated a weighed score, depending on how close to user is to the default location.

    function execute(workItem) {
        var azn = tb.getService("AZN");
        var document = workItem.input.value;

        if (document.user-id !== null) {
            var location = ... // compute default location as latitude-longitude array
            var response = azn.$2("lat", location[0], "lon", location[1]);

            workItem.output = tb.simpleResponse(response);
        }
        else {
            workItem.output = new tbjava.SimpleValueResponse(1000, 0, null);
        }
    }

The response should always be a document, or null in case of an error. In the latter case, a non-zero status and sub-status may also be specified. This results in the creation of an error document. (The rules can check if the response is an error.)

#### Function $2

The *$2* function of authorization service is a convenience function to create JSON-like documents from scratch. It creates a new document and adds a variable number of consecutive key-value pairs to the document. In the example, the first key is "lat", and its value is the first element of the location array. The second key is "lon" (with value the second element of the array). If the number of parameters in the function call is odd, the last element (a key) is ignored.

#### Function $1

The *$1* function of authorization service is a convenience function to create JSON-like lists from scratch. It creates a new list and the parameters of the function call.

### Registering a rule suite

The following workflow script illustrates how to register rule suites on the fly, while the authorization service is running. The rule suite is represented by an XML body in the HTML request.

    function registerRuleSuite(workItem) {
        var azn = tb.getService("AZN");
        var request = workItem.input;
        var xml = request.body;

        if (xml !== null) {
            var error = azn.registerRuleSuite(xml, false);

            workItem.output = tb.generateResponse("Error: " + error, null, null, 200);
        }
        else {
            workItem.output = tb.generateResponse("Absent xml", null, null, 200);
        }
    }

#### Function registerRuleSuite

The *registerRuleSuite* function of authorization service is a convenience function to register a rule suite (XML string) on the fly. The second parameter specifies if the rule suite should be saved (this only works if the TB configuration of the authorization service specifies a directory of rule suites).

**Errors**  

| Error |                   Description                    |
|-------|--------------------------------------------------|
| 0     | No error                                         |
| 1000  | Empty rule suite XML                             |
| 1001  | Error while creating rule suite                  |
| 1002  | A rule suite with the same resource exists       |
| 1003  | A rule suite with the same name exists           |
| 1100  | The rule suite did not validate correctly        |
| 1200  | Engine not active                                |
| 1201  | Attempt to save when using rule suite index file |
| 1202  | Error while saving rule suite                    |

### Unregistering a rule suite

The following workflow script illustrates how to unregister rule suites on the fly, while the authorization service is running.

    function unregisterRuleSuite(workItem) {
        var azn = tb.getService("AZN");
        var request = workItem.input;
        var rulesuite = request.body;

        if (rulesuite !== null) {
            var error = azn.unregisterRuleSuite(rulesuite);

            workItem.output = tb.generateResponse("Error: " + error, null, null, 200);
        }
        else {
            workItem.output = tb.generateResponse("Absent rulesuite", null, null, 200);
        }
    }

#### Function unregisterRuleSuite

The *unregisterRuleSuite* function of authorization service is a convenience function to unregister a rule suite (XML string) on the fly. The parameter specifies the name of the rule suite. If the rule suite is stored on file in the rule suites directory, the file will be removed.

**Errors**  

| Error |               Description                |
|-------|------------------------------------------|
| 0     | No error                                 |
| 1203  | The rule suite file could be not deleted |

---
language: "en"
---
# AZN Use cases

The following use cases illustrate how to use rule suites to handle various scenarios. The *Script interface to the authorization service* details the structure of the input document.

## Use case 1: Authorization based on context attributes and resource, with the resource attributes in context

### Example

John Doe wants to use SMS Authentication but SMS Authentication is only allowed for users in the company TrustBuilder and SecurIT. He also must have a Belgian phone number.

#### Input

    {
        "transactionId": 1234,
        "resource": "test/SMS_Authentication",
        "document": {
            "user": {
                "principal": "jdoe",
                "attributes": {
                    "userid": "jdoe",
                    "firstname": "John",
                    "lastname": "Doe",
                    "displayname": "John Doe",
                    "company": "Acme Corp",
                    "email": "jdoe@acme.org",
                    "phone": "0123456789",
                }
            },
            "target": {
                "attributes": {
                    "allowedCompanies": ["SecurIT", "TrustBuilder"]
                }
            }
        }
    }

#### Rule suite

    <rulesuite name="check_sms_auth">
        <resources>
            <resource>test/SMS_Authentication</resource>
        </resources>
        <rulesets>
            <ruleset name="Check allowed companies" global="true">
                <rules>
                    <rule name="Rule 1" weight="1" variable="rule1">
                        <condition>
                            <test>
                                <function>startsWith:</function>
                                <param>$in.user.attributes.phone</param>
                                <param>"+32"</param>
                            </test>
                        </condition>
                        <assert>
                            <test>
                                <function>isNotEmpty</function>
                                <param>$in.user.attributes.company</param>
                            </test>
                            <test>
                                <function>contains:</function>
                                <param>$in.target.attributes.allowedCompanies</param>
                                <param>$in.user.attributes.company</param>
                            </test>
                        </assert>
                        <hint>
                            <output>
                                <value>{ "message":"Not Allowed"}</value>
                            </output>
                            <output>
                                <condition>
                                    <test>
                                        <function>=</function>>
                                        <param>$rule1</param>
                                        <param>0</param>
                                    </test>
                                </condition>
                                <value>{ "company": "$in.target.attributes.allowedCompanies" }</value>
                            </output>
                        </hint>
                    </rule>
                </rules>
            </ruleset>
        </rulesets>
    </rulesuite>

#### Result

    {
        error : 0,
        score: 0,
        hints: [
            {
                "message": "Not Allowed"
            },
            {
                "company": ["SecurIT", "TrustBuilder"]
            }]
    }

### Use case 2: Authorization based on context attributes and resource, with the resource attributes retrieved from Policy Information Point

### Example

John Doe wants to use SMS Authentication but SMS Authentication is only allowed for users in the company TrustBuilder and SecurIT. He also must have a Belgian phone number.

#### Input

    {
        "transactionId": 1234,
        "resource": "test/SMS_Authentication",
        "document": {
            "user": {
                "principal": "jdoe",
                "attributes": {
                    "userid": "jdoe",
                    "firstname": "John",
                    "lastname": "Doe",
                    "displayname": "John Doe",
                    "company": "SecurIT",
                    "email": "jdoe@acme.org",
                    "phone": "+323456789",
                }
            }
        }
    }

#### Rule suite

    <rulesuite name="check_sms_auth">
        <resources>
            <resource>test/SMS_Authentication</resource>
        </resources>
        <rulesets>
            <ruleset name="Check allowed companies" global="true">
                <variables>
                    <variable name="r_attr">
                        <request>authmechs</request>
                        <payload>{"type": "sms", id: "SMS_Authentication"}</payload>
                    </variable>
                </variables>
                <rules>
                    <rule name="Rule 1" weight="1" variable="rule1">
                        <condition>
                            <test>
                                <function>startsWith:</function>
                                <param>$in.user.attributes.phone</param>
                                <param>"+32"</param>
                        </condition>
                        <assert>
                            <test>
                                <function>isNotEmpty</function>
                                <param>$in.user.attributes.company</param>
                            </test>
                            <test>
                                <function>contains:</function>
                                <param>$r_attr.allowedCompanies</param>
                                <param>$in.user.attributes.company</param>
                            </test>
                        </assert>
                        <hint>
                            <output>
                                <value>{"message":"Not Allowed"}</value>
                            </output>
                            <output>
                                <condition>
                                    <test>
                                        <function>=</function>>
                                        <param>$rule1</param>
                                        <param>0</param>
                                    </test>
                                </condition>
                                <value>{"company": "$r_attr.allowedCompanies"}</value>
                            </output>
                        </hint>
                    </rule>
                </rules>
            </ruleset>
        </rulesets>
    </rulesuite>

#### Result

    {
        "error": 0,
        "score": 1
    }

---
language: "en"
---
# BaseEncryptionService

|    **Name**    |                  BaseEncryptionService                  |
| **Class Path** | `be.securit.trustbuilder.service.BaseEncryptionService` |
|  **Versions**  |                         9 10 11                         |
|----------------|---------------------------------------------------------|

## Overview

The `BaseEncryptionService` class provides encoding and decoding functionality for various encoding formats, including:

* Base64

* Y64 (modified Base64 for URL safety)

* Hexadecimal

* Fingerprint (Hex with colons)

* Base32

It also supports UTF-8 encoding and allows for custom encoding configuration.

*** ** * ** ***

## **Available Functions**

### **Encoding and Decoding Methods**

#### `protected byte[] decode(String data, String decodingFormat): byte[]`

Decodes an input string based on the specified format.

* **Parameters:**

  * `data` (`String`): The encoded string.

  * `decodingFormat` (`String`): The encoding format (`y64`, `hex`, `base64`, or `plain`).

* **Returns:**

  * `byte[]`: The decoded byte array.

* **Throws:**

  * `UnsupportedEncodingException` if an unsupported format is provided.

#### `protected String encode(byte[] bytes, String encodingFormat): String`

Encodes a byte array into the specified format.

* **Parameters:**

  * `bytes` (`byte[]`): The data to encode.

  * `encodingFormat` (`String`): The target encoding format (`y64`, `hex`, `fingerprint`, `base64`).

* **Returns:**

  * `String`: The encoded string.

* **Throws:**

  * `UnsupportedEncodingException` if encoding fails.

*** ** * ** ***

### **Y64 Encoding and Decoding**

#### `public String encodeY64(byte[] bytes): String`

Encodes a byte array into Y64 format (a modified Base64 for URL safety).

* **Parameters:**

  * `bytes` (`byte[]`): The data to encode.

* **Returns:**

  * `String`: The Y64 encoded string.

#### `public byte[] decodeY64(String data): byte[]`

Decodes a Y64-encoded string back into bytes.

* **Parameters:**

  * `data` (`String`): The Y64 encoded string.

* **Returns:**

  * `byte[]`: The decoded byte array.

*** ** * ** ***

### **Base32 Encoding and Decoding**

#### `public String encodeBase32(String data, String decodingFormat): String`

Encodes a string into Base32 format after decoding it from a given format.

* **Parameters:**

  * `data` (`String`): The input string.

  * `decodingFormat` (`String`): The format of the input string (`y64`, `hex`, `base64`, or `plain`).

* **Returns:**

  * `String`: The Base32 encoded string.

* **Throws:**

  * `UnsupportedEncodingException` if an unsupported format is provided.

#### `public String decodeBase32(String base32Text, String decodingFormat): String`

Decodes a Base32-encoded string into a specified format.

* **Parameters:**

  * `base32Text` (`String`): The Base32 encoded string.

  * `decodingFormat` (`String`): The desired output format (`y64`, `hex`, `base64`, or `plain`).

* **Returns:**

  * `String`: The decoded value.

* **Throws:**

  * `UnsupportedEncodingException` if an unsupported format is provided.

*** ** * ** ***

### **Configuration Methods**

#### `public void setEncoding(String encoding): void`

Sets the encoding format for the service.

* **Parameters:**

  * `encoding` (`String`): The desired encoding format (default is `UTF-8`).

*** ** * ** ***

## **Summary**

The `BaseEncryptionService` provides flexible encoding and decoding capabilities, supporting multiple formats such as Base64, Y64, Hex, Base32, and Fingerprint-style encoding. It is useful for cryptographic operations, secure data handling, and encoding compatibility with different formats.

This service allows for seamless conversion between different encoding formats, making it a versatile utility for security and data transformation needs.

---
language: "en"
---
# CaptchaVerificationPublicService

|    **Name**    |                     CaptchaVerificationPublicService                     |
| **Class Path** | `io.trustbuilder.andromeda.web.captcha.CaptchaVerificationPublicService` |
|  **Versions**  |                                 9 10 11                                  |
|----------------|--------------------------------------------------------------------------|

## Overview

The `CaptchaVerificationPublicService` provides functionality to verify whether a CAPTCHA challenge has been successfully completed. This service is intended for use in authentication workflows where CAPTCHA verification is required.

## Available Functions

### `verifyCaptcha(String userResponseToken, String source, String username, String idHubSessionId): int`

Verifies if the provided CAPTCHA response token is valid.

* **Parameters:**

  * `userResponseToken` (`String`): The response token provided by the user (`g-recaptcha-response` parameter in the HTTP request).

  * `source` (`String`, *optional*): The source IP address for event logging.

  * `username` (`String`, *optional*): The username associated with the CAPTCHA request, used for event tracking.

  * `idHubSessionId` (`String`, *optional*): The session ID from the IDHub system for event tracking.

* **Returns:**

  * `int`: The HTTP status code indicating the result of the verification.

    * A successful verification will return a **200** status code.

    * A failed verification will return an appropriate error code.

*** ** * ** ***

## Summary

The `CaptchaVerificationPublicService` allows applications to validate CAPTCHA responses and log associated metadata, such as IP addresses, usernames, and session IDs, for security purposes. It is a crucial component for preventing automated bot interactions and ensuring secure authentication workflows.

---
language: "en"
---
# Certificate adapter

The CertificateAdapter allows TrustBuilder to validate X509-certificates based on their validity periods and a trusted store of signer certificates. In order to be valid: \* the certificate's period must be valid \* the signer must be found in the trust store and the certificate's signature must comply with the signer's public key.

## Prerequisites

**TrustStore**

In order to validate the certificate a truststore is required (if one isn't provided fallback is done on the keystore) For more information about creating and/or using key- and truststores in trustbuilder refer to the KeyStore and TrustStore chapter.

### Configuration

**AdapterUniqueID**

Unique name assigned to this adapter; the name is used to reference the adapter in the workflow. The ID has following requirements:

* START with a letter or _ (underscore)

* FOLLOWED by a combination of following characters: Letter, Number, '.' (dot), '-' (dash), '_' (underscore)

#### Workflow Settings

A request for the adapter is prepared by specifying the following properties/scripts in the adapter activity:

* Input Property: the variable containing the instructions the adapter have to execute

* Output Property: the variable the adapter will store the response in after execution

* Before Adapter Script: script that will be executed before calling the adapter

* After Adapter Script: script that will be executed after the adapter fulfilled its task

#### Request - API

**certificateRequest** The CertificateRequest allows clients check the X509 certificate's validity period and to validate its signature using a signer's public key.

    certificateRequest(base64Certificate) 

with parameters:

    base64Certificate: Non-null, non-empty string; encoded in base64-format (may contain "-CERTIFICATE-" and "-END CERTIFICATE-" delimiters) 

#### Response - API

**Common Properties** The response API can be applied to the variable specified in the "output property" (see "Workflow Settings"): to verify whether the action performed by the adapter was successful, to query for the data returned by the adapter.

All responses have four properties in common:

* **status** Status flag indicating whether the response is ok (0) or not (1).

* **substatus** Response specific number indicating what the problem was, eg. http status code

* **message** Response specific message in case there was a problem (can be null)

* **rc** Return Code, a human readable code based on the substatus

The status flag indicates whether a request was valid yes or no; consequently, the message or return code (rc) can be used to give the end-user a reasonable explanation or send the information to the underlying logging system.

**Adapter Specific Properties**  

|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| serialnumber       | Certificate serial number                                                                                                                                                                       |
| signature          | Signature                                                                                                                                                                                       |
| subject            | Subject DN of the certificate                                                                                                                                                                   |
| getAki()           | Authority Key Identifier of the certificate                                                                                                                                                     |
| getIssuer()        | Issuer DN of the certificate                                                                                                                                                                    |
| getKeyUsage()      | Object with boolean properties: * digitalSignature * nonRepudiation * keyEncipherment * dataEncipherment * keyAgreement * certificateSigning * crlSigning * enciphermentOnly * deciphermentOnly |
| getPublicKeyInfo() | Object containing following properties * algorithm * encodedKey * format * type * rsa (boolean) * dsa (boolean)                                                                                 |
| getSki()           | Signer Key Identifier of the certificate                                                                                                                                                        |
| getValidFrom()     | Date from which the certificate is valid from                                                                                                                                                   |
| getValidTill()     | Date till which the certificate is valid to                                                                                                                                                     |
| getVersion()       | Version of this certificate                                                                                                                                                                     |
| getCertificate()   | Gets the certificate in a base64 format                                                                                                                                                         |
| getSigner()        | Object containing the same functions as the certificate, but all of them apply on the signer's certificate                                                                                      |

#### Response Codes

| Status | Sub status |         Description          |
|--------|------------|------------------------------|
| 0      | 0          | OK                           |
| \>0    | 1          | Certificate not valid        |
| \>0    | 2          | Certificate expired          |
| \>0    | 3          | Certificate not yet valid    |
| \>0    | 4          | No AKI or issuer             |
| \>0    | 5          | Invalid AKI or issuer        |
| \>0    | 6          | Signer certificate not found |
| \>0    | 7          | Keystore error               |
| \>0    | 8          | Signature invalid            |
| \>0    | 9          | Invalid Base64               |

#### Example

Request

    function createCertificateRequest(workItem){
        //workItem.certificate contains the base64 certificate request obtained through a header of direct as parameter
        workItem.certrequest = tb.certificateRequest(workItem.certificate);
    }

Response

    function handleResponse(workItem){
        if(certresponse.status == 0){
            tb.log("Certificate is valid.");
            return 'true';
        }
        return false;
    }

---
language: "en"
---
# Classes

Currently the following services are available

* **Memory / Session service** be.securit.trustbuilder.util.TimedBlockingHashMap

* **MemCached / Session service** be.securit.trustbuilder.service.MemcachedService

* **DateService** be.securit.trustbuilder.service.DateService

* **EncryptionService** be.securit.trustbuilder.service.EncryptionService

* **Radius Endpoint Service** be.securit.trustbuilder.service.RadiusService

* **Ldap Endpoint Service** be.securit.trustbuilder.service.LdapService

* **Domtai Service** be.securit.trustbuilder.service.DomTai

* **Redis Service** be.securit.trustbuilder.service.RedisService

The Service section can be used to call different services, for example a memory store.

    <stb:Service stb:id="urlStore" stb:type="be.securit.trustbuilder.util.TimedBlockingHashMap" stb:singleton="true">
       <stb:property stb:name="ttl">30000</stb:property>
    </stb:Service>
    <stb:Service stb:id="objectStore" stb:type="be.securit.trustbuilder.util.TimedBlockingHashMap" stb:singleton="true">
      <stb:property stb:name="ttl">30000</stb:property>
    </stb:Service>

In this example we configure 2 memory stores, this can be used to store a session, send information between threads and so on. The ttl property specify's how long a key exists in the store in milliseconds.

Getting access to a service from within the workflow can be done via the following

    tb.getService("urlStore");

**NOTE** in order to enable / change session service provider the **trustbuilder application** needs to be restarted on application server level.

You can create your own service by setting the type to the fully qualified name of your java class. Requirements for this class are:

* It should have a public constructor

* Functions that need to be called in the workflow should work with primitives and return primitives.

* Setters and getters can be used to change the internal state of the service.

## TimedBlockingHashMap Service

Classname: be.securit.trustbuilder.service.TimedBlockingHashMap

This service allows TrustBuilder workflows to store key/value pairs in memory for a certain time.

Property:

* **TimeoutInSec** Timeout of hashmap in seconds

* **ttl** Timeout of hashmap in milliseconds

If both are used, the last property in the config is used. Best practice is use only one property.

Functions:

* **get(key)** Get item by key

* **get(key,timeout)** Get item by key , timeout optional

* **put(key,value)** Put key/value pair

* **remove(key)** Remove item from store

## DateService

Classname : be.securit.trustbuilder.service.DateService

**Format variables**

* Letter Date or Time Component Presentation Examples

* G Era designator Text AD

* y Year Year 1996; 96

* M Month in year Month July; Jul; 07

* w Week in year Number 27

* W Week in month Number 2

* D Day in year Number 189

* d Day in month Number 10

* F Day of week in month Number 2

* E Day in week Text Tuesday; Tue

* a Am/pm marker Text PM

* H Hour in day (0-23) Number 0

* k Hour in day (1-24) Number 24

* K Hour in am/pm (0-11) Number 0

* h Hour in am/pm (1-12) Number 12

* m Minute in hour Number 30

* s Second in minute Number 55

* S Millisecond Number 978

* z Time zone General time zone Pacific Standard Time; PST; GMT-08:00

* Z Time zone RFC 822 time zone -0800

**Functions**

* **now(format)** Format now as specified

* **epoch()** Now as epoch number (seconds since 1970)

* **inRange(start,end)** Returns true if now is between start and end as epoch dates

* **nowISO8601()** Now in ISO8601 format

* **formatISO8601(date,timezone)** Date in ISO8601 format where date is in epoch, timezone is a string

* **format(date,format)** Date in specific format where date is in epoch

* **calcDateISO8601(expression)** Date in expression in ISO8601 format where expression can be +/- x \[s\|m\|h\|d\]

* **calcDate(expression,format)** Date in expression in format where expression can be +/- x \[s\|m\|h\|d\]

* **calcDateAsEpoch(expression)** Date as epoch where expression can be +/- x \[s\|m\|h\|d\]

* **calcDateAsEpoch(date,expression)** Calculate date with expression using date as starting point

**formatISO8610()**

    NormalizedCustomID:
             GMT Sign TwoDigitHours : Minutes
     Sign: one of
             + -
     TwoDigitHours:
             Digit Digit
     Minutes:
             Digit Digit
     Digit: one of
             0 1 2 3 4 5 6 7 8 9

Example :

    var time = tb.getService("dateService");
    var now = time.epoch();                        // EPOCH : 1395996050671
    var iso = time.formatISO8601(now);             // ISO DATE : 2014-03-28T09:40:50.671+01:00
    var gmt5 = time.formatISO8601(now,'GMT+05:00'); // NO SPACES !   GMT+5 DATE: 2014-03-28T13:40:50.671+05:00
    var zulu = time.formatISO8601(now,'UTC');       // ZULU DATE: 2014-03-28T08:48:38.075Z

## Domtai Service

Classname : be.securit.trustbuilder.service.DomTai

Properties:

* keySpec generated base64 encoded Key for the DomTai plugin in Lotus Notes

* charSet charset for the encryption (normally ISO-8859-1)

Example:

    DOMTAI = tb.getService("domtai service");
    var domtaiattr = DOMTAI.encrypt("some string");

## Encryption Service

be.securit.trustbuilder.service.EncryptionService

Properties:  

|    property name    |                description                |
|---------------------|-------------------------------------------|
| key                 | base64 encoded binary key                 |
| iv                  | base64 encoded binary iv                  |
| encryptedKey        | password tool encoded key                 |
| encryptedIv         | password tool encoded iv                  |
| PKCS8EncodedKeySpec | base64 encoded binary public key          |
| RsaPublicKey        | base64 encoded binary public key          |
| RsaPkcs8PublicKey   | base64 encoded binary public key          |
| encoding            | sets the encoding format (default "UTF-8" |

Ciphers:

The following ciphers are supported (key length between parentheses)

* `AES/CBC/NoPadding` (128)

* `AES/CBC/PKCS5Padding` (128)

* `AES/ECB/NoPadding` (128)

* `AES/ECB/PKCS5Padding` (128)

* `DES/CBC/NoPadding` (56)

* `DES/CBC/PKCS5Padding` (56)

* `DES/ECB/NoPadding` (56)

* `DES/ECB/PKCS5Padding` (56)

* `DESede/CBC/NoPadding` (168)

* `DESede/CBC/PKCS5Padding` (168)

* `DESede/ECB/NoPadding` (168)

* `DESede/ECB/PKCS5Padding` (168)

* `RSA/ECB/PKCS1Padding` (1024, 2048)

* `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` (1024, 2048)

* `RSA/ECB/OAEPWithSHA-256AndMGF1Padding` (1024, 2048)

Functions:  

|                                                                         function                                                                          |                                                              Description                                                               |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
| encrypt(cipher,string,format)                                                                                                                             | Encrypt the string and return the encrypted data in the format (base64,hex,y64)                                                        |
| decrypt(cipher,encryptedString,format)                                                                                                                    | Decrypt the encryptedString by decoding in format (base64,hex,y64) and return the original string                                      |
| generateHMac(cipher,string,inputformat, outputformat)                                                                                                     | Encrypt the string with hmac and return the result in the outputformat (base64,hex, y64). Inputformat : null, base64, hex, y64         |
| hash(hashAlg, message, encodingFormat)                                                                                                                    | Hash (according to the hashAlg=algorithm) the message and return it in the encoding format (base64, hex, y64)                          |
| saltedHash(password, salt)                                                                                                                                | Hashes (sha-1) the concatenated password+salt and retuns it base64 encoded                                                             |
| generateSalt(int len)                                                                                                                                     | Generates a salt with the specified length                                                                                             |
| sign(\[algorithm\](<http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature> ), data, decodingFormat, encodingFormat) | Sign decoded data (using decodingFormat) and encode the signed data                                                                    |
| verify(\[algorithm\](<http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature> ), data, signature, decodingFormat)    | Verify the signed data by first decoding it using the decodingFormat. Returns boolean indicating whether the signature matched or not. |

Available ciphers can be found for the sun at [jdk6](http://docs.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJSSEProvider) [jdk7](http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJSSEProvider)

Example

    var encryptionService = tb.getService("encryption"); // encryption is the name of the service
    var pwd_hash_user = encryptionService.hash("SHA-512",workItem.input.credentials.password+salt,"base64");

    // Encrypts the signaturebase with HMAC-SHA1 and returns a BASE64 encoded string
    var signature = encryptionService.generateHMac( "HmacSHA1", signaturebase, null, "base64");

**.setKey**

When using the setKey functionality it's recommended to use the Encryption Service with the singleton flag set to false. If the singleton is set to true, the key is persistent until the next .setKey call or restart of the TrustBuilder Server.

Some cases another key must be used instead of the default one. This key can be set dynamic as an BASE64 encoded string.

    encryptionService.setKey(tb.base64Encode("5VRtmBeg9jRJ5mRAsncaGwCGJ2YazTxReQIqbcHqZc",true));   // Encode as string true
    var signature = encryptionService.generateHMac( "HmacSHA1", signaturebase, "base64");   // base64 is default

encodingFormat/decodingFormat

* base64 ; Base64 encode / decode

* y64 : (urldecode) + base64 + (urlencode)

* hex : hex encode / decode

* none : take the bytes from the string as UTF-8

## LDAP Endpoint Service

classname : be.securit.trustbuilder.service.LdapService

The LDAP endpoint service is opening a listener port for the ldap endpoint.

Currently only a search and authenticate is supported. Search is however limited to what you define in the workflows. Using a normal ldap client to browse the server isn't possible as the endpoint is ment for authentication only.

Properties:

* port : Port used for the listener

* workflow : Which workflow has to be run by the engine when this service is called

**Note on ldap port**

If you running your as non-root user you can't open ports under 1024. We recommend setting the ldap port higher and if you want to use port 389 fpr ldap make usage of software that forwards the connection from port 389 to your trustbuilder ldap endpoint.

Config:

    <stb:Service stb:id="ldapserv" stb:singleton="false" stb:synchronised="false" stb:type="be.securit.trustbuilder.service.LdapService">
       <stb:property stb:name="port">1389</stb:property>
       <stb:property stb:name="workflow">ldapworkflow</stb:property>
    </stb:Service>

We set the listener to port 1389 and attach the "ldapworkflow" to it. Each requests to this endpoint starts the configured workflow.

Requests:

**Bind Request**

    {"user":"null","type":"bind","ip":"10.0.10.243","dn":"cn=administrator,dc=securit,dc=biz","password":"somepasswd"}

Exposed fields in the input :

    user :
    type : bind
    ip : ip of requesting host
    dn : DN to bind to
    password : the given password to bind

**Search Request**

    Engine.WorkItem - set ___INPUT___=LdapEndpointSearchRequest: {
           baseDN: 'dc=securit,dc=biz',
           scope: 'SUB',
           filter: '(&(objectclass=posixaccount)(uid=ewold))',
           attributes: '[userPassword, cn, gidNumber, uidNumber, loginShell, objectClass, gecos, uid, homeDirectory]',
    } []

    {"user":"null","type":"search","base":"dc=securit,dc=biz","scope":"SUB","filter":"(&(objectclass=posixaccount)(uid=username))","attributes":["userPassword","cn","gidNumber","uidNumber","loginShell","objectClass","gecos","uid","homeDirectory"]}

Exposed fields in input :

    User :
    Type : Search
    Base : Search base
    Scope : Search scope
    Filter : Search filter
    Attributs : Required attributes in return

**Response**

To create a response to the ldap client TrustBuilder uses a function that called on the input object.

Bind Response :

    // Authentication accepted
    workItem.output = workItem.input.generateResponse(0);

    // Authentication rejected
    workItem.output = workItem.input.generateResponse(49);

Search Response :

    var username = "testuser";
    var response = {
                           "host" : "10.0.10.243",
                           "gidNumber" : info.gidNumber,
                           "uidNumber" : info.uidNumber,
                           "homeDirectory" : info.homeDirectory,
                           "loginShell" : info.loginShell,
                           "userPassword" : "password"
                   };
    workItem.output = workItem.input.generateResponse(0);
    // Add search Result and attributes
    workItem.output.addResult("cn="+username,response);

The addResult function can be called multiple times.

**Returning error codes**

The 49 is an invalid credentials error code. If you wish to use other codes you can have a look at : <http://docs.oracle.com/javase/jndi/tutorial/ldap/models/exceptions.html>

## MemCached Service

Classname: be.securit.trustbuilder.service.MemcachedService

To use this service an extra jar has to be included in your trustbuilder-web.war file. Download the latest xmemcached jar file and place it in the /lib folder of your TrustBuilder package.

Property:

* **address** Address of the remote memcached service

* **poolsize** Size of the connectionpool to use

Functions:

* **get(key)** Get item by key

* **put(key,value)** Put key/value pair

* **add(key,value)** Set key/value pair

* **replace(key,value)** Replace key/value pair

* **set(key,expiry,value)** Put key/value pair with expiry

* **add(key,expiry,value)** Set key/value pair with expiry

* **replace(key,expiry,value)** Replace key/value pair with expiry

* **remove(key)** Remove item from store

Memory / Session service:

There are 3 different session services available. They allow to integrate a session service in the workflow. However, it's not limited to only sessions, they can be used as a way to pass information between requests.

Possible implementations:

**database: be.securit.trustbuilder.util.DatabaseCacheService**

Properties: \* jndi \* putStatement (optional) \* getStatement (optional) \* remStatement (optional)

**memcached: be.securit.trustbuilder.service.MemcachedService**

Properties: \* address (supports multiple addresses) \* poolsize \* memory be.securit.trustbuilder.util.SimpleCacheService

**expiring memory: be.securit.trustbuilder.util.TimedBlockingHashMap**

Properties: \* ttl Time to keep the entries in memory before removing them

These implementations can be used as backend for sessionmanagement, see the section over sessionmanagement.

Functions:

* **put(key,object)** Put a key in the store with a value (expiring after ttl defined in the config)

* **get(key)** Get the value from the store by its key

* **get(key,timeoutSeconds)** Get the value from the store by its key with a timeout in seconds

* **remove(key)** Remove a value from the store

## Radius Endpoint Service

Classname: be.securit.trustbuilder.service.RadiusService

The radius endpoint service is opening a listener port for the radius endpoint.

Properties:

* **sharedSecret** : The shared secret between the client and the endpoint. This is encoded by the [Trustbuilder password tool](https://trustbuilder.zendesk.com/hc/en-us/articles/360019968674-passwordtool).

* **port** : Port used for the listener

* **workflow** : Which workflow has to be run by the engine when this service is called

## Redis Service

Classname: be.securit.trustbuilder.service.RedisService

Requirements:

To use this service you must install to following jar in your application servers library. For TrustBuilder appliance this location is /opt/trustbuilder/tomcat-core/lib/ext

* [Jedis](https://search.maven.org/remotecontent?filepath=redis/clients/jedis/2.9.0/jedis-2.9.0.jar)\> 2.9.0

Property:

* ***host*** Set the hostname of the redis server (only for single node)(this is for backwards compatibility and will be removed in the next major release)

* ***timeOutInSec*** Default time to live for a key that gets added in seconds.

* **master**Name of the master node.

* **sentinels**";" - separated list with addresses of the sentinels.

* **password**Optional password for the redis cluster.

Invoking Redis in the scripts:

Since the Redis Service is a wrapper around the jedis calls we have to threat the function somewhat different than other services. The Redis Service is using a Pool of connections with tha Apache Commons pooling library.

Creating a pool :

    var redispool = tb.getService("Redis");

Invoke the pool :

    redispool.invoke(function(jedis){
        // Your redis commands are place here. The jedis name can be anything you want
        but you need it to call the commands
        jedis.set("foo", "bar");
    });

This wil set a key "foo" with value "bar" in the Redis Server.

Functions:

Since redis has a lot of functions we will only explain the basics. Most functions are derived from the original redis commands fount on the [Redis website](http://redis.io/commands).

Basic Functions:

***set(key,data)***

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

    jedis.set("foo", "bar");

***get(key)***

Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.

    var data = jedis.get("foo");   // bar 

***incr(key)*** ***incrBy(key, increment)***

Increments the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers.

*Note: this is a string operation because Redis does not have a dedicated integer type. The string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation.*

Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.

    jedis.incr("foo");  // increment 1 
    jedis.incrBy("foo", 10);  // increment by 10

***decr(key)*** ***decrBy(key)***

Decrements the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers.

    jedis.decr("foo");
    jedis.decrBy("foo", 10);

***Expire(key, seconds)***

Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout is cleared only when the key is removed using the DEL command or overwritten using the SET or GETSET commands. This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will leave the timeout untouched. For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH, or altering the field value of a hash with HSET are all operations that will leave the timeout untouched. The timeout can also be cleared, turning the key back into a persistent key, using the PERSIST command.

*Refreshing expires*

It is possible to call EXPIRE using as argument a key that already has an existing expire set. In this case the time to live of a key is updated to the new value. There are many useful applications for this, an example is documented in the Navigation session pattern section below.

    jedis.expire("foo", 300);   // Expire foo in 5 minutes

***expireAt(key, timestamp)***

EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970).

Please for the specific semantics of the command refer to the documentation of EXPIRE. Background

EXPIREAT was introduced in order to convert relative timeouts to absolute timeouts for the AOF persistence mode. Of course, it can be used directly to specify that a given key should expire at a given time in the future.

    jedis.expireAt("foo", "1414500547"");

***persist(key)***

Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).

    jedis.persist("foo");   // persist the foo key

***setbit(key, bit, boolean)***

Sets or clears the bit at offset in the string value stored at key. The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset argument is required to be greater than or equal to 0, and smaller than 232 (this limits bitmaps to 512MB). When the string at key is grown, added bits are set to 0.

    jedis.set("foo", "0");  // Set foo to 0
    jedis.setbit("foo", 3, true);
    jedis.setbit("foo", 7, true);

    /*
     * byte: 0 1 2 3 4 bit: 00010001 
     */

***getbit(key, bit)***

Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also assumed to be a contiguous space with 0 bits.

    jedis.getbit("foo",3);  // true
    jedis.getbit("foo",5);  // false

### Hashes

***hset(key,field,data)***

Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.

    jedis.hset("foo", "bar", "car");

***hsetnx(key,field,data)***

Sets field in the hash stored at key to value, only if field does not yet exist. If key does not exist, a new key holding a hash is created. If field already exists, this operation has no effect.

    jedis.hsetnx("foo", "bar", "car");

***hget(key,field)***

Returns the value associated with field in the hash stored at key.

    jedis.hget("foo", "bar");    // car 

***hmset(key, key/value object)***

Sets the specified fields to their respective values in the hash stored at key. This command overwrites any existing fields in the hash. If key does not exist, a new key holding a hash is created.

    jedis.hmset("foo", { bar : "car", user : "John");

**hgetAll(key)**

Returns all fields and values of the hash stored at key. In the returned value, every field name is followed by its value, so the length of the reply is twice the size of the hash.

    var data = jedis.hgetall("foo");   
     var user = data.get("user");      // John 

***hmget(key, field, \[field\])***

Returns the values associated with the specified fields in the hash stored at key. For every field that does not exist in the hash, a nil value is returned. Because a non-existing keys are treated as empty hashes, running HMGET against a non-existing key will return a list of nil values.

    var data = jedis.hmget("foo", "bar", "user");
    var user = data.get("user");      // John 

***hexists(key, field)***

Returns if field is an existing field in the hash stored at key.

    var dataexists = jedis.hexists("bar", "foo");  // true 
    var datanotexists = jedis.hexists("bar", "example");  // false

**hdel(key, field, \[field\])**

Removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.

*Remark : to remove a complete hash you have to use the delete command (del)*

    // deleting a field 
    jedis.hdel("foo", "bar"); 

    // deleting a complete hash
    jedis.del("foo");

***hlen(key)***

Returns the number of fields contained in the hash stored at key.

    var length = jedis.hlen("foo");    // 2

***Expiring hashes***

Only a full hash can be set to expire, not the fields on their own.

## Digipass Service

Requirements:

To use this service you must first install the VACMAN Controller. Then you need to do the following steps:

* Add the aal2wrap.jar to your classpath. The file can be found in your VACMAN controller installation directory.

* Add the VACMAN controller library to your classpath or to your java.library.path. The file can be found in your VACMAN controller installation directory. Make sure the version matches your platform.

* Create a MySQL database scheme and populate it using the digipass*service*mysql.sql script. It can be found in the trustbuilder.war.

Property:

**Database Properties**  

| Property |                       Description                        |
|----------|----------------------------------------------------------|
| jdbcUrl  | The JDBC Url you want to use to connect to the database. |
| username | The username to use to connect to the database.          |
| password | The username password to connect to the database.        |

**Digipass Properties**  

|         Property         | Default |                                                                                                                                                                                                                                                                                                                                 Description                                                                                                                                                                                                                                                                                                                                 |
|--------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| CheckChallenge           | 1       | 0: No challenge checking 1: Check the parameter then verify with the DPDate Challenge                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| CheckInactiveDays        | 0       | Acceptable number of days of user/token inactivity. Past this number, returncode 205 will be genrated and the digipass will have to be reset. 0 = disabled                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| DeriveVector             | 0       | Vector used to make the data encryption unique for a host                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| DiagnosticLevel          | 0       | Requested diagnostic level                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| EventWindow              | 100     | Expressed in number of iterations This represents the acceptable event counter difference between digipass and host. This parameter applies only for event based operating modes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| GMTAdjustment            | 0       | GMT Time adjustment to perform in case the C language gmtime function doesn' t give an accurate value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| HSMSLotId                | 0       | HSM Slot Id used to store Storage Key and Transport Key                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| IdentificationTreshold   | 0       | Number of successive identification errors that will cause server-side locking of the digipass. When the specified number is reached, return code 202 is sent to the caller. 0=disabled                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| IdentificationTimeWindow | 100     | This size determines the acceptable time difference between a digipass and the host system for identification function. This difference is adjusted to the last knows shift for each token. the maximum drift correction acceptance is 1 second per 6 hour period. Since version 3.5.0.3, this parameter can be set to be dynamic or static. If dynamic, the size of the window will increase as the time passes since last use of the DIGIPASS. Because of this feature, the Dynamic window can be set smaller than if Static window was used. TW_DYNAMIC_WINDOWS (in aal2sdk.h) is a bitmask indicator that can be used to show whether ITimeWindow is Dynamic or Static. |
| OnlineSignature          | 0       | Level of online signature 1: several signatures are allowed in the same timestep (except identical successive ones) 2: only one signature per timeStep is allowed 3: for event based signature, use the deffered data input parameter                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| SignatureTreshold        | 0       | Number of successive signature errors that will cause server-side locking of the digipass. When the specified number is reached; return code 203 is sent to the caller. 0=disabled                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| SignatureTimeWindow      | 24      | Signature window size in number of time steps.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| StorageDeriveKey1        | 0       | Derivation key part 1 used to make data encryption unique for a host.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| StorageDeriveKey2        | 0       | Derivation key part 2 used to make data encryption unique for a host.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| StorageDeriveKey3        | 0       | Derivation key part 3 used to make data encryption unique for a host.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| StorageDeriveKey4        | 0       | Derivation key part 4 used to make data encryption unique for a host.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| StorageKeyId             | 0       | Key Id used to read (Decrypt) DIGIPASS Blob from database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| TransportKeyId           | 8388607 | Key Id used to read (Decrypt) DIGIPASS Blob from database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| SynchronizationWindow    | 6 hours | The Initial Time Synchronization Window - for the first verification of a DIGIPASS. This parameter allows the verification process to calculate the initial deviation between a DIGIPASS time and the VACMAN Controller GMT Time. IMPORTANT: This value is expressed in hours or minutes.                                                                                                                                                                                                                                                                                                                                                                                   |

Invoking Digipass Service in the scripts:

The Digipass service is used to load the Digipass tokens into the database and use them to do validation.

Retrieving the service :

    var digipassService = tb.getService("DigipassService");

Functions:

***loadDPX(filename, transportkey, staticvector)***

Loads the DPX file specified in the filename parameter and stores it into the database. The transportkey is the key used to decrypt the DPX file. If the staticvector parameter is not specified, the call will try to retieve it from the DPX file. If you specify the staticvector parameter, it should be the unencrypted staticvector.

    digipassService.loadDPX("/opt/securit/dpx/demo.dpx", "11111111111111111111111111111111", null);

This method can throw SQLExceptions and DigipassExceptions which should be handled by the caller.

***generateActivationCode(serialnumber)***

This method activates the Digipass token and returns a digipass activation object. This digipass activation object contains 3 fields that can be retrieved: \* Serial number with getSerialNumber(). \* Activation code with getActivationCode(). \* Encrypted event reactivation counter with getXerc().

    var data = digipassService.generateActivationCode("VDS10000120");

This method can throw SQLExceptions and DigipassExceptions which should be handled by the caller.

***validateOtp(serial, application, otp)***

Validates the One Time Password (OTP) for that serial number and application. If the Digipass serial only has one Response Only application, then application should not be supplied in the parameters. Otherwise it is required.

    digipassService.validateOtp("VDS10000120", null, "123456");

This method can throw SQLExceptions, DigipassExceptions and IllegalArgumentException which should be handled by the caller.

***getFreeDigipass(dpType)***

This method returns the serial number of the first available Digipass of that type or the first free Digipass that is available (if dpType is not specified). There are 5 different values for status.

* Free (0)

* Pending (1)

* Assigned (2)

* Revoked (99)

* Unavailable (-1)

Depending on the situation you may update the status from Free to Pending or from Free to Assigned.

    digipassService.getFreeDigipass("DP300");

This method can throw SQLExceptions which should be handled by the caller.

***getFreeLicense()***

This method returns the serial number of the first available MDL Digipass license. We have 5 possible status values:

* Free (0)

* Pending (1)

* Assigned (2)

* Revoked (99)

* Unavailable (-1)

    digipassService.getFreeLicense();

This method can throw SQLExceptions which should be handled by the caller.

***updateDigipassStatus(serialnumber, status, application)***

Updates the status of the Digipass serial to the specified status. We have 3 statusses:

* Free (0)

* Pending (1)

* Assigned (2)

* Revoked (99)

* Unavailable (-1)

If the application is specified, only that application status is updated. In general you will want to update all the statusses of the Digipass applications to a certain value.

    digipassService.getFreeDigipass("VDS10000120", 2, null);

This method can throw SQLExceptions and IllegalArgumentException which should be handled by the caller.

***updateLicenseStatus(serialnumber, status)***

Updates the status of a specific Digipass MDL license to the specified status. We have 5 status values:

* Free (0)

* Pending (1)

* Assigned (2)

* Revoked (99)

* Unavailable (-1)

    digipassService.updateLicenseStatus("VDS10000120", 2);

This method can throw SQLExceptions and IllegalArgumentException which should be handled by the caller.

***updateInstanceStatus(serialnumber, instanceNumber, status)***

Updates the status of a specific instance for a specific Digipass MDL license to the specified status. We have 5 status values:

* Free (0)

* Pending (1)

* Assigned (2)

* Revoked (99)

* Unavailable (-1)

    digipassService.updateInstanceStatus("VDS10000120",1,2);

This method can throw SQLExceptions and IllegalArgumentException which should be handled by the caller.

***getDigipassStatus(serialnumber, application)***

Returns the status of the Digipass as an integer based on the serial number and the application (optional). If the application is not supplied, all the applications should have the same status or -1 will be returned.

    var status = digipassService.getDigipassStatus("VDS10000120");

***getDigipassByDpType(dpType, status)***

Returns an array of DigipassToken objects for a specific type and status

    digipassService.getDigipassByDpType("DP300",0);

Returns an array of objects

    [{"serialNumber":"VDS10000120",
      "dpMode":"CR", //possible values are CR, RO, SG and MM
      "dpBlob":"12f1ds231f23ds, //base64 encoded string of the blob
      "dpType":"DP300",
      "application":"APPL1",
      "sharedSecret":"1346", //aka Pin
      "staticVector":"456f4ds54fd65s",
      "statusChanged":1525770790000,
      "status":"FREE",
      "blobCounter":2
    }]

***getDigipassTypes()***

Returns an array of strings of digipass types available in the database.

    digipassService.getDigipassTypes();

Returns an array of strings

    ["DP300","DP700","DPMOB"]

***resetTokenBlobs(serialnumber)***

This method resets all the Digipass application blobs.

    digipassService.resetTokenBlobs("VDS10000120");

***changeStaticPassword(serialnumber, pwd1, pwd2)***

This methods allows you to reset the static/server PIN from a Digipass token. The Digipass token will need to support the server PIN functionality (for example the Digipass GO 1). Generated OTPs will need to be prepended with this server PIN. The parameters pwd1 and pwd2 will need to be identical in order to successfully change the server PIN.

***resetStaticPassword(serialnumber)***

This function is used in combination with a DIGIPASS that can use a static PIN (e.g. DIGIPASS GO 1). The user will have to define his static PIN at the next authentication request. In order to activate this option, the PIN Change Allowed functionality has to be activated.

    digipassService.resetStaticPassword("VDS10000120");

***mdlGenerateLicenseActivationMsg(serialnumber, crontosize, crontoonpaper)***

Generates the first activation message in the process of activation of a multi-device license

    digipassService.mdlGenerateLicenseActivationMsg("VDS10000120",400,false);

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "cronto":"base64StringOfCrontoImageInPNGformat",
     "challenge":"challengeString"
    }

The cronto image can be rendered using an HTML \<img tag with the SRC using base 64.

    <img src="data:image/png;base64,iVBORw0KG....."/>

***mdlGenerateInstanceActivationMsg(serialnumber, challenge, devicecode, crontosize, crontoonpaper)***

Generates the second activation message in the process of a multi device license. The cronto size argument defines the size of the cronto image, in pixels, that is to be created

    digipassService.mdlGenerateInstanceActivationMsg("VDS10000120","theChallenge","deviceID", 400, false);

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "cronto":"base64StringOfCrontoImageInPNGformat",
     "signedMessage":"signedMessageString",
     "instanceNumber":"12346"
    }

The cronto image can be rendered using an HTML \<img tag with the SRC using base 64.

    <img src="data:image/png;base64,iVBORw0KG....."/>

***mdlGenAuthRequest(serialnumber, DigipassMdlSignOptions)***

Generates an authentication request which can be used to authenticate an end user when multi-device license is installed. The serialnumber argument is the serial number of an instance token to generate the authentication request for. The options can be null to use the default signing options or an object.

    digipassService.mdlGenAuthRequest("VDS10000120",null);

This is an example of the options object:

    {"crontoSize":10,
     "crontoOnPaper":false,
     "crontoOnHw":false,
     "msgBase64":true,
     "spacesAsTabs:2,
     "spacesString":null,
     "title":null,
     "vascoAskApproval":true,
     "vascoAskPin":true,
     "vascoShowData":true,
     "vascoShowMac":true,
     "vascoShowWarning":true}

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "cronto":"base64StringOfCrontoImageInPNGformat",
     "signedMessage":"signedMessageString"
    }

The cronto image can be rendered using an HTML \<img tag with the SRC using base 64.

    <img src="data:image/png;base64,iVBORw0KG....."/>

***mdlGenFTRequest(serialnumber, freetext, options)***

Generates a free text request which can be used to authenticate an end user when using a multi-device license.

    digipassService.mdlGenFTRequest("VDS10000120","freeTextString",{options});

This is an example of the options object:

    {"crontoSize":10,
     "crontoOnPaper":false,
     "crontoOnHw":false,
     "msgBase64":true,
     "spacesAsTabs:2,
     "spacesString":null,
     "title":null,
     "vascoAskApproval":true,
     "vascoAskPin":true,
     "vascoShowData":true,
     "vascoShowMac":true,
     "vascoShowWarning":false}

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "cronto":"base64StringOfCrontoImageInPNGformat",
     "signedMessage":"signedMessageString"
    }

The cronto image can be rendered using an HTML \<img tag with the SRC using base 64.

    <img src="data:image/png;base64,iVBORw0KG....."/>

***mdlGenSignRequest(serialnumber, \[{"key":"value"}\], {options})***

Generates a signing request which can be used to authorize a transaction of the end user

    digipassService.mdlGenSignRequest("VDS10000120",[{"key":"value"}, {"key2","value2"}],{options});

This is an example of the options object:

    {"crontoSize":10,
     "crontoOnPaper":false,
     "crontoOnHw":false,
     "msgBase64":true,
     "spacesAsTabs:2,
     "spacesString":null,
     "title":null,
     "vascoAskApproval":true,
     "vascoAskPin":true,
     "vascoShowData":true,
     "vascoShowMac":true,
     "vascoShowWarning":false}

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "cronto":"base64StringOfCrontoImageInPNGformat",
     "signedMessage":"signedMessageString"
    }

The cronto image can be rendered using an HTML \<img tag with the SRC using base 64.

    <img src="data:image/png;base64,iVBORw0KG....."/>

***mdlValidateInstanceActivationMsg(serialnumber, sequencenumber, message, signature, expirationtimeSeconds)***

Validates the response to the instance activation message

    digipassService.mdlValidateInstanceActivationMsg("VDS10000120","1234","generatedActivationMessage","signatureToValidateString",120);

The returning object is as below.

    {"instanceToken":
       {"serialNumber":"VDS10000120",
        "instanceNumber":"12345",
        "applicationName":"APPL1",
        "deviceId":"458f7ds895fe4w4f8edw5f4af",
        "deviceType":"DP110" 
       },
     "statusCode":"203"
    }

***mdlValidateSignature(serialnumber, signedmessage, signature, expirationtime)***

Validates a supplied signature to a signed message which was generated by mdlGenAuthRequest() mdlGenSignRequest()

    digipassService.mdlValidateSignature("VDS10000120","originalSignedMessage","signatureToCheck",120);

The returning object is as below.

    {"instanceToken":
       {"serialNumber":"VDS10000120",
        "instanceNumber":"12345",
        "applicationName":"APPL1",
        "deviceId":"458f7ds895fe4w4f8edw5f4af",
        "deviceType":"DP110" 
       },
     "statusCode":"203"
    }

***generateActivationCode(serialnumber)***

*Generates an activation code for use with single lincense tokens. The response returns an XFAD for online activation.*

    digipassService.generateActivationCode("VDS10000120");

The returning object is as below.

    {"serialNumber":"VDS10000120",
     "activationCode":"45fds4f94dsa65",
     "xerc":"456f4dsa56f4ds"
    }

***blockLicenseInstances(serialnumber, block)***

Blocks a Digipass MDL licences. If block is true then the status is set to revoked. If block is false then status is set to assigned.

    digipassService.blockLicenseInstances("VDS10000120",true);

***blockSingleLicenseInstance(serialnumber, instanceNumber, block)***

Blocks a single instance of a Digipass MDL licence. If block is true then the status is set to revoked. If block is false then status is set to assigned.

    digipassService.blockSingleLicenseInstance("VDS10000120",1,true);

**blockTokenApp** ***(serialnumber, app, block)***

Blocks a single application of a single token. If block is true then the status is set to revoked. If block is false then status is set to assigned.

    digipassService.blockTokenApp("VDS10000120","APPL1",true);

***getLicense(serialnumber)***

Get a single license by it's serial number. Returns a DigipassLicense object

    digipassService.getLicense("VDS10000120");

    {serialNumber:"VDS10000120",
     "activationType":"online",
      "masterAppName":"ACTIV APP",
      "masterAppAMode":"MA",
      "masterAppBlob":"456f4dsa56f4ds",
      "activationVector":"456f4d5sf4d5s6ds",
      "payloadKeyBlob":"56f4dsa56f4d6",
      "status":PENDING,
      "messageVector":"1",
      "staticVector:"1",
      "tokens":[arrayOfTokenObjectsBeingActivatedInstances]
    }

***getInstance(serialnumber, instanceNumber)***

Get a single token instance for a specific MDL license by the serial number of the license and the instance number of the token instance. Returns a DigipassToken object

    digipassService.getInstance("VDS10000120",1);

    {"serialNumber":"VDS10000120",
      "dpMode":"CR", //possible values are CR, RO, SG and MM
      "dpBlob":"12f1ds231f23ds, //base64 encoded string of the blob
      "dpType":"DP300",
      "application":"APPL1",
      "sharedSecret":"1346", //aka Pin
      "staticVector":"456f4ds54fd65s",
      "statusChanged":1525770790000,
      "status":"ASSIGNED",
      "blobCounter":2,
      "instanceNumber":1
    }

## QR Service

Invoking QR Service in the scripts:

The purpose of the QR service is to create a QR code based on an input string.

Retrieving the service :

    var qrService = tb.getService("QRService");

Functions:

***generateQrBase64(input,size)***

Generates a QR code based on the string input. The optional size parameter specifies the size of the QR image. The default size is 125 pixels. The output is base64 encoded PNG image with the specified size.

    qrService.generateQrBase64("http://mysite/context", 250);

## Mobile Authenticator Service

This is a set of properties that have to be set on the service that define an issuer. Once these properties are set and the service is started, you cannot effectively change these properties.

* url

* mobileTimeoutInSeconds

* transactionTimeoutInSeconds

* issuerName

* otpLength

* algorithm

* qrCodeSizeInPixels

Properties:

These are other properties that have to be set on the service.  

|          Property           |                                  Description                                  |
|-----------------------------|-------------------------------------------------------------------------------|
| type                        | The type of the authenticator service. The type PULLING is already available. |
| issuerAndTokenStoreJdbcUrl  | The jdbc url for the issuerAndTokenStore                                      |
| issuerAndTokenStoreUsername | The username for the issuerAndTokenStore                                      |
| issuerAndTokenStorePassword | The password for the issuerAndTokenStore                                      |
| requestStoreJdbcUrl         | The jdbc url for the requestStore                                             |
| requestStoreUsername        | The username for the requestStore                                             |
| requestStorePassword        | The password for the requestStore                                             |

Functions:

**pollStatus(actionUID) -\> AuthenticationRequest**

Fetches the authentication request linked to that actionUID. If there is no authentication request found, you will get null.

**fetchAuthenticationRequest(deviceUID) -\> AuthenticationRequest**

Fetches the oldest new authentication request linked to that deviceUID. If there is no authentication request found, you will get null.

**requestAuthentication(issuer, username, actionType, description) -\> actionUID**

Create an authentication request. actionType has to be AUTHENTICATE.

**authenticate(message, actionUID) -\> boolean**

Confirm the request linked to that actionUID. Returns true if a request was found for that actionUID, otherwise returns false.

**cancel(actionUID) -\> boolean**

Cancel the request linked to that actionUID. Returns true if a request was found for that actionUID, otherwise returns false.

**register(issuer, username) -\> qr code base64**

**registrationCallback(identifier, deviceUID)** **-\> boolean**

How to use:

First, a user has to register. You can use the register function to accomplish that. The mobile app will do a callback call to the url (defined in issuer properties) appended with "/register/callback". That callback request will contain the parameters "deviceUID" and "tbid" in the body, where "tbid" has as value the identifier. These parameters can be used to finalize the registration by calling the registrationCallback function.

When a user is registered that user can try to log in. We can start a login procedure by calling the requestAuthentication function. We can poll for the authentication request with the actionUID. The device polls for the authentication request with the deviceUID to the url (defined in issuer properties) appended with "/poll/{deviceUID}". The response from the device will arrive in the url (defined in issuer properties) appended with "/tokenresponse". The response consists of the properties "status", "message" and "actionUID" in the response body. If the status is not equal to "OK" (case is ignored), the login is cancelled, else the login succeeds.

Data:

**AuthenticationRequest**

The authentication request contains the following fields:

* issuer

* username

* actionType: For now actionType is always AUTHENTICATE

* deviceUID: UID of the device linked to this authentication request

* actionUID: UID of the request

* description

* authenticationStatus: The authenticationStatus can be any of the following (with accompanying value in the database): NEW(0), VALIDATED(1), CANCELLED(2), OTP_FAILED(3), TIMED_OUT(4), NOT_PRESENT(5)

## InternalApiPublicService

io.trustbuilder.andromeda.internalapi.InternalApiPublicService

This service has a method available to make direct API calls to IDHub. This avoid the need to use a HTTP Adapter to make these calls. The method has one mandatory parameter and one optional parameter.

.callInternalApi( request )

.callInternalApi( request, userName )

    var loggingFormat = { name: 'frominternal', format: 'teststee' };
    var request = {
      method: 'POST',
      path: '/admin/api/v1/gateway/loggingformats', 
      headers: {"Content-Type" : "application/json"},
      encoding: 'utf-8',
      body: JSON.stringify(loggingFormat)
    };
    var internalCall = tb.getService('internalCall');
    var response = internalCall.callInternalApi(request); // session inherit

    var request = {
      method: 'GET',
      path: '/admin/api/v1/'
    };
    var internalCall = tb.getService('internalCall');
    var userName = 'IDHUB_ADMINISTRATOR';
    var response = internalCall.callInternalApi(request, userName); // impersonate

## Mobile Authenticator ScriptService

Service Description:

Service Class : io.trustbuilder.andromeda.protocols.mobile.MobileAuthenticatorScriptService

Functions :

(all functions will return null if a mobile idp is not properly configured)

**getServer()**

Returns a java Server object (class : io.trustbuilder.andromeda.protocols.mobile.client.Server)

It has the following getters, returning the Mobile IDP server properties :

It has setters too, but they won't affect the actual server.

* getAccountCount()

<!-- -->

* getAppandroid()

<!-- -->

* getAppios()

<!-- -->

* getAppname()

<!-- -->

* getAppurl()

<!-- -->

* getLastLogin()

<!-- -->

* getLogo()

<!-- -->

* getOwner()

<!-- -->

* getPingTime()

<!-- -->

* getPinTimeout()

<!-- -->

* getPinTransTimeout()

<!-- -->

* getServerFlags()

<!-- -->

* getServerid()

<!-- -->

* getServerName()

<!-- -->

* getServerpk()

<!-- -->

* getSiteurl()

<!-- -->

* getWsurl()

**register()**

Returns a String which is the base64 encoded PNG of the registration QR for the current user.

This method will fail if no user is authenticated as principal

**getQR()**

Returns a String which is the base64 encoded PNG of a login QR.

**getVash()**

Returns a String which is the base64 encoded PNG of the server Vash.

**provoke()**

Attempts to send a push notification to the user.

This will use the userid based on the login hint cookie handed out by idhub.

Returns a boolean indicating success or failure.

**provoke(userid)**

userid: String containing the userid as known on the Mobile IDP server.

Returns a boolean indicating success or failure.

**getStatus()**

Returns a java LoginStatus object (class : io.trustbuilder.andromeda.protocols.mobile.client.LoginStatus)

It has the following getters, returning the login status properties :

It has setters too, but they won't affect the actual login status.

* getAccountid()

<!-- -->

* getHsid()

<!-- -->

* getLoginqrdata()

<!-- -->

* getPk()

<!-- -->

* getUserid()

<!-- -->

* isCanprovoke()

<!-- -->

* isLoggedin()

---
language: "en"
---
# Client Credentials grant

This section deals with the OAuth 2 client credentials grant - a flow designed for machine-to-machine communication, e.g. a client app in an unsafe environment calling an API behind an API gateway, without any user context.

The more common OAuth2 flows, such as the authorization code grant, work within a user's context after the user has been authenticated. In those flows, a client app can "borrow" some of the user's privileges when calling an API. Without a user's context, the client app cannot borrow the user's privileges and needs to obtain an access token using the OAuth 2 client credentials grant.

There are a number of situations in which client apps need to operate as themselves rather than on behalf of a user. Even if a user happens to be signed in at that time of access, a client app might exercise privileges that the user does not have.

## API Key

A traditional way of working is to give the client app an "API Key". The best thing about an API key is its simplicity. You merely log in to a service, find your API key (often in the settings screen), and copy it to use in an application, test in the browser, or use with one of these API request tools. Along with the simplicity, though, comes both security and user experience downsides to API keys.

An API key, however, typically gives full access to every operation an API can perform, including writing new data or deleting existing data. If you use the same API key in multiple apps, a broken app could destroy your users' data without an easy way to stop just that one app. Some apps let users generate new API keys, or even have multiple API keys with the option to revoke one that may have gone into the wrong hands. The ability to change an API key limits the security downsides.

Many API keys are sent in the query string as part of the URL, which makes it easier to discover for someone who should not have access to it. A better option is to put the API key in the Authorization header. In fact, that's the proposed standard: `Authorization: apikey 1234567890abcdef`. Yet, in practice, API Keys show up in all sorts of places: Authorization Header, Basic Auth, Body Data, Custom Header, or Query String.

API keys make sense when the users of an API are only developers. However, as developers created tools for themselves, they started sharing them with others. End users often find themselves fumbling through API documentation, registration, and settings just to find the API key that a tool needs, often without even knowing what an API is. This opens the floodgates and exposes the API and all data it has access to.

So, API keys may be useful in very closed environments where developers build internal applications that don't need more access than shared data. In open environments where microservcies are develoopped independepntly of each other and are exposed to client apps, the API Key simply represents too high a security risk.

## OAuth 2 JWT access tokens

Enter the OAuth 2 client credentials grant. TrustBuilder enables a client app to obtain an access token and take it along when calling a protected API, the so-called Relying Party. Before issuing the access token to the client app, however, TrustBuilder checks the policy whether it should indeed issue the token with the requested privileges. The flows is as follows:  
![image-20230113-101044.png](https://docs.trustbuilder.com/__attachments/a_1ec51a67a7d68a35d89353a61b2a11a58539e4140bdeff553574adf30563120c/image-20230113-101044.png?cb=6e79c118ecebd0b8932c37c8bd44210a)

The 'TB.io AS' is the OAuth Authorization Server of the TrustBuilder platform. The 'RP' is the OAuth Relying Party, i.e. the intended API endpoint referred to by \<audience\> \& \<scope\>. As long as the access token has not expired, and, the API endpoint is the same (read: \<audience\> \& \<scope\> are the same), the access token can be reused (hence the loop in the diagram).

### Configuration

First, ensure your client app can be authenticated. You can obtain credentials in the form of`client_id`/`client_secret` from TrustBuilder.

The use of a symmetric `client_secret`, however, exposes it every time an access token is requested and is also present and thus vulnerable in the code of the client app. A better alternative is passing on a token that is signed with the private key of the client app. This is standardized as the so-called `private_key_jwt,` see below '*Token-based client authentication'*.

#### Access Token Request

The client app requests a token by contacting the token endpoint directly with the Client Credentials grant. The request parameters are typically:

    {
      "grant_type": "client_credentials",
      "client_id": "<client_id of the client app>",
      "client_secret": "<shared client_secret>",
      "scope": "<intended API endpoint>"
    }

Remember that, as opposed to more common OAuth 2 grants, the client credentials grant only relies on the client's own identity rather than requesting authorization through a user. So, from the OAuth 2 standpoint, the flow described here might just as well occur in a command-line tool, a long-running process, or in general, any kind of application executed in a context where distribution and protection of client credentials are possible.

The request is a customary HTTP POST, carrying the credentials of the client app, the `grant_type` set to client_credentials, the requested `scope`, in a given `aud` (audience) and a `state` value to protect against cross-site request forgery. The credentials can be a `client_id`/`client_secret` or can be token-based with a `private_key_jwt` (see below).

The `scope` parameter indicates the type of operation the client app wishes to execute, e.g. `"get:hr_record"`.

The `aud` parameter indicates in what realm the client is requesting access. This information is crucial for an API gateway to distinguish between different microservices. Moreover, it is critical to distinguish between different tenants in a multi-tenant SaaS environment.

#### Token Response

The token endpoint response returns the requested access token and may add specific claims to the access token. These claims may indicate certain fine-grained attributes of the client app, such as its `persona` or `tenant` in the TrustBuilder context. Note that there is no id token, given that the grant doesn't entail user identity in any capacity.

Important note: the mechanism should be used in an efficient way taking advantage of the fact that an access token can be reused until it expires. Once a client app requests and obtains an access token, it should keep it around in a safe place for the duration of its useful lifetime and re-use it whenever it needs to call the same API. Requesting a new access token from TrustBuilder every time again and again can be a costly anti-pattern, possibly draining performance and availability.

A TrustBuilder bearer access token is encrypted (e.g. `VCJ943eyJzdWIiOiIxMjM...wIiwibmFtZSI6IkpvaG4`). A decoded access token may look like:

    {
      "iss": "https://<your domain>/",
      "aud": "<your domain>",
      "client_id": "<client_id of the client app>",
      "iat": 1590440782,
      "exp": 1590450969,
      "scope": "<intended API endpoint>",
      "tenant": "<tenant-id>"
    }

The `scope` claim will only contain the scopes that (1) have been requested and (2) that can be granted to the user after evaluating the policy for the requested API endpoint. This means that less scopes may be returned in case the user does not qualify for all scopes given the user profile and the user session.

Since TrustBuilder 11.2.18, the custom claim `principal_type` has been added to the access token to differentiate between clients from users. In client credential grant, the `principal_type` value is set to `client` (the default value is `user`).

#### Calling the API

The call to the API occurs as usual with the access token in the authorization header:

    authorization: Bearer VCJ943eyJzdWIiOiIxMjM...wIiwibmFtZSI6IkpvaG4

The call happens without any dependency on how the client obtained the access token.

The API Gateway can first check whether the JWT access token is issued by TrustBuilder (by verifying its signature) and is issued for the client app that is doing the call.

The API Gateway can then orchestrate the call to the correct API given the `aud` and `scope` and can verify whether the `scope` corresponds to the API endpoint.

If the connection between the API Gateway and the API is sufficiently trusted (e.g. within the same environment), the API itself can then blindly accept the call. Optionally, it can further exercise fine-grained authorization using the claims that TrustBuilder has added to the access token, such as `persona`.

#### Token-based client authentication

The 'client credentials' to authenticate the client app and can be symmetric with `client_id` / `client_secret` or be token-based using an asymmetric key pair, in the form of a `private_key_jwt`. The token-based authentication has been standardized by <https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication>. The `private_key_jwt` is basically a token signed by the client app using its private key.

When configuring the client app, its public key must be registered at TrustBuilder when registering the `client_id`. The public key can be represented as follows:

    {
      "keys": [{
        "kty": "RSA",
        "alg": "RS256",
        "use": "sig",
        "kid": "<the public key identifier>",
        "n": "<the RSA modulus>",
        "e": "<the RSA exponent>"
      }]
    }

When the client app requests an access token and authenticates itself, the `private_key_jwt` is constructed as follows:

    {
      "iss": "<client_id>",
      "sub": "<client_id>",
      "aud": "<trustbuilder audience>",
      "exp": "<expiration time to represent a short lived jwt>",
      "jti": "<unique identifier to avoid replay"
    }

The client app then adds this `private_key_jwt` to the request body (in lieu of the `client_id` and `client_secret` in the authorization header). The complete request body may look like:

    grant_type=client_credentials
    &scope=<requested scope>
    &client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
    &client_assertion=<the actual private_key_jwt>

## References

<https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication>

<https://tools.ietf.org/html/rfc7521>

<https://tools.ietf.org/html/rfc7523#section-2.2>

---
language: "en"
---
# Client-level access

* [AZN Concepts](https://docs.trustbuilder.com/tb-io/azn-concepts.md)
* [AZN Use cases](https://docs.trustbuilder.com/tb-io/azn-use-cases.md)
* [AZN Configuring the authorization service](https://docs.trustbuilder.com/tb-io/azn-configuring-the-authorization-service.md)
* [AZN Script Interface](https://docs.trustbuilder.com/tb-io/azn-script-interface.md)
* [AZN Policies in TrustBuilder Administrator](https://docs.trustbuilder.com/tb-io/azn-policies-in-trustbuilder-administrator.md)

---
language: "en"
---
# Components Tab

Components were introduced in TrustBuilder 8.0. They can be seen as a complete sub-configuration packaging together adapters, services, workflows and scripts into one file that can be simply distributed, configured and documented. The idea is to package a complete process into one place that can be distributed and shared easily.

Components are supplied as .tbc files and are uploaded into the TrustBuilder Administrator and configured therein.

## Role to Access

To access the Components functionality in the TrustBuilder Administrator the TBAGComponent role is needed.

### Uploading a New Component (.tbc) File

On the components tab click the **Upload and Import Component** button.  
![image-20230504-080449.png](https://docs.trustbuilder.com/__attachments/a_df05daaa57a8c2d4c63ebbc458f9f62392d98cdc5bf33cef051242dcd68ee0d0/image-20230504-080449.png?cb=c85e0f39003282de89396b542fc667a0)

This will present an Upload Component form, complete the fields and click the **Upload** button:  

|     Form Field      |                                Description                                | Required |
|---------------------|---------------------------------------------------------------------------|----------|
| Component ID        | The ID that will be given to the component                                | yes      |
| Description         | A text description to be given to this component for easy identification. | no       |
| .tbc Component File | The physical component file to be uploaded from this computer.            | yes      |

![image-20230504-080458.png](https://docs.trustbuilder.com/__attachments/a_62c59e0630799b9ed318db33cbd6eecf31c214d9659cfacc671c7592f1801243/image-20230504-080458.png?cb=e24ab9d77ec6926eb6b8ad08e9610833)

If the file is uploaded successfully then a new row is added to the component table list. This new component is **not** yet configured. This means that the component is not referenced in the configuration file and will not be exported when the configuration is exported.  
![image-20230504-080505.png](https://docs.trustbuilder.com/__attachments/a_f763d3b2c3c9e28fc182d1b2426b69e14b78cb200b0ae28532c6bf3e85fdc49f/image-20230504-080505.png?cb=b287c4991f9a5a7d0bffac5700414d0c)

There are two buttons available to a new component **Read Me** which will display the read me file in the component which documents it's use and how it should be configured. This is displayed in a new window. The **Configure** button opens a form to configure the properties of the component.

### Configuring a Component

A component is not usable until it has been configured. It cannot be referenced from a workflow or a policy and it is not exported when the configuration is exported. To configure a component click the **Configure** button in the relevant row this will open a form.  
![image-20230504-080514.png](https://docs.trustbuilder.com/__attachments/a_ab62f218b410231037187d709efa831fca94486369c32a5e942126f5d2ab0510/image-20230504-080514.png?cb=faeaf9138893a42b359398d574d90ffd)

Beside each label is a description of the data that should be provided. This serves as in-line documentation.  
![image-20230504-080525.png](https://docs.trustbuilder.com/__attachments/a_c9eee7b7ebf9e31c1d9dcd6f1af7eadd8e01afcc02f588499bc09b98e184c59f/image-20230504-080525.png?cb=26eae288c77a4718cb0f7749bfb5f531)

Each input can also be overridden. This means that a value is not specified for this component field and that property is added to the override properties file. When exporting the value is entered for each server in a form so that different values can be provided for different servers but the same component and configuration can be used. For more information of overriding values refer to the export chapter. To override a value just check the override check box.  
![image-20230504-080533.png](https://docs.trustbuilder.com/__attachments/a_a2acbaef52a33da09241922f53607083f3a3ec0ee06cb7e1d6e45055bdae3e2d/image-20230504-080533.png?cb=b51e858afd9004277ffbc7e9d13fa107)

When the form is completed and successfully submitted the component row will show as configured. This enables the following.

* The component is now included in the main configuration file and will be exported when the configuration is exported.

* The component is now available for use within workflows from a component activity.

* The component can be referenced from a policy resource.

The relevant row in the component table list will be highlighted a different colour and the resource field is populated with the resource entry that is used in the main configuration file.

There is also a new check box available: Hidden. The hidden check box sets an attribute in the main configuration file. When enabled this component cannot be accessed directly via a URL it can only be referenced from within a workflow. If the component is not hidden it can be accessed directly via a URL using the component ID as a reference in the URL.

### De-Configuring a Component

To de-configure a component, this means to remove it from the main configuration so that it will not be exported and also not accessible to workflows and policies, select the checkbox to the left of the relevant component row and click the **De-configure Selected** button. The values for the properties that have been provided are also discarded.  
![image-20230504-080541.png](https://docs.trustbuilder.com/__attachments/a_2cae8ffdebe59f6f16a736329405c0d278f6a6b440c71bc002e0d21a808560d1/image-20230504-080541.png?cb=f78658de9682c5dd80009165265fed77)

### Updating a Component

A component that has already been imported to a configuration can be updated with a new .tbc file. To do this click the **Update** button in the corresponding row of the component to be updated.  
![image-20230504-080558.png](https://docs.trustbuilder.com/__attachments/a_b12030aebb70bd5d50310413912ecd8553169bd1e07220062baf33214434643d/image-20230504-080558.png?cb=f31dcbb43dad674b7227259c44822a71)

When the **Update** button is clicked the upload dialog is opened. The id of the component cannot be changed only the new .tbc file can be selected. Once a file is selected click the **Upload** button.  
![image-20230504-080630.png](https://docs.trustbuilder.com/__attachments/a_a7bca4c5f84ebd1f44355876b9d2c2c27d520d94592f2f18ed6850b4dde58027/image-20230504-080630.png?cb=320a2fe451deaadc6626d908f69f2229)

If the new .tbc file is uploaded successfully all the details for the component are updated. Any values that have been provided to configure the component are preserved and any new details, such as version number, are updated.

### Exporting the Component Package

To export a configured component use the main configuration Export buttons. To export just the package, this means just the physical .tbc file not any configuration, check the box to the left of the relevant component row and click the **Export Selected Packages** button. More than one package can be exported at one time.

### Deleting a Component

To delete a component check the check box to the left of the relevant component row and click the **Delete Selected** button. This will remove the component from the configuration and remove the .tbc file.

### Components and workflows

The TrustBuilder config **always** needs 1 workflow together with the component. If no workflow exists next to your component the config will not validate.

---
language: "en"
---
# Config

* [Services](https://docs.trustbuilder.com/tb-io/services-list.md)
* [Introduction](https://docs.trustbuilder.com/tb-io/introduction.md)
* [Endpoints](https://docs.trustbuilder.com/tb-io/endpoints.md)
* [Workflows](https://docs.trustbuilder.com/tb-io/workflows-1.md)
* [Logging](https://docs.trustbuilder.com/tb-io/logging.md)

---
language: "en"
---
# Configuration Adapters Tab

The adapters tab is where adapters can be added, edited and deleted for a single configuration.

## Add Adapter

Add a new adapter by clicking the **Add Adapter** button at the top of the adapters tab.

This will display a form. Select the type of adapter that is to be created from the select list.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/406/972/original/94cd937f-1ed0-4c88-abdb-dada7fbb5acb.png?1521061108](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/406/972/original/94cd937f-1ed0-4c88-abdb-dada7fbb5acb.png?1521061108)

Then the appropriate form will be displayed.

Complete the form. Each label of the form has a question mark icon. Move the mouse over the question mark for details of what data is expected for each field.

Note that fields marked with an asterisk (\*\*) are required and those marked (numeric) will only accept numeric values.

Once the form is complete click the **Submit Form and Create Adapter** button. The form will be validated before submission and any issues highlighted.  
![https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/406/973/original/0b4c35e8-b359-4b39-957b-18a089a77e9a.png?1521061109](https://s3.amazonaws.com/screensteps_live/image_assets/assets/001/406/973/original/0b4c35e8-b359-4b39-957b-18a089a77e9a.png?1521061109)

Any password fields will be encrypted locally within TB.Connect so no passwords are stored or transmitted over the wire in plain text. On export TB.Connect will determine if the passwords need to be encrypted using a local master password if one has been configured for each specific TB server. For details of master passwords refer to the hardening and password encryption chapters.

### Override

Beside each label within an adapter form is an override checkbox. If this box is checked it means that the value can be replaced when the configuration is exported.

For example the JDBC adapter has an entry for DataSource. This is the name of a datasource that is configured in the application server.

This datasource name may be different in the development and test environments but this same configuration is to be used in both environments.

In this instance checking override will allow the datasource name to be overridden by a value set in the config-override.properties file.

On export the configuration is checked to see if any data is to be overridden and a form is provided to enter the value for each TB Server that is to be exported to.

So for the development TB Server a value of jdbc/devDS can be entered and for the test TB Server a value of jdbc/testDS can be entered.

These values will then be written to the config-override.properties file when the export is made to each server.

When the engine is started it will use the value defined in the config-override.properties file.

Any value that is entered in the DataSource field will be ignored when the engine loads the configuration.  
![image-20230505-102401.png](https://docs.trustbuilder.com/__attachments/a_9fadf2b56b05742dd80b137694b34dc296b9ea692721aca49913fead2fa3d73f/image-20230505-102401.png?cb=92dc672fad32fe3f24afc5d5813a1e90)

### Edit Adapter

To edit an adapter click the **Edit** button beside the adapter in the list.

The same form that is displayed when adding will be presented with the values populated.  
![image-20230505-102408.png](https://docs.trustbuilder.com/__attachments/a_bc75d11903cb30c0ab47b0908331a0b138dabaecad688b7fa88ee200e29b00ea/image-20230505-102408.png?cb=119dffc5f87de0f2d04595d8c9c89bd4)

### View Adapter

To view the entry that will be made in the configuration for a specific adapter click the adapter name to reveal the XML. Click it again to hide it.  
![image-20230505-102420.png](https://docs.trustbuilder.com/__attachments/a_447ab05b84acd8be241a3568c49db184486fcdf24bea17d0c37ccde971a1c1c6/image-20230505-102420.png?cb=f4f59cef8de5ae20313d8c8176e0a5f1)

### Delete Adapter

To delete an adapter click the Delete button beside the adapter in the list.

Deletion of an adapter is final, there is no undo.

---
language: "en"
---
# Configuring notifications

You can configure the notifications sent from TrustBuilder. In the Admin Portal, go to **Notifications Service** \> **Communication**.  
We are progressively reworking the interface and user experience of our platforms. You may encounter difficulties in using features that are not fully operational. We appreciate your patience as we strive to provide an enhanced experience tailored to your needs.

* ![check mark](https://docs.trustbuilder.com/__attachments/a_8758dc924e244d1571b1120e4c5a0acab0bcc3b262141e2ebe4ef61695db3881/atlassian-check_mark?cb=a10212e1c1021c5194f7535b6843f955) **SUPPORTED**

  * E-mail → use your own e-mail server

  * Workflow → use a custom workflow sending notifications

* ![cross mark](https://docs.trustbuilder.com/__attachments/a_90c8aa1de764905484edda76fe2783d9f6be7a753bcc5091ccf894d6be1042db/atlassian-cross_mark?cb=a9c671cfc7809253be52d640dbbf1019) **CURRENTLY NOT SUPPORTED**

  * E-mail → use TrustBuilder e-mail server

  * E-mail → use TrustBuilder e-mail server with your own e-mail address domain

## Overview

You can configure notifications according to the action performed.  

|     **Action**      |                                                                                                                                                                                                        **Description**                                                                                                                                                                                                        |
|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Change Password** | Configure notifications received when: * password is set or changed on Admin Portal provision page * user changes their own password on password change page User receives a notification according to predefined e-mail template. This notification type is disabled by default. Note that notification is NOT triggered when: * user registers themselves for the first time (with a password) * user resets their password |
| **Provision User**  | Configure notifications for user profile activation. User receives a notification according to predefined template.                                                                                                                                                                                                                                                                                                           |
| **Reset Password**  | Configure password reset notifications. User receives a notification according to predefined template.                                                                                                                                                                                                                                                                                                                        |
| **Verify e-mail**   | Configure e-mails for e-mail verification. User receives a notification according to predefined e-mail template.                                                                                                                                                                                                                                                                                                              |

For each action, you should select:

* **Channel**: the notifications will be sent through the selected channel.

  * E-mail → the notification channel will be the e-mail. The SMTP should needs to be enabled and properly configured in the e-mail tab.

  * Workflow → the notifications will be sent based on a workflow. The workflow has to be selected in the Workflow tab.

* **Template** : the selected template will be used to notify the users.

  To consult the default templates or create new ones, go to Settings \> Edit Templates. Note that default templates are not editable. You can use them as-is or you can use them as base template for your new template.

* **Attribute**: the value of the selected attribute defines where the notification will be delivered to send the notification.

## Configuration to send e-mail notifications (SMTP server)

You can configure TrustBuilder to use your own SMTP server to send notifications for the actions listed above.

1. In the Admin Portal, go to **Notifications Service** \> **Communication** \> **E-mail** tab.

2. Fill in the form with your SMTP server information:

   * **From** **\***→ the value for the FROM field of the e-mails to be sent- Make sure your SMTP allows this e-mail address as a sender.

   * **Host** **\***→ The URL or IP address of your SMTP Server

   * **Host certificate** → Select a trust certificate from the trust store.

     *To add a trust certificate, go to Settings \> Certificates \> Trust Store tab \>* ***+*** *Import Trust Certificate.*

   * **Port** **\***→ The port used by the SMTP to connect to the server.

     The default is 587 which is a standard SMTP port for secure communications (support TLS natively and STARTTLS)

   * **User** → The SMTP username

   * **Password** → The SMTP password

3. Check the box to **activate e-mail communication** at the top of the form.

   ![image-20240208-131852.png](https://docs.trustbuilder.com/__attachments/a_c88d501e17183f3e69d98855e96d58a9f60ec85c493723958eef3de783052fab/image-20240208-131852.png?cb=fb427ab352d3e680012caafb79724c5a)
4. If you check the "**Verify**" checkbox then:

   * Setting or updating a value in an e-mail field triggers a verification e-mail being sent to that e-mail address.

   * E-mail are only sent to e-mail addresses that are verified (and skipped for the unverified ones), except for the verification action.

5. Click on **Save**.

## Customize e-mail content

To create your own e-mail template:

1. in the Admin Portal, go to **Settings** \> **Edit Templates** \> **+ Add New Template**.

2. Fill in the fields:

   * **Name** **\*** → Enter a name for your template.

   * **Base Template** → (optional) Select a default template to use it as a base content of your template.

   * **Type** **\*** → Select the type of template based on the action it will be associated (refer to the actions listed above)

     * CHANGE_PASSWORD for "Change Password" action

     * RESET_PASSWORD for "Reset Password" action

     * VERIFY_RECIPIENT for "Verify e-mail" action

     * RESET_PASSWORD for "Provision user" action

   * **Channel** **\*** → Select "e-mail"

   * **Default Local** **\*** → Select the default language

3. Enter the e-mail content. The e-mail should be written in HTML format.

       <html>
           <head>
           </head>
           <body>
               <h1>My e-mail title</h1>
               My e-mail content "{{my_variable}}"
           </body>
       </html>

   * You can press CTRL+ SPACE to display code completion.

   * Variables should be inserted as `"{{my_variable}}"`

   * `"{{url}}"` → the URL that is specific to the user and the action to perform

   * `"{{recipient}}"` → the recipient e-mail address

   * `"{{password}}"` → the password value

---
language: "en"
---
# ConsentCleanupService

|    **Name**    |                       ConsentCleanupService                       |
| **Class Path** | `io.trustbuilder.andromeda.protocols.oauth.ConsentCleanupService` |
|  **Versions**  |                               10 11                               |
|----------------|-------------------------------------------------------------------|

* Implements: `io.trustbuilder.andromeda.util.PublicBean`

## Overview

The `ConsentCleanupService` provides maintenance operations for the CONSENT data, including removing expired and unlinked consents, optimizing table statistics, and bulk-removing consents based on filtering criteria.

## Available Functions

`cleanExpiredConsents(): int`

This method cleans consents which are expired.

* **Returns**:

  * `int`: number of deleted consents.

*** ** * ** ***

`cleanUnlinkedConsents(Long batchSize): long`

This method checks OAuth tokens and finds the linked consent IDs, then removes unlinked consents (not used by any OAuth token) in iterations until there is no unlinked consent.

* **Parameters:**

  * `batchSize`(long): Max size of consents deleted in each iteration.

* **Returns:**

  * `long`: number of deleted consents.

*** ** * ** ***

`optimizeConsentTable(): void`

Requests the SQL server to analyze and update CONSENT table statistics and reclaims empty space.

* **Returns:**

  * `void`

*TrustBuilder v.11 - Release 2026.4*

The `optimizeConsentTable()` method is disabled. Contact TrustBuilder Support for any required consent table optimization.

*** ** * ** ***

`removeConsents(Long createdAfterMilliseconds, Long createdBeforeMilliseconds, boolean includeClientSPs, boolean excludeClientSPs, List<Integer> spIds, boolean includeAuthenticationMethods, boolean excludeAuthenticationMethods, List<Integer> authenticationMethodIds, long batchSize, Long limit): long`

Deletes rows in the CONSENT table with respect to the given parameters. Only `createdAfterMilliseconds`, `createdBeforeMilliseconds`, and `limit` can be null.

* **Parameters:**

  * `createdAfterMilliseconds` (`Long`): EPOCH time in milliseconds (JS compatible) where consents created after this time will be deleted. If null, begins from EPOCH.

  * `createdBeforeMilliseconds`(`Long)`: EPOCH time in milliseconds (JS compatible) where consents created before this time will be deleted. If null, uses NOW.

  * `includeClientSPs`(`boolean`): Deletes consents having SP IDs given in `spIds` if true.

  * `excludeClientSPs`(`boolean`): Deletes consents having SP IDs NOT given in `spIds` if true.

  * `spIds`(`List<Integer>`): ID list of SPs where the consents will be deleted. If `includeClientSPs` and `excludeClientSPs` are both true or both false, `spIds` will not be used as a condition.

  * `includeAuthenticationMethods`(`boolean`): Deletes consents having Authentication Method IDs given in this parameter if true.

  * `excludeAuthenticationMethods`(`boolean`): Deletes consents having Authentication Method IDs NOT given in this parameter if true.

  * `authenticationMethodIds`(`List<Integer>`): ID list of Authentication Methods where the consents will be deleted. If `includeAuthenticationMethods` and `excludeAuthenticationMethods` are both true or both false then `authenticationMethodIds` will not be used as a condition since inclusion or exclusion cannot be determined.

  * `batchSize`(`long`): Max number of consents to be deleted in each iteration.

  * `limit`(`Long`): Max total number of consents to be deleted. If null, uses `Long.MAX_VALUE`.

* **Returns:**

  * `long`: number of deleted consents.

*** ** * ** ***

## Summary

The ConsentCleanupService supports:

* Cleaning expired consents.

* Removing unlinked consents (with optional batch size control).

* Bulk removal of consents using time windows, SP filters, authentication method filters, and batching/limits.

---
language: "en"
---
# Core and Administrator Relationship

The relationship between the TrustBuilder Administrator (TBA) and TrustBuilder (TB) is made via the management port. For every export, import and restart operations are called upon via this socket. The port is configured both in the server via the management port input:  
![image-20230425-134403.png](https://docs.trustbuilder.com/__attachments/a_c90923fa6afe7288c4ffaeddf4358568029e46a2301214d3a6940d3d98774c7c/image-20230425-134403.png?cb=e6064c1008859c67ac25aafe3fba3643)

There is also the option to download and upload a complete configuration as a zip file to manually distribute to other TBA installations or for manual export.  
![image-20230425-134417.png](https://docs.trustbuilder.com/__attachments/a_f892796be079161f95ac82bb7fddc5b39ba7da653a174986dcfd5a037b67545a/image-20230425-134417.png?cb=5b167855bf48316b63acabd3abb05aa2)

These are the main elements that can be controlled by the TrustBuilder Administrator:

* servers

* configurations

* workflows

* services

* workflow tests

* scripts

* library files

* templates

* properties

* logging

* authorization policies

* security stores

All of these items can be edited and then exported and deployed to installed TrustBuilder servers.

TrustBuilder servers can be re-started directly from within TBA.  
![image-20230425-135507.png](https://docs.trustbuilder.com/__attachments/a_d96cd4102a903043407f1d83d968fad7f7644fa8020e6231ca65d1e5d12ec725/image-20230425-135507.png?cb=eaf25e2d4c07d7c5f5342171b598e060)

## Servers

An TrustBuilder server is a representation of an installed TrustBuilder instance. The main purpose of a server is to define the location of the server and how to connect to that server to import and export. One server has one configuration, one or many workflows and none or many scripts, templates and services.

### Configurations

Configurations hold everything needed by the TrustBuilder engine to process an incoming request. This includes: license, workflows, adapters, security and services. A description can also be set. Also the port number that is used for administration purposes such as export, import and restart of the engine. Each configuration can be related to more than one server. When exporting a complete configuration it is exported to all the servers that it is related to. There can be multiple workflows for one configuration. To add/edit/delete workflows related to a configuration first select the configuration from the home page.  
**Server and Configuration Relationships**

A configuration can be related to more than one server. This allows for the configuration to be re-used over multiple installations of TrustBuilder.

### Workflows

Workflows define the steps that an incoming request takes when processed by the TrustBuilder engine.  
Each configuration must have one or more workflow(s).

A workflow is comprised of a number of activities or steps. Each activity has a single purpose. There are several types of activity:  

| Activity Name |                                          Description                                          |
|---------------|-----------------------------------------------------------------------------------------------|
| Initial State | The start of the workflow. There must be, and can only be, one initial state in one workflow. |
| Condition     | A logical condition or if/else if/else or case statement                                      |
| Script        | Run a function from a Javascript                                                              |
| Adapter       | Make a call to a configured adapter                                                           |
| Workflow      | Make a call to a sub-workflow from this workflow                                              |
| Component     | Make a call to a configured component                                                         |
| Final State   | The end of the workflow                                                                       |
| Error State   | Activity defined to handle exceptions thrown by this workflow                                 |

Workflows are defined in the TrustBuilder Administrator using layout files which are representations of actual TrustBuilder workflows that are serialized to workflows when saved.

### Scripts

Scripts are Javascript files that perform processing during a workflow. The functions in the scripts are related to activities defined in a workflow. Some common use cases of functions are to extract data from the incoming request, process data before calling an adapter, processing the response from an adapter or create the eventual response from the workflow. Scripts are related to workflows a workflow can have more than one script and a script can be referenced by more than one workflow. Scripts can also call services defined in the configuration

### Templates

Templates are HTML, TMPL, JSON or TXT files that can be populated by script files and delivered by a workflow. The functions in the scripts are related to activities defined in a workflow. A common template maybe a login page.

### Library Files

Library files are files that will exist in the TB_HOME/lib directory. These might be JAR lib files or files that are used by services for instance.

### Properties

Property files are PROPERTIES, CONF, CNF, CONFIG or JAAS files that can be used by the TrustBuilder core.

### Logging

The logging configuration file that the TrustBuilder core uses to log messages. This is a logback configuration file. For details see: <http://logback.qos.ch/>

### Authorization Policies

The Authorization (AZN) policies are configured in a sub-set of screens from the main configuration. There are a number of elements: RuleSuites, Resources, PiPs, Rules, Conditions, Assertions and Hints. For more details refer to the relevant chapters in this document. The AZN policies use a service that is configured in the core. This is enabled within the AZN screens.

### Security Stores

Trust and Key stores can be created or imported and then managed. These actions are currently available.  

|       Store Action        |                                                      Description                                                       |
|---------------------------|------------------------------------------------------------------------------------------------------------------------|
| New Store                 | Create a new, empty, key or trust store secured with a password.                                                       |
| Upload a Certificate      | Upload a certificate file to the current store from this computer.                                                     |
| Change Password           | Change the password of the key or trust store. The current password is needed.                                         |
| Upload a Security Store   | Upload a key or trust store file from this computer. The current password of store is needed                           |
| Download a Security Store | Download the key or trust store to this computer.                                                                      |
| Export Security Store     | If configuration is related to one or more servers then export this key or trust store to that/those servers.          |
| Import Security Store     | If configuration is related to one or more servers then import the key or trust store from one of the related servers. |
| Delete Security Store     | Delete the current key or trust store.                                                                                 |
| Delete Certificate        | Delete one or more certificates from the key or trust store.                                                           |
| View Certificate Details  | View the details of a certificate including extensions.                                                                |
| PEM                       | Access the certificate as a string that can be copied.                                                                 |

## Interface Elements

### Notification Status Log

Notifications are displayed to the user when there are errors, warnings or an action has been successfully performed. All actions are listed in the Notifications Status Log found at the top right of each screen except for the editors (scripts, templates and properties) and the server logs screen which all open in a different window.

The number of unread notifications is displayed in a counter. This is cleared once the messages have been accessed.  
![image-20230425-135609.png](https://docs.trustbuilder.com/__attachments/a_4726a737dcb1c488427c615522cc164d7652c1c255bfca815381a4d2aa5b48a7/image-20230425-135609.png?cb=81742e7a34a15d5a10d01c5d50cac929)

To view the notification status log click the **Notifications** button:  
![image-20230425-135652.png](https://docs.trustbuilder.com/__attachments/a_46f4d217c68f7c724adf1238352175be47b1096ee5856d7002d66ef47e31a798/image-20230425-135652.png?cb=04c60744d34136c76c30974701c531a9)

The notifications are listed in order that they occurred the latest is listed first.  
![image-20230425-135719.png](https://docs.trustbuilder.com/__attachments/a_3237b921cd8617c9686f20ce03277a666b9169342c5df513efb45f847c5ae30b/image-20230425-135719.png?cb=55cf3e82215c5e28a606042b6da38e89)

To cope with a large list the messages can be filtered to show just Errors or Warnings by clicking the relevant buttons at the top of the Notifications Status Log.  
![image-20230425-135752.png](https://docs.trustbuilder.com/__attachments/a_7fa1b02a93796281362a644c26e8dbacb720ef67c29d3c43df9304d9bf9bce81/image-20230425-135752.png?cb=ddee82e4f2942425433ba35c93dbac36)

To clear the list click the **Clear all notifications** button. To close the Notification Status Log either click anywhere outside the list or click the **X** button.

### Cancelling Requests

When an action is started a loading icon is displayed and access to the main screen is blocked. If a request is taking too long it can be cancelled by hitting the escape, Esc, key. This will return control to the main screen.

## Using the Administrator

The normal process initially taken in the TrustBuilder Administrator (TBA) is the following:

* Create a configuration

* Edit the configuration

* Create an instance pointing to a TrustBuilder installation

* Export the configuration and restart the TrustBuilder server.

If there is a TrustBuilder server that has already been installed and populated with configurations, workflows, scripts etc. Then a configuration can be created by importing from this TB server by following these steps.

* Create a TrustBuilder server with the correct host name and management port or the installed TrustBuilder

* Click the option \> import button

* Work on your configuration

* Export and restart to the server when required.

If there are no files or the TB_HOME does not exist then a blank configuration file is created in TBA for that server.

A configuration can also be uploaded from the current computer. If a valid configuration zip file is supplied click the **Upload Config Zip** button on the Administration screen and upload the file.

---
language: "en"
---
# Creating Rules and Policies

This tutorial shows you how to create policies and rules in TrustBuilder.io.

TrustBuilder rules and policies allow for a flexible and powerful mechanism for specifying access control decisions.

* Policies provide a high-level view of the access control requirements for a particular resource.

* Rules provide a more detailed view of the access control requirements for a particular request.

*For more information, please see* [Defining Security Policies](https://docs.trustbuilder.com/product/defining-policies#DefiningSecurityPolicies-PoliciesandRules)

To create rules and policies, you should **login to the Admin Portal**as administrator.  
**Known limitation**

* The rule must be defined first. In a later release it will be possible to create a rule when creating a policy.

## Create a rule

To create a rule:

1. Go into **Access Management** \> **Rules \> + Add Rule**

2. Click on the three lines icon in the top right corner to get a JSON view.

   ![TB-rules01.gif](https://docs.trustbuilder.com/__attachments/a_02941b1f972fdee85ceea22daa87db9ca8484f24164e8d65f0be8b1ab3a61e11/TB-rules01.gif?cb=b17da673442cbe77eafe7babac64eff7)
3. Enter your rule. For this example, you can copy \& paste the following rule:

       {
         "name": "hourly-authentication",
         "description": "check whether the user has authenticated less than 1 hour ago",
         "condition": {
           "elem_match": [
             "$session.authentications",
             { "not_older_than" : [ "~last_supplied_at", "PT1H" ] }
           ]
         },
         "effect": "PERMIT",
         "obligation": {
           "requires_acr": [ "AAL1" ]
         }
       }

   In plain English, this rule actually means: "If the session of the user contains an authentication that is not older than 1 hour, return a permit; if not, return an obligation to ask the user to re-authenticate."
   * Ensure that the name of the rule does not contain spaces.

   * The period `PT1H` means "1 hour" according to ISO 8601. Other possibilities include `PT2M` (2 minutes), `PT30S` (30 seconds), `P5D` (5 days), `P1Y` (1 year), etc.

   * The rule in this example uses the the `$sessions.authentications` attribute of the session state. This is an array with the latest values of the `acr` and `last_supplied_at` of all types of authentications done by the user during this session.

   * The rule in this example also uses the `elem_match` operator: this operators looks in an array (the first operand) and tries to find the first element that meets the criteria (the expression in the second operand). In case such element is found, the result is `TRUE` else it will be `FALSE`.

   * The obligation in a rule is returned to the client application in case the condition is not met. In this case, it asks to request the user to provide a new authentication with an IDP that has the assurance level `AAL1`.

4. Click on **Save**.

   ![image-20230605-122140.png](https://docs.trustbuilder.com/__attachments/a_8c6f21000836f60f1c25e5493d53f0e58b5c56804eea2102dcd62cdf991240f1/image-20230605-122140.png?cb=7ea521bf26250406ee677b278ad745c9)

Well done! Your first rule is saved. It should appear in the rules list.

Now, you should create a policy and add the rule in this policy.

## Create a policy

To create a policy:

1. Go into **Access Management** \> **Policies \> + Add Policy**

2. Enter a name for your policy (without spaces) and a description.

   ![Untitled design.png](https://docs.trustbuilder.com/__attachments/a_942bae2560fd5189ffd5b9c975f4c688d7cf46ba440d8b97dffae6d52557822c/Untitled%20design.png?cb=5890c6040c0ee04a42791a98e94c670a)

   You can click on the three lines icon in the top right corner to get a JSON view.
3. Drag and drop your rule to the policy.

   ![TB-policy_rules10.gif](https://docs.trustbuilder.com/__attachments/a_b29a2fdbee8c0707b167cdfba56047d81644d03a8bb427edb88f78860c3e651f/TB-policy_rules10.gif?cb=2ea7e1ea5a5a286db384d6c6f75bb230)

   You can add as many rules as needed to a policy. You can arrange them in any order you want to apply a priority.
4. Click the gear icon to select the combination *(* [*more information*](https://docs.trustbuilder.com/product/defining-policies#DefiningSecurityPolicies-PolicyLanguage)*)*.

   ![image-20230606-125553.png](https://docs.trustbuilder.com/__attachments/a_87508a29b75fa280e02a590f038e6d86535b90933523c81ab63204d060c735ef/image-20230606-125553.png?cb=aeb301ff9a3f9811e70e0ff5e18d3a8d)
5. Click on **Save**.

Well done! You created your first policy. It should appear in the policies list.

---
language: "en"
---
# Custom adapter

There is a specific type of adapter called a Custom Adapter which can be used to configure adapters that may be specific to an installation, such as a call to an in-house logging API or to an in-house database connection API. A custom adapter should extend the base class "be.securit.trustbuilder.adapter.kernel.Adapter".

## Configuration

**AdapterUniqueID**

Unique name assigned to this adapter; the name is used to reference the adapter in the workflow. The ID has following requirements:

* START with a letter or _ (underscore)

* FOLLOWED by a combination of following characters: Letter, Number, '.' (dot), '-' (dash), '_' (underscore)

### Workflow Settings

A request for the adapter is prepared by specifying the following properties/scripts in the adapter activity:

* Input Property: the variable containing the instructions the adapter have to execute

* Output Property: the variable the adapter will store the response in after execution

* Before Adapter Script: script that will be executed before calling the adapter

* After Adapter Script: script that will be executed after the adapter fulfilled its task

#### Request - API

In order to generate a request in the scripts it is considered best practise to create a function like this:

    var createMyCustomAdapterRequest = function(payload){
         return new Packages.my.tld.package.RequestClass(payload);
    }

#### Response - API

**Common Properties** The response API can be applied to the variable specified in the "output property" (see "Workflow Settings"): to verify whether the action performed by the adapter was successful, to query for the data returned by the adapter.

All responses have four properties in common:

* **status** Status flag indicating whether the response is ok (0) or not (1).

* **substatus** Response specific number indicating what the problem was, eg. http status code

* **message** Response specific message in case there was a problem (can be null)

* **rc** Return Code, a human readable code based on the substatus

The status flag indicates whether a request was valid yes or no; consequently, the message or return code (rc) can be used to give the end-user a reasonable explanation or send the information to the underlying logging system.

**Extending the response api** If you want your custom adapter responses to behave like real javascript object you can register a converter. This is a function that converts your java response class into a javascript object.

    tbres.converters['MyCustomAdapterResponseClass'] = function(responseInstance){
         // convert to js object 
         return {
            myProperty: String(responseInstance.getMyProperty()) // cast to javascript string
         };
    }

---
language: "en"
---
# DateService

|----------------|-----------------------------------------------|
| **Name**       | DateService                                   |
| **Class Path** | `be.securit.trustbuilder.service.DateService` |
| **Versions**   | 9 10 11                                       |

## Overview

The `DateService` class provides various utilities for working with dates, including formatting, epoch conversions, range validation, and date calculations.

*** ** * ** ***

## **Available Methods**

### `String now(String format)`

Returns the current date and time formatted according to the provided pattern.

* **Parameters:**

  * `format` (`String`): The format pattern (e.g., `"yyyy-MM-dd HH:mm:ss"`).

* **Returns:**

  * `String`: The formatted current date.

*** ** * ** ***

### `long epoch()`

Retrieves the current epoch timestamp in milliseconds.

* **Returns:**

  * `long`: Current timestamp.

*** ** * ** ***

### `long epoch(String date, String format)`

Parses a date string into an epoch timestamp.

* **Parameters:**

  * `date` (`String`): The date string.

  * `format` (`String`): The format of the date string.

* **Returns:**

  * `long`: Epoch timestamp or `-1` if parsing fails.

*** ** * ** ***

### `boolean inRange(long start, long end)`

Checks if the current time falls within a specified range.

* **Parameters:**

  * `start` (`long`): Start timestamp.

  * `end` (`long`): End timestamp.

* **Returns:**

  * `boolean`: `true` if the current time is within the range, otherwise `false`.

*** ** * ** ***

### `String nowISO8601()`

Gets the current date and time in ISO 8601 format.

* **Returns:**

  * `String`: ISO 8601 formatted date.

*** ** * ** ***

### `String formatISO8601(Number epoch)`

Formats an epoch timestamp into an ISO 8601 date string.

* **Parameters:**

  * `epoch` (`Number`): The epoch timestamp.

* **Returns:**

  * `String`: ISO 8601 formatted date.

*** ** * ** ***

### `String formatISO8601(Number epoch, String timezone)`

Formats an epoch timestamp into an ISO 8601 date string with a specific timezone.

* **Parameters:**

  * `epoch` (`Number`): The epoch timestamp.

  * `timezone` (`String`): The desired timezone.

* **Returns:**

  * `String`: ISO 8601 formatted date.

*** ** * ** ***

### `String format(Number epoch, String format)`

Formats an epoch timestamp using a specified format pattern.

* **Parameters:**

  * `epoch` (`Number`): The epoch timestamp.

  * `format` (`String`): The format pattern.

* **Returns:**

  * `String`: Formatted date string.

*** ** * ** ***

### `String format(Number epoch, String format, String timezone)`

Formats an epoch timestamp with a specific format and timezone.

* **Parameters:**

  * `epoch` (`Number`): The epoch timestamp.

  * `format` (`String`): The format pattern.

  * `timezone` (`String`): The desired timezone.

* **Returns:**

  * `String`: Formatted date string.

*** ** * ** ***

### `String calcDateISO8601(String addOrSubtract)`

Calculates a new date by adding or subtracting a time unit from the current date and returns the result in ISO 8601 format.

* **Parameters:**

  * `addOrSubtract` (`String`): Time adjustment (e.g., `"+1d"`, `"-3h"`).

* **Returns:**

  * `String`: ISO 8601 formatted date.

*** ** * ** ***

### `String calcDate(String addOrSubtract, String format)`

Calculates a new date by adding or subtracting a time unit from the current date and returns the result in a specified format.

* **Parameters:**

  * `addOrSubtract` (`String`): Time adjustment (e.g., `"+1d"`, `"-3h"`).

  * `format` (`String`): The desired format pattern.

* **Returns:**

  * `String`: Formatted date.

*** ** * ** ***

### `String calcDate(long epoch, String addOrSubtract, String format)`

Calculates a new date based on a given epoch timestamp and returns it in the specified format.

* **Parameters:**

  * `epoch` (`long`): The reference epoch timestamp.

  * `addOrSubtract` (`String`): Time adjustment (e.g., `"+1d"`, `"-3h"`).

  * `format` (`String`): The desired format pattern.

* **Returns:**

  * `String`: Formatted date.

*** ** * ** ***

### `long calcDateAsEpoch(String addOrSubtract)`

Calculates a new epoch timestamp by adding or subtracting a time unit from the current date.

* **Parameters:**

  * `addOrSubtract` (`String`): Time adjustment (e.g., `"+1d"`, `"-3h"`).

* **Returns:**

  * `long`: Updated epoch timestamp.

*** ** * ** ***

### `long calcDateAsEpoch(long dateInEpoch, String addOrSubtract)`

Calculates a new epoch timestamp based on a given epoch and time adjustment.

* **Parameters:**

  * `dateInEpoch` (`long`): The reference epoch timestamp.

  * `addOrSubtract` (`String`): Time adjustment (e.g., `"+1d"`, `"-3h"`).

* **Returns:**

  * `long`: Updated epoch timestamp.

*** ** * ** ***

## **Date Calculation Units**

When using the `calcDateAsEpoch` and related methods, the following units can be used:

* `s` → seconds

* `m` → minutes

* `h` → hours

* `d` → days

For example:

* `"+1d"` → Adds one day

* `"-3h"` → Subtracts three hours

*** ** * ** ***

## **Summary**

The `DateService` class provides an extensive set of methods for handling date and time operations, including:

* Formatting timestamps in various formats.

* Converting dates to and from epoch timestamps.

* Validating time ranges.

* Performing calculations on dates (addition/subtraction).

This utility simplifies date-related operations, making it efficient for applications that require precise time handling.

---
language: "en"
---
# Working with Personas

TrustBuilder fundamentally implements the model of "every user has one and only one profile" even if the person has different subscription accounts and even when the person works with different mandates or in different capacities. To enable this, TrustBuilder introduced its persona-model. A user profile in TrustBuilder can embody one or more "personas".

## What is a persona?

A persona in TrustBuilder reflects the type of activities a users wants to undertake and allows these activities to be clearly segregated, for reasons of user convenience and/or for reasons of security. TrustBuilder policies use the selected persona to decide whether certain activities can be granted or not.

For example, a person can be a retail customer or be mandated for administrative tasks on behalf of her company. Depending on the relationship with the enterprise, a user has more or less privileges. More privileges typically represent more authority but also more risk. To reflect the fact there are different types of users, TrustBuilder introduces the "persona" concept. The TrustBuilder identity and access management model is based on personas. This means that depending on your persona, different rules may apply, different workflows may apply, different ways of orchestrating delegation may apply and different levels of identity proofing may apply.

The TrustBuilder persona models goes even one step further. Imagine she is both a retail customer and representing her company. In that case, TrustBuilder still recognizes her as the same individual with only one profile but with two 'personas' in her user profile. Each persona in her user profile corresponds to one of the roles she can assume. This way a user in TrustBuilder can belong to more than one user segment: an individual can assume of the role of retail customer and of corporate customer

Another example is a person who is a health care professional, but who can at one point also be a patient herself. Or a professor at a university who can also become a student for particular post-university courses. Or a staff member can equally be a retail customer of the same company. Or a person may be part time in one team and part time working for another company. Or a person may be a software developer who, in times of emergency, needs to help out in operations.

Using TrustBuilder, a user logs in with a single user profile - there is only one, even if the person can act in different capacities or needs different accounts in different systems. At login, the user selects a specific persona or uses their preferred persona by default. Afterwards, the user can switch to a different persona when relevant or required. Even though this happens within the same session of the user, an authorization policy may state that switching to a privileged persona requires additional authentication (step up authentication).

## Why using personas?

By introducing the concept 'persona', authorization policies can rely on attributes that reflect a mandate or capacity that a person plays at that time. A TrustBuilder 'persona' embodies attributes that are specific for that mandate or capacity and can be self-declared.

The "persona" model enables the user base to be segmented (but without hard borders because users may belong to more than one segment, i.e. have more than one persona). The "persona" model enables differential life cycles, provisioning workflows, authentication and authorization policies (depending on selected persona). The "persona" model also enables delegated administration to be scoped to the attributes of a specific persona only, without affecting other parts of the user profile. The top-level user profile thus stays under control of the enterprise

Additionally, TrustBuilder offers a full approval mechanism for self-declared attributes to delegate administration to the end users.

With its persona-driven authorization policies, TrustBuilder:

1. Enables *Delegated Security Administration* whereby security admin (indeed!) is moved to people close to the end user. This is in contrast to having a sysadmin assign permissions, roles and groups. Delegating security administration to the people themselves, fosters timeliness, accuracy, appropriateness, and freshness.

2. Enables *User Lifecycle Management* to be done at the persona level rather than traditionally at the 'user account per application' level. This means that when a person leaves a function, her accounts do not need to be deactivated: only the associated persona needs to be deactivated. It also allows people to already start using their account, even before their persona 'employee' has been activated.

3. Enables effortless implementation of *Segregation of Duties*, by having different personas corresponding to different duties.

4. Enables straight-forward implementation of *Privileged Access Management*. For example controlled 'privilege elevation' during emergencies is easily implemented by using different personas and have the authorization policy take care of additional authentication and the logging of activities.

5. Enables a policy-driven implementation of *User Managed Access*. For example, a person may grant access to her diploma details by stating what persona is required for getting access, typically the persona 'hr-manager'.

TrustBuilder personas bring the management of access control to a new level: it easily combines the benefits of RBAC and ABAC while simplifying its administration. In fact, delegating persona administration using TrustBuilder allows access to be controlled at massive scales: no longer is a central sysadmin group needed to assign permissions, access rights, roles, and groups to end users. Instead, delegated persona administration puts people in the center of their own administration: they manage their own attributes and personas and therefore their own access.

## Guidelines: types and scopes of personas

When to create separate persona-types? As a general rule of thumb, a persona-type denotes a user segment in business terms. You may have a user segment of employees, one of consumers and one of corporate customers, one for suppliers, another for distributors and resellers, etc. Since a person may be assigned one or more persona-types, that person can belong to one or more user segments. For example, an employee can also act as a consumer at times.

A persona inside a user profile is uniquely identified with the persona-type in addition to the persona-scope. The persona-type indicates the category, the type of relationship, the business role (e.g. "employee", "consumer"). The persona-scope refines this to say for which company, region or other characteristics this applies. For example, the scope for an "employee" persona will contain the name of the employer. The scope for a "service-desk-operator" may refer to the region they are responsible for.

How granular should the persona type be? In the design of persona types, it is important to keep in mind that TrustBuilder gears identification and access control, which implies policies, workflows, and life cycle management. For example:

* While an office employee may need access to enterprise applications, non-office employees may only need access to the payslip and holiday request aspects of the HR service. In this case, it makes sense to have two different personas: "office employee" and "non-office employee." Additionally, you may have employees on the payroll and contractors. But from an access point of view, their may be no difference between the two categories. In that case, it does not makes sense to differentiate between an employee and a contractor and to generalize the personas to co-worker: "office-co-worker" and "non-office-co-worker" rather than "employee" versus "contractor."

* While a consumer can enroll on their own initiative, a customer could also be enrolled by their company in a form of delegated administration (see below). In that case, it may make sense to a differentiate between "retail customer" and "company customer". The reason being that the lifecycle of a "retail customer" is managed by the customer themselves, while the life cycle of a "company customer" is managed by their company. On the other hand, a consumer who has bought two categories of products does not need a persona for each product: this is dealt with in the `scope` attribute. Additionally, individual subscriptions can be dealt with by the `entitlements` attributes.

In the design of the User Profile, you have the choice of putting attributes at top level or at the persona level. What rules of thumb to apply?

* A top-level attribute says something about the individual, independent of the type of role that individual can assume. Example top-level attributes are name, title and preferences such as preferred language, preferred communications channel.

* Persona-related attributes refer to attributes that are specific to the business role it represents. For example, a supplier persona may include the supplier-id in the ERP, while a consumer persona may include the customer-id in a CRM. An employee persona may also include the AD account(s) for accessing enterprise applications.

## Guidelines: using personas for delegated administration

The "persona" concept is also a key ingredient for Delegated Administration in TrustBuilder. Delegated Administration means that user profiles are not only created and maintained by a Service Desk, but can also be managed by end users. For example:

* Self-service: an individual may create a profile and add information themselves (delegation the profile owner)

* Team leaders: a team leader may create and update the user profile of a team member

* Partners: a supplier, a dealer, a distributor, a reseller or an installer may create and update the user profile of their employees themselves

* Branches: a branch, a shop or a region may create and update the user profile of the people in scope on behalf of the user

* Organization: a company, organization or association may create and update the user profile of their members

* Family: a household or private club may create and update the user profile of their family members

In all these cases, it is not the Service Desk but one of the end users who does (some part of) the user administration in a delegated way. Because it is much closer to the profile owner, Delegated Administration offers some key advantages:

* less work or the Service Desk since they will only need to deal with exceptions

* less delays since it is not driven by anonymous service tickets but by human interaction

* more accurate because the administrator knows the profile owner's context much better.

TrustBuilder, however, adds a unique feature to Delegated Administration. Thanks to the "persona" concept:

* because every individual has only a single user profile, they own it: they can create it or activate it and they set their preferred username, their full name, their title, and their preferred language.

* a delegated person can only create or update persona-related attributes: the user profile remains owned by the holder and the delegated person can only add or change one of the personas. For example an indivual may have a user profile for e-commerce, and thus have a "consumer" persona. Their employer can add a "co-worker" persona with its specific company-related attributes.

* a delegated person can only create or update a persona with the same scope. For example, a HR manager can add a "co-worker" persona only for the branch or region they are responsible for. An individual can thus have a persona "co-worker" with scope "West" and another persona "co-worker" with scope "East" that is managed by a different HR.

What if an individual does not have a user profile yet? The action of "adding" a persona will then typically first implicitly create a user profile to which the first persona will be added. The fresh user profile then needs to be 'activated' by the owner during which the owner can add their consent, can enter or correct their full name and can add an authentication factor.

## Guidelines: relating personas to role and group provisioning

Many enterprise applications today are controlling access using permissions. Permissions may be grouped into "roles" or "groups". For example SAP has roles and compositie roles. Also Salesforce uses roles to specify the levels of access of a user can. Microsoft applications use Activate Directory groups. So, how does this relate to personas?

In contrast to such technical roles, a 'persona' refers the real-life function, capacity or mandate of a person. It is an attribute that people can easily relate to in real-life: "yes, I'm a consumer buying products" or "yes, I'm an employee at this company." As such, personas are business and person-centric.

Roles used in the context of Role-Based Access Control (RABC), on the other hand, represent permissions relative to an application. RBAC roles are application-centric. Roles are then assigned to users.

Since many enterprise applications need roles, how does TrustBuilder bridge personas with roles? TrustBuilder allows the roles to be registered inside a persona of a user profile, using the `entitlements` attribute. This attribute is used to provide service providers and applications with the roles they need, either during the provisioning flow, or as custom claims in the access token. This means that TrustBuilder maps a persona onto permission-roles using the `entitlements` attribute to enable it to feed RBAC systems when needed. TrustBuilder implements a Policy-Based Access Control (PABC) model, which does not need roles. A customer, however, can take the `entitlements` attribute into account when designing rules for an Authorization Policy.

The next section shows some use cases of multiple personas for individual users. Of course, many users will only have a single persona, e.g. 'staff member' or 'consumer'. The examples show how authorization decisions can be influenced by selecting the right persona when a user has more than one persona.

## Use cases

Use case 1. Privileged Access  
If an IT-er is doing only office work, she can use the persona 'staff' and when she manages the settings in a software platform, she can switch to her 'operator' persona. When using the latter persona, she will be able to conduct sensitive operations on a production system. The authorization policy may also forbid her to use read her email using this persona, to be shielded from phishing attacks.
JSON

    "personas": [
    {
       "persona_name": "staff",
       "scope": [ "chemco" ],
       "entitlements": [ "office365", "sharepoint_team_A" ],
       "email": "an.janssen@chemco.com"
    },
    {
       "persona_name": "operator",
       "scope": [ "chemco" ],
       "entitlements": [ "office365", "windows_servers" ],
       "email": "an.janssen@chemco.com"
    }
    ]

Another example is a person who performs office work and from time to time helps out in the customer services team.
JSON

    "personas": [
    {
       "persona_name": "staff",
       "scope": [ "chemco" ],
       "entitlements": [ "office365" ],
       "email": "jan.janssen@chemco.com"
    },
    {
       "persona_name": "user-admin",
       "scope": "chemco-region-west",
       "entitlements": [ "office365", "sharepoint_helpdesk" ],
       "email": "jan.janssen@chemco.com"
    ]

Another example is an HR manager who can do administration in an HR platform, but who is also employee using the HR platform for her own pay slips and holiday requests, for which Segregation Of Duties is required.
JSON

    "personas": [
    {
       "persona_name": "customer_hr_manager",
       "scope": [ "chemco-region-west" ],
       "email": "hr_management@chemco.com"
     },
    {
       "persona_name": "customer_employee",
       "scope": [ "chemco" ],
       "email": "an.janssen@chemco.com"
    }
    ]

Use case 2. Job Cumulation  
A person may be part time working for one team and be part time working for another team. To implement Segregation Of Duties for certain activities (or to simply avoid that documents are misplaced in the wrong team folder on Sharepoint), the person may be given 2 personas, one for each team. The authorization policy may state that for a number of activities it does not matter which persona is selected, and that for specific sensitive activities the selected persona does matter.
JSON

    "personas": [
    {
       "persona_name": "staff",
       "scope": [ "team-A" ],
       "entitlements": [ "office365", "sharepoint_team_A" ],
       "email": "jan.janssen@chemco.com"
    },
    {
       "persona_name": "staff",
       "scope": [ "team-B" ],
       "entitlements": [ "office365", "sharepoint_team_B" ],
       "email": "jan.janssen@chemco.com"
    }
    ]

Another example is a person who is the supervisor of a team and who may also be delegated the supervisor role of a seocnd team during the absence of their supervisor.
JSON

    "personas": [
    {
       "persona_name": "staff",
       "scope": [ "team-A" ],
       "entitlements": [ "office365", "sharepoint_team_A" ],
       "email": "jan.janssen@chemco.com"
    },
    {
       "persona_name": "supervisor",
       "scope": [ "team-A" ],
       "entitlements": [ "office365", "sharepoint_team_A", "officient_hr" ],
       "email": "jan.janssen@chemco.com"
    },
    {
       "persona_name": "delegated-supervisor",
       "scope": [ "team-B" ],
       "entitlements": [ "office365", "officient_hr" ],
       "email": "jan.janssen@chemco.com"
    }
    ]

A healthcare professional may be working in a private practice (identified with e.g. a custom attribute `hcp_registration_number`) as well as in a hospital. The authorization policy may decide to grant different types of access to different medical records, depending on the selected persona.
JSON

    "personas": [
    {
       "persona_name": "health_care_professional",
       "scope": [ "My Private Practice" ],
       "hcp_registration_number": "BE 4-15136-31-522",
       "email": "jan.janssen@gmail.com"
    },
    {
       "persona_name": "health_care_professional",
       "scope": [ "UZLeuven" ],
       "email": "jan.janssen@uzleuven.be"
    }
    ]

People at an accountancy office may be working for different customers. In order not to confuse the administration between their customers, they may decide to explicitly ask their staff to choose the company they are working for at that moment using persona selection.
JSON

    "personas": [
    {
       "persona_name": "accountant_at_customer",
       "scope": [ "chemco" ]
    },
    {
       "persona_name": "accountant_at_customer",
       "scope": [ "ibm" ]
    }
    ]

Use case 3. Consumers and Professionals  
A person may be a retail customer as well as being a staff member of the company. When acting as an employee, identified with the custom attribute `employee_number`, the person can use all internal applications. When acting as a consumer, the person can order products and gets a totally different user experience.
JSON

    "personas": [
    {
       "persona_name": "consumer",
       "email": "jan.janssen@gmail.com"
    },
    {
       "persona_name": "employee",
       "scope": [ "chemco" ],
       "employee_number": "P036652",
       "email": "jan.janssen@chemco.com"
    } 
    ]

Or a person may be a retail customer as well as representing a company for the B2B business.
JSON

    "personas": [
    {
       "persona_name": "consumer",
       "email": "an.janssen@gmail.com"
    },
    {
       "persona_name": "customer_employee",
       "scope": [ "chemco" ],
       "email": "an.janssen@chemco.com"
    } 
    ]

Another example is a healthcare professional may be a patient herself at times, identified e.g. a custom attribute `patient_number` = National Register Number.
JSON

    "personas": [
    {
       "persona_name": "heart_surgeon",
       "scope": [ "UZLeuven" ],
       "email": "an.janssen@uzleuven.be"
    },
    {
       "persona_name": "patient",
       "patient_number": "73.07.11-149.62",
       "email": "an.janssen@gmail.com"
    }
    ]

Use case 4. Households and Associations  
A person may be a retail customer as well as being the pater familias paying the bills of a family subscription. Using the latter persona, the user can administer subscriptions and share the subscriptions with his family members. The subscriptions being managed are listed in the custom attribute `subscriptions` and the family is identified with `scope` = e.g. family name in a village. This truly implements Delegated Administration for households.
JSON

    "personas": [
    {
       "persona_name": "consumer",
       "email": "jan.janssen@gmail.com",
       "entitlements": [ "tv-channels", "streamz", "my-personal-vault"]
    },
    {
       "persona_name": "family-administrator",
       "scope": [ "janssen_wilrijk" ],
       "email": "jan.janssen@gmail.com",
       "entitlements": [ "tv-channels", "streamz"],
       "status": { "current": "pending", "set_at": "2022-07-22T13:29:01Z" }
    } 
    ]

A person may be a retail customer as well as representing a company and their employees. Using the latter persona, the user can administer digital services on behalf of the company (identified e.g. with its registered company name in `scope` and the custom attribute `tva` containing the verified company registration number) and share access with his team members. This truly implements Delegated Administration for companies.
JSON

    "personas": [
    {
       "persona_name": "customer",
       "scope": [ "MyBakery SA" ],
       "email": "jan.janssen@gmail.com"
    },
    {
       "persona_name": "team-administrator",
       "scope": [ "MyBakery SA" ],
       "tva": [ "BE 0812.087.341" ]
    } 
    ]

A person may be a member of an association as well as representing the association. Using the latter persona, the user can administer access for the other members. This truly implements Delegated Administration for associations, communities and even friendships and temporary groups.
JSON

    "personas": [
    {
       "persona_name": "alumni",
       "scope": [ "alumni-association-abc" ]
    },
    {
       "persona_name": "alumni-administrator",
       "scope": [ "alumni-association-abc" ],
       "email": "jan.janssen@gmail.com"
    } 
    ]

## Create a custom Persona

Creating a persona is a step before associating it with a user profile.

To create a persona from TrustBuilder admin portal:

1. Go to **Directory** \> **Persona Definitions**.

2. Click on **+ Add Persona**

3. Enter a **name** *(lowercase and numbers only)* and a **description** *(optional)* for the new persona.

   The name cannot be edited after the persona has been created. The name will be visible to users to which this persona is linked.

   ![image-20230215-162422.png](https://docs.trustbuilder.com/__attachments/a_c1cf3dffd116ac665e1a7e1bc846f092df38f359c4d275c91a2f6ef5539a20c5/image-20230215-162422.png?cb=f8a02f45d31cfba4721d2eb4409f907f)
4. Define whether this persona will be the **default persona** .

   The default persona will be automatically selected for users if they don't choose another one.

5. **Link attributes** to this persona. *See Manage Attributes to know more*

   You can search for attributes or select them from the list.

6. Drag and drop the attributes to**re-order**the list.

7. Click on **Save**.

The Persona is successfully created. You can now associate it to a User Profile.

## Edit a custom Persona

To edit a Persona from the admin portal:

1. Go to **Directory** \> **Persona Definitions**.

2. Click on **the edit button** for the relevant persona.

3. **Edit**the parameters. The persona name cannot be edited.

4. Click on **Save**.

The Persona is successfully updated.  
Any change to a persona is immediately applied to the user profiles associated with it.

## Delete a custom Persona

To delete a Persona:

1. Go to **Directory** \> **Persona Definitions**.

2. Click on **Delete**for the relevant Persona.

3. In the pop-up, click on **Yes**to confirm the action.

The Persona is successfully deleted.  
Users will still be able to log in with their user profile, but they will no longer be able to select the persona. This action cannot be undone.

---
language: "en"
---
# Defining Policies & Rules

In TrustBuilder, Policies and Rules control access is based on user attributes and context. A Policy contains multiple Rules, and a combination algorithm defines how these rules are evaluated to grant or deny access.

TrustBuilder uses the XACML standard (eXtensible Access Control Markup Language) for defining and enforcing access control in a consistent, structured way..

TrustBuilder uses PBAC (Policy-Based Access Control), an extension of ABAC (Attribute-Based Access Control). Unlike role-based models, PBAC evaluates dynamic data like user attributes, context (time, device, etc.), and risk scores in real-time.

## Create a policy

To create a policy **from TrustBuilder Admin portal:**

1. Navigate to **Access Management** \> **Policies**.

2. Click on **+ Add Policy**.

3. Enter a name for your policy (without spaces) and a description.

   ![name-policy.gif](https://docs.trustbuilder.com/__attachments/a_aaf52de6711e0b9a09b33d86c809d06d0832d9397c0b02776e4a7284c301c78d/name-policy.gif?cb=61666bfd6952da75cd4cdcfe4d60f016)
4. Add one or more rules.

   ![info](https://docs.trustbuilder.com/__attachments/a_a375735788fda1d4f10298d9f0ec0b943e58ed90870947297014557c6c0b3979/atlassian-info?cb=feab5cd71111204d6b52545f3027dd0c) *Rules are evaluated in order: the first rule is checked first, then the second, and so on.*

   * If the rule already exists: drag and drop it under the policy

     ![drag-drop-rule.gif](/__attachments/a_da5ba3c318795b29610cc8d64669308b4a063dfff2f144722f28826ab76d255a/drag-drop-rule.gif?cb=91cd2adf2d17348fc3dd25e13edd393b)
   * If the rule does not yet exist, click on **+ Create new rule** ([see Create a rule](https://docs.trustbuilder.com/tb-io/defining-policies.md#create-a-rule)).

5. Choose a **combination algorithm** ([see Combination](https://docs.trustbuilder.com/tb-io/defining-policies.md#policy-attributes)):

   ![Policy-Combinaison.png](https://docs.trustbuilder.com/__attachments/a_07ca4b67844a0997b4eb677b7399a8c9c5445290ea26a496b55bec28e81bf457/Policy-Combinaison.png?cb=a1ff5fe27355ceb3a51eb644a3e3cc13)
6. Click on **Save**.

Create a policy using JSON view:  
1. Navigate to **Access Management** \> **Policies**.

2. Click on **+ Add Policy** on the top-right corner.

3. Click on the tree lines icon to switch to JSON view.

   ![Policy-JSONview.png](https://docs.trustbuilder.com/__attachments/a_f6d05ddc74a78d056fa91d128fb76bc936d17bac079e953a324d202e71d2be0a/Policy-JSONview.png?cb=81255613ee1fdb702e022156779539ad)
4. Enter the policy attribute values:

   JSON

       {
         "name": "policy-name",
         "description": "Optional description",
         "rules": ["rule1", "rule2"],
         "combination": "DENY_OVERRIDES"
       }

5. Click on **Save**.

|                                                                                                                                                                                                                                                                                    **Policy Attributes**                                                                                                                                                                                                                                                                                     |
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Name** Unique identifier for the policy String *(in lowercase without space)*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **Description** Short explanation of the policy String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **Rules** List of rules assigned to the policy Array of rule names "rules": ["rule_name01","rule_name02","rule_name03","rule_name04"]                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **Combination** How rules are evaluated together to make the policy decision |    No combination    | If a policy has one rule, no need to apply an algorithm. The rule alone determines the decision. | |   `DENY_OVERRIDES`   |               Access is denied unless all rules permit. One deny overrides permit.               | | `DENY_UNLESS_PERMIT` |                        Access is denied unless at least one rule permits.                        | |----------------------|--------------------------------------------------------------------------------------------------| |

#### Policy example

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Secure admin access**                                                                                                                                                                        |
| { "name": "secure-admin-access", "description": "Requires MFA and admin role for access", "rules": ["require_authent_aal1","only-admins","specific_userid"], "combination": "DENY_OVERRIDES" } |

## Create a rule

To create a rule from TrustBuilder Admin portal:

1. Navigate to **Access Management** \> **Rules**.

2. Click on **+ Add Rule**.

3. Enter enter **a name** for your rule (in lowercase without space) and an optional description.

4. Add **expression(s)**:

   1. Click on the **+ icon** to add an expression.

   2. In the expression section:

      * select **an attribute,**

      * **select an operator**

      * enter **a value** if needed.

        ![image-20260602-150949.png](/__attachments/a_9a6b18ee7404448e05852ab861c31556389d1ab479a4857de5e8ca23a0b97a6d/image-20260602-150949.png?cb=d6fae4f23843882b6986137e4268a7e9)

        ([see Condition below](/tb-io/defining-policies.md#rule-attributes))
5. Select the **combining condition**:

   ![image-20260602-151829.png](https://docs.trustbuilder.com/__attachments/a_6c281c694a4c02416585ecb6e4da086153490ed746f770a2bc7f460fc0b403aa/image-20260602-151829.png?cb=2365b79d7eb4fa09278b961455b445cf)
   * `all-of` → act as **AND** = all expressions must be met.

   * `any-of` → act as **OR** = at least one expression must be met.

6. Select the **effect** : `"PERMIT"` or `"DENY"` ([see Effect below](https://docs.trustbuilder.com/tb-io/defining-policies.md#rule-attributes)).

7. (optional) Define **an obligation** to add additional requirement before granting access:

   1. Click on **Obligation options.**

   2. Select an obligation type:

      * Persona → select "any persona" or specific persona(s) in the list.

      * Specific authentication level → select at least one authentication level.

      * Minimum authentication level → select an authentication level.

        ([see Obligation below](/tb-io/defining-policies.md#rule-attributes))
   3. Click **Save** to add the obligation.

8. Click on **Save**to create the rule.

|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                ****Rule Attributes****                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Name** Unique identifier for the rule String *(in lowercase without space)*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **Description** Short explanation of the rule *(optional)* String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **Effect** The access decision `"PERMIT"` or `"DENY"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **Condition** A set of conditions that must be satisfied in order for the rule to be applied Expressions in a rule condition are constructed as follows: `{ "<operator>": [ "<operand-1>", "<operand-2>", ... ] }` **Operators in Conditions** |------------------|----------------------------------------------------------------------------------------------------------------------------------------------------| | `equals`         | Is equal to the specified value                                                                                                                    | | `not_equals`     | Is not equal to the specified value                                                                                                                | | `is_in`          | Is present in the list of specified values                                                                                                         | | `not_in`         | Is not present in the list of specified values                                                                                                     | | `has_value`      | * Has a non-empty value (for single-valued operands) * Has at least one non-empty value (for multi-valued operands)                                | | `is_empty`       | (inverse of "Has a value")                                                                                                                         | | `older_than`     | Is a timestamp and its value Is longer ago than the duration stated in [++ISO 8601 format++](https://en.wikipedia.org/wiki/ISO_8601#Durations)     | | `not_older_than` | Is a timestamp and its value Is not longer ago than the duration stated in [++ISO 8601 format++](https://en.wikipedia.org/wiki/ISO_8601#Durations) | | `elem_match`     | Is an array in which at least one element meets the embedded condition                                                                             | | `not`            | Is the negated value of the nested expression                                                                                                      | **Operands in Conditions** Operands are values that define conditions. They can be: * Fixed values: strings, numbers, or dates (e.g.,`"2023-05-17"`). * Dynamic values: variables that reference session or user attributes. * Example: `$session.user_id` refers to the logged-in user's ID. * Attributes are accessed using a dot `.` (e.g., `$session.persona.name` retrieves the active persona's name). |                 **Operand**                 |                                                                                             **Description**                                                                                             | |---------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `$session.user_id`                          | uuid of the user of the current session                                                                                                                                                                 | | `$session.started_at`                       | The start data \& time of the session identified with `session_id`                                                                                                                                      | | `$session.persona.name`                     | The `name` of the user's active persona in the current session.                                                                                                                                         | | `$session.persona.id`                       | The `id` of the user's active persona in the current session.                                                                                                                                           | | `$session.persona.scope`                    | The `scope` of the user's active persona in the current session.                                                                                                                                        | | `$session.persona.is_preferred`             | The `is_preferred` value of the user's active persona in the current session.                                                                                                                           | | `$session.persona.entitlements`             | The `entitlements` of the user's active persona in the current session.                                                                                                                                 | | `$session.persona.email`                    | The `email` of the user's active persona in the current session.                                                                                                                                        | | `$session.persona.valid_from`               | The `valid_from` value of the user's active persona in the current session.                                                                                                                             | | `$session.persona.valid_till`               | The `valid_till` value of the user's active persona in the current session.                                                                                                                             | | `$session.persona.status.current`           | The current `status` of the user's active persona in the current session.                                                                                                                               | | `$session.authentications`                  | The list of the latest values of the `acr` and `last_supplied_at` of all types of authentications done by the user during this session. You can refer to those values by `~acr` and `~last_supplied_at` | | `$session.persona.attributes`               | The `attributes` of the user's active persona in the current session.                                                                                                                                   | | `$session.persona.persona_definition_id`    | The `persona_definition_id` of the user's active persona in the current session.                                                                                                                        | | `$session.persona.attributes.category.name` | The custom attribute `category` and the custom attribute `name` of the user's active persona in the current session.                                                                                    | | `$session.user.attributes.category.name`    | The custom attribute `category` and the custom attribute `name` of the user in the current session.                                                                                                     | **Combining Conditions** Use `all-of` (AND) or `any-of` (OR) to combine multiple conditions: * `all-of` → act as **AND** = all conditions must be met. * `any-of` → act as **OR** = at least one condition must be met. |
| **Obligation** Additional actions required before granting access *(optional)* |--------------------|---------------------------------------------------------------------------------------------| | `requires_acr`     | The user must authenticate with a given assurance level(s) *e.g* `requires_acr: [ "AAL3" ]` | | `requires_persona` | The user must switch to the given persona `requires_persona: [ "doctor" ]`                  |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

## Authentication rule in policy

For a policy to work, it must include at least one rule that allows authentication.

Without authentication, the system cannot identify the user and therefore cannot evaluate conditions based on user attributes, persona or session context.

A typical authentication rule checks whether the user has authenticated with a given assurance level (e.g., AAL1) and enforces this requirement as an obligation:
JSON

    {
      "name": "require_authent_aal1",
      "effect": "PERMIT",
      "description": "Simple authentication with one factor",
      "condition": {
        "elem_match": [
          "$session.authentications",
          {
            "equals": [
              "~acr",
              "AAL1"
            ]
          }
        ]
      },
      "obligation": {
        "requires_acr": [
          "AAL1"
        ]
      }
    }

* The `condition` checks whether the session includes an authentication with AAL1 level.

* The `obligation` ensures the user **must** authenticate using AAL1.

**Match the ACR in the Access Flow**

This rule only works if the Access Flow offers at least one authentication method that is mapped to the same ACR value (e.g., `AAL1`).

*Exemple: A password-only login method should have an OIDC Context = AAL1 in the Access flow.*

If no method in the Access Flow matches the required ACR, the policy will always deny access.

[**More information**](https://docs.trustbuilder.com/tb-io/access-flows.md)

---
language: "en"
---
# Delegated administration

Delegated administration enhances flexibility and control over persona management within the TrustBuilder platform. Admins can delegate persona management, allowing users to oversee and manage other users' personas within their assigned scope.  
**Before you start**

* [Understand the concept of personas in TrustBuilder](https://docs.trustbuilder.com/tb-io/defining-personas.md)

* [Define personas and assigned them to users](https://docs.trustbuilder.com/tb-io/personas.md)

<https://youtu.be/lUhzFpJcVNE?si=v_iU3X05cwS4FjCc>

## Setting up Delegated administration

There are two ways for admins to set up delegated administration:

* [configure a broad delegation](https://docs.trustbuilder.com/tb-io/delegated-administration.md#broad_delegation), granting rights across all personas within a defined scope.

* [configure a targeted delegation](https://docs.trustbuilder.com/tb-io/delegated-administration.md#targeted_delegation), *restricting rights to selected personas within the defined scope.*

### Broad delegation

<https://youtu.be/Q_vcU79L3gs?si=LGdDXWPKRXhNUjaP>  
As "Delegated Admin" is a system persona, its properties cannot be modified.

To delegate persona administration through a system persona, you should assign "Delegated Admin" persona to a user with a specific duration and scope.

1. In TrustBuilder Admin portal, go to **Directory** \> **Users**.

2. **Edit**the user profile to be assigned to the persona.

3. Go to**Personas** tab **\> +Add Persona**.

4. Select **Delegated Admin persona** and click on **Next step**.

   ![image-20240701-100026.png](https://docs.trustbuilder.com/__attachments/a_c2f6acac8710fa32c1802264890dd01a962bccd6ae2b7214468dffdf243314bb/image-20240701-100026.png?cb=e7364ce8cb547757fb4778530ce3cced)
5. Define this persona's parameters for this user:

   * **Preferred persona**: (Optional) Set as preferred.

   * **Persona details** : Define the validity period.

     If left empty, the assignment becomes effective immediately upon saving the form and remains valid indefinitely.

   * **Persona scope** : Add persona scope value(s).

     Scopes can be any value. However, we recommend that you use values that make sense and are consistent. F*or example: scope values based on the location (Belgium, France, Italie, Spain), on the department (marketing, IT, sales, HR,...), on a number (scope1, scope2, scope3,...).*

     The scope values added here must match the scope values defined in the personas of the users to be managed.

     ![image-20240701-100233.png](/__attachments/a_ebf604cb9c1c66f59e5b3791549e7a1c15b75676e7dcfefb98df3f539dde3213/image-20240701-100233.png?cb=dda03d5fbc39339d8f6eed1b90f631b1)
6. Click on **Save**.

The Delegated Admin persona has been assigned to the user with a specific scope.  
![image-20240701-100446.png](https://docs.trustbuilder.com/__attachments/a_31c0dcd34402ca5dd4dc607c119235a208e9d78f13eb7f06ad6b0749cf735593/image-20240701-100446.png?cb=48ce3535d5daeed82cc00f06ccc4d55a)

Based on the defined validity, the user will be able to manage users personas within the specified scope, from its Self Service Portal.

[*See Self-Service Portal documentation*](https://docs.trustbuilder.com/tb-io/self-service-portal.md)

### Targeted delegation

<https://www.youtube.com/watch?v=CJZhc5N5BsI>

To delegate persona administration trough delegation parameters in a persona, you should first enable and configure delegation in a persona definition and then assign this persona to a user with a specific duration and scope.

**Step 1: Enable and configure delegation in persona definition**

1. In TrustBuilder Admin portal, go to **Directory** \> **Persona Definitions**.

2. Create or edit a persona definition.

3. In the Delegation parameters in the persona definition:

   * Toggle to **Authorize delegation**.

   * Select the persona(s) that can be delegated.

     ![image-20240701-132844.png](/__attachments/a_7bf316206a526e10a7799d21c5fb404a0aca964bd2b19854394dfe41f0d7f43f/image-20240701-132844.png?cb=45b0b3116a4d06574b53e3a0661e76eb)
   * Click on **Save**.

**Step 2: Assign the persona to the user**

1. In TrustBuilder Admin portal, go to **Directory** \> **Users**.

2. **Edit**the user profile to be assigned to the persona.

3. Go to**Personas** tab **\> +Add Persona**.

4. **Select the persona** with delegation enabled and click on **Next step**.

5. Define this persona's parameters for this user:

   * **Preferred Persona**: (Optional) Set as preferred.

   * **Persona details** : Define the validity period.

     If left empty, the assignment becomes effective immediately upon saving the form and remains valid indefinitely.

   * **Persona scope** : Add persona scope value(s).

     Scopes can be any value. However, we recommend that you use values that make sense and are consistent. F*or example: scope values based on the location (Belgium, France, Italie, Spain), on the department (marketing, IT, sales, HR,...), on a number (scope1, scope2, scope3,...).*

     The scope values added here must match the scope values defined in the personas of the users to be managed.

     ![image-20240227-145443.png](/__attachments/a_2586ba323cd051ab0f71c1a12afcba5c235b0de101dafc60a9cc7805d62c4547/image-20240227-145443.png?cb=77a949bbce79bbe1e9b7bbb10b825e8d)
6. Click on **Save**.

Based on the defined validity, the user will be able to manage users personas within the specified scope, with the specific personas from its Self Service Portal.

[*See Self-Service Portal documentation*](https://docs.trustbuilder.com/tb-io/self-service-portal.md)

---
language: "en"
---
# Developers documentation

* [APIs](https://docs.trustbuilder.com/tb-io/apis.md)
* [SDKs](https://docs.trustbuilder.com/tb-io/sdks.md)

---
language: "en"
---
# Digipass DB adapter

The Digipass DB Adapter allows TrustBuilder to use strong authentication using a Digipass token. This token can be a hardware token or a software token.

The Digipass DB adapter uses a specific database schema. A schema for MySQL and Oracle are available.

The Digipass DB adapter will try to authenticate a user and manage the tokens assigned to a user. Two scenarios are possible:

1. You store the user information in the database.

2. You have a user repository (identity store) and will use that repository to store your user data.

In case of scenario 1, you will need the PERSON table (see below). In case of scenario 2 (the default) the PERSON table should not exist. Inserting data and updating data in the PERSON table is not part of the Digipass DB adapter.

## Database Schema

All the token information will be stored in a database. The structure of this database is explained in this section and is part of a generic authentication model. The database has the following tables for Digipass:

* PERSON (optional)

* AUTH_PRINCIPAL

* TOKEN

Table PERONS has the following columns:

* ID: The primary key

* USERID

* FIRSTNAME

* LASTNAME

* ... (depending on the data you want to store about a user in the database)

Table AUTH_PRINCIPAL has the following columns:

* PRINCIPAL: if a customer already has an identity store, the type will be a VARCHAR. If the customer does not have an identity store, the type will be an INT referencing to the PERSON(ID) column.

* AUTH_ID: references to the TOKEN(ID) column. However, no foreign key constraint will be made to the TOKEN table because AUTH_ID will hold a reference to multiple tables. If Digipass is the only authentication mechanism, then a foreign key constraint can be made between this column and the AUTH_ID column.

* AUTH_TYPE: Will contain the table name where the authentication information is found for this user. For Digipass, this will contain the value 'TOKEN'.

* LOGINID: The id used to login to the application.

* LOGIN_POLICY: A reference to the login policy that should be used. We do not supply means of checking the LOGIN_POLICY. This should be handled separately.

* STATUS: Will contain the status of this authentication row. At the moment, we have 2 statuses: enabled and disabled.

Table TOKEN has the following columns:

* ID: The primary key of the table

* SERIALNR: Will contain the Digipass token serial number.

* DPBLOB: Will contain a base64 encoded string containing the Digipass token blob.

* APPLICATION: Will contain the application to which this Digipass token blob applies.

* DPMODE: Will contain the Digipass token blob mode.

* DPTYPE: Will contain the Digipass token type.

* QABLOB: Will contain the Questions and Answers blob.

* STATUS: Will contain the status of the token.

### Configuration

The DigipassDB adapter allows you to configure the following:

* The JDBC Adapter that will be used to connect to the external database. This parameter is required.

* The Vacman controller kernel parameters. For more information on the kernel parameters: see the "VACMAN Controller Product Guide". The default values are recommended in most situations.

### Request - API (Administration)

**Import DPX**

This is not part of the Digipass DB adapter but is required to import tokens into the database. The class that imports tokens from a DPX file can be found in the TrustBuilder config jar: be.securit.trustbuilder.tools.DigipassDbDpxLoader.

This class takes one argument: the path to a properties file. The properties file has the following keys:

* type: token

* dpxfile: The (absolute) path to the DPX file you want to import

* key: The key of the DPX file

* db.driver: The database driver

* db.url: The database URL

* db.password: The database password

* applmapping1\>: These optional fields allow you to map an application in the DPX file to an application in the database. If for instance you specify: "applmapping1=APPL 1, banking", all the tokens of APPL 1 in the DPX will be stored with application "banking" in the database. The index starts at 1, is ascending and no gaps are allowed. If not specified, the applications are stored as the application specified in the DPX file.

* appltoimport: A comma separated list of applications in the DPX file you want to import. If not specified, all applications are imported.

* activation*code*file: The path to the file where the activation codes of the tokens are stored. This file is supplied with the DPX file.

The Digipass Kernel parameters can also be specified. See 'VACMAN Controller Product Guide' for more information. Possible properties:

* IdentificationTimeWindow

* SignatureTimeWindow

* GMTAdjustment

* CheckChallenge

* IdentificationThreshold

* SignatureThreshold

* CheckInactiveDays

* DeriveVector

* SynchronizationWindow

* OnlineSignature

* EventWindow

* HSMSlotId

* StorageKeyId

* TransportKeyId

* StorageDeriveKeys0

* StorageDeriveKeys1

* StorageDeriveKeys2

* StorageDeriveKeys3

Take great care when specifying the Digipass Kernel parameters. Under most circumstances, you should not alter the default values.

**Link Token Request (digipassDBLinkTokenRequest)**

This request will allow you to link a user to a token.

* Application (String): required.

* Serial number (String): required.

* Loginid (String): required.

* Principal (String): required.

* Login Policy (String): optional.

* Token (Boolean): optional. Defaults to true (single token)

* User (Boolean): optional. Defaults to true (single user)

**Unlink token request (digipassDBUnlinkTokenRequest)**

This request will unlink a user from a token.

* Serialnr (String): Optional.

* Application (String): Required.

* Loginid (String): Required.

* Principal (String): Optional. Required if a token can be linked to multiple users.

**Unlock token request (digipassDBUnlockTokenRequest)**

This request will unlock a tyoken from a user for a specific application.

* Application (String): required

* Serialnr (String): optional

* Principal (String): optional

* Loginid (String): required

* Randomnr (String): required.

**Change static password request (digipassDBChangeStaticPasswordRequest)**

This request will change the static password of a token.

* Application (String): required.

* Loginid (String): optional.

* Serialnr (String): required.

* Principal (String): optional.

* Pwd1 (String): required.

* Pwd2 (String): required.

**Delete Token request (digipassDBDeleteTokenRequest)**

This request will delete a token.

* Application (String): required.

* Serialnr (String): required.

**Free Token Request (digipassDBFindFreeTokenRequest)**

Find the first token with status 0 (free).

* Application (String): required.

* Type (String): optional.

**Find Tokens Request (digipassDBFindTokensRequest)**

Find the tokens attached to the principal.

* Principal (String): The principal you want the tokens for.

**Find Users Request (digipassDBFindUsersRequest)**

Find the principals linked to a token.

* Serialnr (String): required.

**Force Pin Change Request (digipassDBForcePinChangeRequest)**

Trigger a force pin change.

* Application (String): required.

* Serialnr (String): required.

**Reset Static Password (digipassDBResetStaticPasswordRequest)**

Resets Digipass Static PIN.

* Application (String): required.

* Serialnr (String): required.

**Reset Token Request (digipassDBResetTokenRequest)**

Resets a Digipass token.

* Application (String): required.

* Serialnr (String): required.

**DB Sync Token Request (digipassDBSyncTokenRequest)**

Synchronize a Digipass token.

* Application (String): required.

* Serialnr (String): required.

* Pwd1 (String): required.

* Chl1 (String): required.

* Pwd2 (String): required.

* Chl2 (String): required.

**Token Info Request (digipassDBTokenInfoRequest)**

Retrieve the Digipass token info.

* Application (String): required.

* Serialnr (String): required.

### Request - API (Authentication)

**General Remark**

All authentication requests will use the following parameters:

* Loginid (String): required.

* Application (String): required.

* Serial number (String): optional.

* Principal (String): optional.

Application and login id are required as they are the minimum information you need to login to an application. The serial number is optional if only one token can be assigned to one user (single user). In that case, the serial number will be retrieved using login id and application. An error will be generated if more than one token is found. Principal is also optional but only if a user can be linked to one token (single token). Otherwise we have no means of finding which user is trying to generate the challenge. An error will be generated if the principal was not found.

**Generate Challenge Request (digipassDBGenerateChallengeRequest)**

This request will generate a challenge for challenge response authentication.

* Loginid (String): required.

* Application (String): required.

* Serial number (String): optional.

* Principal (String): optional.

**Authenticate Token (digipassDBAuthenticateTokenRequest)**

Will perform challenge/response or response authentication.

* Loginid (String): required.

* Application (String): required.

* Password (String): required.

* Challenge (String): optional but required for challenge/response authentication (see Generate Challenge Request)

* Serialnr (String): optional.

* Principal (String): optional.

**Verify Signature (digipassDBVerifySignatureRequest)**

Will perform a signature verification.

* Signature (String): Required.

* SignedFields (String array): Required.

* Loginid (String): Required.

* Application (String): Required.

* Serialnr (String): Optional.

* Principal (String): Optional.

#### Response - API

**Common Properties**

All responses have three properties in common:

* **status** Status flag indicating whether the response is ok (0) or not (1)

* **substatus** Response specific number indicating what the problem was

* **message** Response specific message in case there was a problem (can be null)

Some requests return more than these three common properties and are listed below.

---
language: "en"
---
# DigipassService

|----------------|------------------------------------------------------------|
| **Name**       | DigipassService                                            |
| **Class Path** | `be.securit.trustbuilder.service.digipass.DigipassService` |
| **Versions**   | 9 10 11                                                    |

## Overview

The `DigipassService` provides functionalities for managing Vasco Digipass tokens, including activation, authentication, validation, and signature processing. It interfaces with secure messaging protocols and database storage for handling secure authentication workflows.

*** ** * ** ***

## Available Functions

### `setJdbcUrl(String jdbcUrl)`

Sets the JDBC URL for database connection.

* **Parameters:**

  * `jdbcUrl` (`String`): The database connection URL.

*** ** * ** ***

### `setUsername(String username)`

Sets the database username.

* **Parameters:**

  * `username` (`String`): The username for authentication.

*** ** * ** ***

### `setPassword(String password)`

Sets an encrypted or plain password for database authentication.

* **Parameters:**

  * `password` (`String`): The password to store.

*** ** * ** ***

### `setDataSource(DataSource dataSource)`

Assigns a data source and tests the connection.

* **Parameters:**

  * `dataSource` (`DataSource`): The database source.

*** ** * ** ***

### `generateChallenge(String serialNumber, String mode): String`

Generates a Digipass challenge for authentication.

* **Parameters:**

  * `serialNumber` (`String`): The serial number of the token.

  * `mode` (`String`): The Digipass mode.

* **Returns:**

  * `String`: The generated challenge.

*** ** * ** ***

### `authenticateWithChallenge(String serialNumber, String mode, String challenge, String password): DigipassAuthentication`

Authenticates a user against a challenge.

* **Parameters:**

  * `serialNumber` (`String`): The Digipass serial number.

  * `mode` (`String`): The Digipass mode.

  * `challenge` (`String`): The generated challenge.

  * `password` (`String`): The user's response.

* **Returns:**

  * `DigipassAuthentication`: An object containing authentication details.

*** ** * ** ***

### `mdlGenAuthRequest(String serialNumber, DigipassMdlSignOptions options): DigipassMdlSignRequest`

Generates an authentication request for signing.

* **Parameters:**

  * `serialNumber` (`String`): The Digipass serial number.

  * `options` (`DigipassMdlSignOptions`): Customization options.

* **Returns:**

  * `DigipassMdlSignRequest`: The authentication request.

*** ** * ** ***

### `mdlValidateSignature(String serialNumber, String signedMessage, String signature, int expirationTime): DigipassMdlSignReply`

Validates a signature generated from a signing request.

* **Parameters:**

  * `serialNumber` (`String`): The Digipass serial number.

  * `signedMessage` (`String`): The signed message.

  * `signature` (`String`): The user's signature.

  * `expirationTime` (`int`): Timeout duration.

* **Returns:**

  * `DigipassMdlSignReply`: Validation results.

*** ** * ** ***

### `validateOtp(String serial, String application, String otp)`

Validates a one-time password (OTP).

* **Parameters:**

  * `serial` (`String`): The serial number of the Digipass token.

  * `application` (`String`): The application name.

  * `otp` (`String`): The OTP to validate.

*** ** * ** ***

### `getFreeDigipass(String dpType): String`

Retrieves an available Digipass token.

* **Parameters:**

  * `dpType` (`String`): Type of Digipass.

* **Returns:**

  * `String`: The serial number of the available Digipass.

*** ** * ** ***

### `resetStaticPassword(String serialNumber)`

Resets the static password of a Digipass.

* **Parameters:**

  * `serialNumber` (`String`): The Digipass serial number.

*** ** * ** ***

### `getDigipassStatus(String serialNumber, String application): int`

Retrieves the current status of a Digipass.

* **Parameters:**

  * `serialNumber` (`String`): The Digipass serial number.

  * `application` (`String`): The application name.

* **Returns:**

  * `int`: The status code.

*** ** * ** ***

## **Summary**

The `DigipassService` provides core functionalities for:

* Managing Digipass tokens (activation, authentication, and validation).

* Processing secure transactions using Vasco's security mechanisms.

* Storing and retrieving Digipass information from a secure database.

This service is essential for implementing strong multi-factor authentication solutions.

---
language: "en"
---
# DomTai

Classname : `be.securit.trustbuilder.service.DomTai`

## Properties

* keySpec generated base64 encoded Key for the DomTai plugin in Lotus Notes

* charSet charset for the encryption (normally ISO-8859-1)

### Example

    DOMTAI = tb.getService("domtai service");
    var domtaiattr = DOMTAI.encrypt("some string");

---
language: "en"
---
# Dynamic Authorization

User Authorization is the act of taking a decision whether a user should get access and to a particular application, service provider, function, resource and/or record.

## About user authorization

User authorization is often confused with user authentication. Authentication is the act of knowing which user profile is trying to use a service. Many implementations grant a user access as soon as they are authenticated. This is of course a very coarse-grained model for access control.

TrustBuilder fosters the security model that is much more flexibel and fine-grained. In this model, being authenticated is a necessary but not sufficient condition to get access. And even 'being authenticated' has many flavours, e.g. how strong was the authenticated method used, how long ago did the authentication take place, etc. To maintain the level of confidence in the user authentication, TrustBuilder maintains User Sessions. Any access to a system, an application, a resource, a service provider or an API is determined separately. This is the act of 'authorization', namely evaluating a policy, within a given user session, and determining whether the user should get access in the given circumstances.

While the result of an authentication is a user session, the result of an authorization is a permit/deny decision. While a user session may be represented by an OIDC id-token in the client app, the permit/deny decision is typically represented by an OAuth2 access token or a XACML3 policy decision.

## Policy-based authorization

The act of authorising a user to access something and to do something, is fully policy-driven.

With Policy-Based Access Control (PBAC), we aim:

* To offer centralised policy management, whereby all policies and policy rules are governed and maintained in 1 place, as opposed of being 'implied' by different access control systems and applications

* To offer externalised fine-grained authorization, whereby policy decisions happen in 1 place, and not in every application

* To enable transaction authorization, i.e. not only authorization to access an application or a record, but also authorization at the transaction level, for every individual transaction

* To enable consent-driven authorization, i.e. to include the owner's consent before giving authorization to access a personal record.

The TrustBuilder PBAC model is built to achieve high levels of security, while offering security administrators maintenance at scale and offering users a frictionless environment. While the model embraces RBAC when needed, it avoids the pre-assignment of roles, groups, permissions and other access rights to users. It is this 'pre-assignment' that causes security administrators so many headaches: it is labour intensive, difficult to maintain on the long run, requires periodic attestation, and cannot be given in the hands of regular users.

Key elements of the TrustBuilder PBAC model are:

* Policy Engine with no-code declarative policies that take into account user profile attributes, user session attributes and context attributes

* Personas defined at user profile level and selected by the user during a user session

* Delegated Administration that push administration of user profiles and personas to the people that are very close to the user

* User sessions with a risk score that evolves during its lifecycle.

## Obtaining policy decisions

A user session has a lifecycle during which multiple authorization requests are made.  
![image-20220720-124927.png](https://docs.trustbuilder.com/__attachments/a_a291006c5ac10574c41fc3736d42f2c8db91325227885ace62b9d15df5f5575b/image-20220720-124927.png?cb=b92588144ea9594bc85198e26281d4cb)

Authorization will only be granted during a valid session: a valid session indicates that the user is recognised (identified with a user profile) and authenticated (proven that they are the holder) in some way. Further authorization requests may require the user to strenghten the authentication level (Step Up Authentication).

Whereas the Policy Decision Point is called upon when the user logs and gets a session, multiple access decisions may be made and returned during a single session. TrustBuilder returns such decisions in the form of an OAuth2 access token or as a XACML3 policy-decision result.

How to obtain an authorization (= access decision) from the Policy Engine (aka PDP) described on Policy Model ?

* either as direct request/response adopting XACML as protocol

* or token-based adopting OAuth2 as protocol.

## Why token-based authorization?

Token-based Dynamic Authorization has big advantages when implementing authorization at scale; access tokens offer scalability, performance and throughput and reduce the number of API calls for authorization.

### Scalability, throughput, privacy and security

1. embody a policy decision that can easily be checked by any PEP without further API calls to a policy engine (PDP)

2. enable intermediate hubs such as an API Gateway or Enterprise Service Bus, to act as PEP on behalf of the back-end API

3. can be reused and thus can be viewed as caching a policy decision, so that the policy decision does not need to be re-obtained for every back-endAPI call.

4. offer better privacy since they do not need to convey personal information throughout the API chain and can be made anonymous.

5. offer better security thanks to its short lifetime and its cryptographic protection compared to than mechanisms that are based on symmetric long-lived secrets such as service accounts, API keys and client-id/client-secrets that can easily become compromised.

#### Protect against man-in-the-middle

The downside of access tokens, however, is that could be intercepted and be replayed by adversaries. To protect against such man-in-the-middle attacks:

1. access tokens contain information about the requestor and the request so that their re-usability is severely constrained

2. access tokens are typically short-lived with refresh mechanisms to re-obtain fresh access tokens, possibly after re-evaluating the policy

3. access tokens can be revoked when a security compromise is suspected, but this requires a call to the introspection endpoint for real-time verification of the revocation status.

---
language: "en"
---
# EncryptionService

|----------------|-----------------------------------------------------|
| **Name**       | EncryptionService                                   |
| **Class Path** | `be.securit.trustbuilder.service.EncryptionService` |
| **Versions**   | 9 10 11                                             |

## **Overview**

The `EncryptionService` class offers cryptographic operations for encrypting, decrypting, hashing, signing, verifying, and securely handling passwords using various algorithms.

*** ** * ** ***

## **Available Methods**

### **Encryption \& Decryption**

#### `String encrypt(String cipher, String data, String encodingFormat)`

Encrypts the given data using the specified cipher.

* **Parameters:**

  * `cipher` (`String`): Encryption algorithm (e.g., `"AES"`, `"RSA"`).

  * `data` (`String`): The plaintext data to be encrypted.

  * `encodingFormat` (`String`): Output encoding format (`"base64"`, `"hex"`, `"y64"`).

* **Returns:**

  * `String`: The encrypted data in the specified encoding format.

*** ** * ** ***

#### `String decrypt(String cipher, String encrypted, String decodingFormat)`

Decrypts the given encrypted data.

* **Parameters:**

  * `cipher` (`String`): Decryption algorithm.

  * `encrypted` (`String`): Encrypted data.

  * `decodingFormat` (`String`): Format of the encrypted data.

* **Returns:**

  * `String`: The decrypted plaintext.

*** ** * ** ***

### **Hashing**

#### `byte[] hash(String hashAlg, byte[] message)`

Computes a cryptographic hash for the given byte array.

* **Parameters:**

  * `hashAlg` (`String`): Hashing algorithm (e.g., `"SHA-256"`).

  * `message` (`byte[]`): Data to hash.

* **Returns:**

  * `byte[]`: The computed hash.

*** ** * ** ***

#### `String hash(String hashAlg, String message, String encodingFormat)`

Computes a hash for a given string and encodes it.

* **Parameters:**

  * `hashAlg` (`String`): Hashing algorithm.

  * `message` (`String`): Data to hash.

  * `encodingFormat` (`String`): Encoding format (`"base64"`, `"hex"`, `"y64"`).

* **Returns:**

  * `String`: Encoded hash.

*** ** * ** ***

### **HMAC (Hashed Message Authentication Code)**

#### `String generateHMac(String cipher, String data, String decodingFormat, String encodingFormat)`

Generates an HMAC using the specified algorithm.

* **Parameters:**

  * `cipher` (`String`): HMAC algorithm (`"HmacSHA256"`, `"HmacMD5"`, etc.).

  * `data` (`String`): Data to be signed.

  * `decodingFormat` (`String`): Encoding format of input.

  * `encodingFormat` (`String`): Encoding format of output.

* **Returns:**

  * `String`: HMAC value.

*** ** * ** ***

### **Salted Hashing**

#### `String saltedHash(String algorithm, String password, String salt)`

Computes a salted hash using the specified algorithm.

* **Parameters:**

  * `algorithm` (`String`): `"SHA"` or `"SHA256"`.

  * `password` (`String`): User password.

  * `salt` (`String`): Salt value.

* **Returns:**

  * `String`: Salted hash in base64.

*** ** * ** ***

#### `boolean verifySaltedPassword(String password, String salt, String digest)`

Verifies if a password matches the salted hash.

* **Parameters:**

  * `password` (`String`): Plaintext password.

  * `salt` (`String`): Salt value.

  * `digest` (`String`): Hashed password.

* **Returns:**

  * `boolean`: `true` if password is valid, otherwise `false`.

*** ** * ** ***

#### `String retrieveSalt(String digest)`

Extracts the salt from a salted hash.

* **Parameters:**

  * `digest` (`String`): Salted hash.

* **Returns:**

  * `String`: Extracted salt.

*** ** * ** ***

#### `String generateSalt(int len)`

Generates a cryptographic salt of a given length.

* **Parameters:**

  * `len` (`int`): Desired salt length.

* **Returns:**

  * `String`: Base64-encoded salt.

*** ** * ** ***

### **Asymmetric Cryptography (RSA)**

#### `void setPKCS8EncodedKeySpec(String key)`

Loads a private key in PKCS8 format.

* **Parameters:**

  * `key` (`String`): Base64-encoded private key in PKCS8 format.

*** ** * ** ***

#### `void setRsaPublicKey(String key)`

Loads a public key in X.509 format.

* **Parameters:**

  * `key` (`String`): Base64-encoded public key in X.509 format.

*** ** * ** ***

#### `void setRsaPkcs8PublicKey(String key)`

Loads a public key in PKCS8 format.

* **Parameters:**

  * `key` (`String`): Base64-encoded public key in PKCS8 format.

*** ** * ** ***

### **Digital Signatures**

#### `String sign(String algorithm, String data, String decodingFormat, String encodingFormat)`

Signs a message using a private key.

* **Parameters:**

  * `algorithm` (`String`): Signature algorithm (e.g., `"SHA256withRSA"`).

  * `data` (`String`): Message to sign.

  * `decodingFormat` (`String`): Encoding format of the input.

  * `encodingFormat` (`String`): Encoding format of the signature.

* **Returns:**

  * `String`: Digital signature.

*** ** * ** ***

#### `boolean verify(String algorithm, String data, String signature, String decodingFormat)`

Verifies a digital signature.

* **Parameters:**

  * `algorithm` (`String`): Signature algorithm.

  * `data` (`String`): Original message.

  * `signature` (`String`): Digital signature.

  * `decodingFormat` (`String`): Encoding format of the signature.

* **Returns:**

  * `boolean`: `true` if valid, `false` otherwise.

*** ** * ** ***

#### `boolean verifyWithPublicKey(String algorithm, String publicKey, String data, String signature, String decodingFormat)`

Verifies a signature using a public key.

* **Parameters:**

  * `algorithm` (`String`): Signature algorithm.

  * `publicKey` (`String`): Base64-encoded public key.

  * `data` (`String`): Original message.

  * `signature` (`String`): Digital signature.

  * `decodingFormat` (`String`): Encoding format of the signature.

* **Returns:**

  * `boolean`: `true` if valid, `false` otherwise.

*** ** * ** ***

#### `boolean verifyWithCertificate(String algorithm, String certificate, String data, String signature, String decodingFormat)`

Verifies a signature using an X.509 certificate.

* **Parameters:**

  * `algorithm` (`String`): Signature algorithm.

  * `certificate` (`String`): X.509 certificate in Base64.

  * `data` (`String`): Original message.

  * `signature` (`String`): Digital signature.

  * `decodingFormat` (`String`): Encoding format of the signature.

* **Returns:**

  * `boolean`: `true` if valid, `false` otherwise.

*** ** * ** ***

### **Password Hashing**

#### `String bcryptHash(String password, String salt, int rounds, boolean php)`

Hashes a password using bcrypt.

* **Parameters:**

  * `password` (`String`): Plaintext password.

  * `salt` (`String`): Salt for hashing.

  * `rounds` (`int`): Cost factor.

  * `php` (`boolean`): If `true`, outputs PHP-compatible bcrypt hash.

* **Returns:**

  * `String`: Bcrypt hash.

*** ** * ** ***

### **Argon2 Hashing**

#### `String argon2Hash(String password, int saltLength, int parallelism, int resultLength, int memorySizeInKb, int iterations)`

Hashes a password using Argon2id.

#### `boolean argon2Verify(String password, String encodedHash)`

Verifies an Argon2 hash.

*** ** * ** ***

### **PBKDF2 Hashing**

#### `String pbkdf2Hash(...)`

Hashes a password using PBKDF2.

#### `boolean pbkdf2Verify(...)`

Verifies a PBKDF2 hash.

*** ** * ** ***

This service provides a robust suite of cryptographic functions for secure data processing.

---
language: "en"
---
# Endpoints

## Endpoint URL

An endpoint is uniquely identified by an endpoint URL:  

|--------------|-------------------------------------------------------------------|
| Request Type | Endpoint URL                                                      |
| SOAP         | http://\<host\>:\<port\>/\<context_root\>/soap/\<Workflow_ID\>    |
| XML          | http://\<host\>:\<port\>/\<context_root\>/xml/\<Workflow_ID\>     |
| HTML         | http://\<host\>:\<port\>/\<context_root\>/html/\<Workflow_ID\>    |
| GENERIC      | http://\<host\>:\<port\>/\<context_root\>/generic/\<Workflow_ID\> |
| OCSP         | http://\<host\>:\<port\>/\<context_root\>/ocsp/\<Workflow_ID\>    |

The parallel requests are limited to 100 requests. All requests above this limit will drop and a 503 Server busy will be returned.

### Endpoint Configuration

Normally the defaults are fine and you don't need this file, except if you want to tune a specific endpoint eg. ocsp or allow big attachments.  

|-----------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Variable                                      | Description                                                                                                                                                                         |
| maxRequestSize                                | Size in MB of request allowed to be sent through the servlet 0 for no restriction.                                                                                                  |
| requestTypeParameterName / requestTypeDefault | parameter acting as the requestType, and default that should be taken if it wasn't found.                                                                                           |
| parseHeaders                                  | true or false Do we want to parse the http headers sent to the TrustBuilder servlet. if set to true these headers will we placed into the RequestHeaders of the incomming resquest. |
| ocspResponderKeystoreType                     | Specific ocsp endpoint setting. PKCS12 or JKS Defines the type of keystore used.                                                                                                    |
| ocspResponderKeystoreFile                     | Specific OCSP endpoint setting. Absolute path to the store                                                                                                                          |
| ocspResponderKeystorePassword                 | Specific OCSP endpoint setting. Password of the store \[Base64\].                                                                                                                   |
| ocspResponderKeystoreAlias                    | Specific OCSP endpoint setting. Alias of the private key in the keystore used to sign the response. Only used when type is set to 'JKS'                                             |
| ocspResponderKeystoreAliasPassword            | Specific OCSP endpoint setting. Password of the private key in the keystore.                                                                                                        |

#### Request-api

Whenever a request comes into the workflow as an entry in your workItem it request will have a couple of attributes. These attributes are depending on the endpoint on which the request comes in. Note, the attributes are always there, but not necessarily filled in. The request object available as a real javascript object contains the following properties/function .

* headers: containing all headers

* cookies: containing all cookies

* parameters: containing all passed parameters (empty for every endpoint except html-endpoint), value is an array !!

* parameter('myparam'): function!! returning the value if there is only one value for a certain parameter, array in every other case

* body: string containing the body

* bodyAsXml(): function returning the body as an xml object (if it actually is one)

#### Response-Api

When sending something out via the FinalState property the engine requires a response the endpoint can understand.

This is where the tb.generateResponse comes in. This is a helper function requires the following parameters:

* body: whatever you want to have in the body of your endpoint, html/xml/soap

* headers: object key/value pairs rendered as headers in the endpoint

* cookies: object key/value pairs rendered as cookies in the endpoint (only applies to http protocol, not to cdas)

* status: number to be used as http statuscode

eg:

    var cookies = {
        "TbSession": {
            value: 'someIdentifier',
            maxage: '300',
            path: "/"
        },
        "RememberMe": {
            value: '1',
            maxage: '300',
            path: "/"
        },
    };
    var header = { "Content-type": "text/html", 'X-Application': 'Trustbuilder' };
    tb.generateResponse('\<html\>my doc\</html\>', headers, cookies, 200);

#### Endpoint Authorisation

These pages describe the authorisation mechanism applied to the TrustBuilder Endpoints. There are currently five HTTP endpoints within TrustBuilder (TB) being XML, SOAP, HTML, GENERIC and OCSP.Each endpoint consumes a different kind of request with its own authorisation structure.

The mechanism for authentication and authorization is the standard J2EE implementation where roles are defined in the deployment descriptor of the application and then mapped on the application server.

Not only can the endpoints be secured, but are some of the parameters of the request taken into account in the decision: config, workflow and RequestType. If none of these parameters are present (via HTTP headers, URL or Form values) the authorisation is applied on the default requestType on the condition that this is configured naturally.

Through services in the configuration of TrustBuilder it is possible to add an Radius and LDAP endpoint.

Many applications and network access management solutions use these interfaces for such requests. Now they can take advantage of the power of TrustBuilder's Policy and Workflow Engine to handle the requests independently from the actual repository containing the user and validation data.

The deployment descriptor (DD) is where the roles are defined. These roles are read by the application server upon installation of the application and can then be mapped to users and groups. These can be from ITIM or LDAP or any other mechanism that your application server provides. The destinations for authorisation and the authentication method are also defined in the deployment descriptor.

##### Security Roles

Roles are defined in the DD that are used by the following definitions to map the application to the container: WebSphere. Ultimately the security; users, credentials, groups, roles, are defined by the container these roles provide hooks to the container and need to be mapped on installation of TB.

    <security-role>
        <role-name>TrustBuilderRole\</role-name>
    </security-role>
    <security-role>
        <role-name>TrustBuilderAdmin\</role-name>
    </security-rol\>
    <security-role>
        <role-name>TrustBuilderAuditor\</role-name>
    </security-role>

##### Security Constraints

The constraints map the endpoint servlets to roles and transport restrictions securing SOAP, XML, HTML or Genric types of requests. The constraints are mapped to URLs so one constraint can be set for each request type or the trustbuilder/\* root could be constrained covering all the instances. The role-name elements map to security-role elements.

    <security-constraint>
       <web-resource-collection>
          <web-resource-name>XMLRequest</web-resource-name>
          <url-pattern>/xmlTrustBuilderRequest</url-pattern>
          <http-method>DELETE</http-method>
          <http-method>GET</http-method>
          <http-method>POST</http-method>
          <http-method>PUT</http-method>
          <http-method>HEAD</http-method>
          <http-method>TRACE</http-method>
          <http-method>OPTIONS</http-method>
       </web-resource-collection>
       <auth-constraint>
          <role-name>TrustBuilderRequestXML</role-name>
          <role-name>TrustBuilderRequestALL</role-name>
       </auth-constraint>
       <user-data-constraint>
          <description>SSL or MSSL not required</description>
          <transport-guarantee>NONE</transport-guarantee>
       </user-data-constraint>
    </security-constraint>

##### Authentication Configuration

For authorisation to function authentication needs to be performed. This is also specified in the web.xml file. Initially this is set to BASIC authentication but can be set to DIGEST or FORM.

    <login-config>
       <auth-method>BASIC</auth-method>
       <realm-name>TrustBuilder</realm-name>
    </login-config>

##### Websphere

The roles defined in the deployment descriptor of TrustBuilder (TB) must be mapped to users that are defined within WebSphere (WAS). This is performed at the application level within WAS and for it all to function application security needs to be enabled.

**Application Security Settings**

For the authentication that is setup within the web.xml file to function application authentication must be enabled in WebSphere.

For WAS 7 and WAS 8 this is set here:

    > Security > Global Security > Application Security > Enable application security 

**Creating Internal Users**

NB. This is only one way to create users in WAS for more information view WAS documentation.

Once TrustBuilder has been installed within WAS then the roles defined in the deployment descriptor(web.xml) need to be assigned to users within the organisation, however they are managed. WebSphere can use a number of resources for users and groups.

If using the internal federated repository then users can be seen here (in WAS 7 or 8):

    > Users and Groups > Manage Users 

**Mapping Application Roles**

To map the TrustBuilder roles created in the deployment descriptor (web.xml) enter the WAS administrative console and go here for WAS 7 and WAS 8:

    > Applications > Application Types > Websphere enterprise applications > trustbuilder > Security role to user/group mapping 

Within this page all the roles defined in the deployment descriptor with be visible. To map a role to users within WAS select the roles you wish to work with then click the Map Users or Map Groups buttons. On the following page search for the users or groups that are to be assigned to the selected roles. These users or groups define the credentials that are used when authenticating to the TrustBuilder endpoints and authorising to specific resources.

##### XSD Validation

This section describes how to configure XSD validation of requests for TrustBuilder. This can be used to validate transactions or portions of a request to TrustBuilder against a pre-written XSD file.

##### Configuration

In order to use the xsd validation the config file should contain the 'ValidationResource' element referencing an absolute path to a validation properties file.

This properties file contains the element to be validated against which XSD. For each type of request that must be validated the request type name and the name and location of the XSD file to perform the validation must be specified within the property file (requestValidation.properties).

An example property set for one element that is to be validated

    # requestValidation.properties
    TRAN1=/opt/securit/XSD/tran1.xsd
    TRAN1.element=TranData
    TRAN1.element.namespace=http://securit.be/stb 

|-----------------------------------|---------------------------|-------------------------------------------------------------------------------------------------|
| Name                              | Example                   | Description                                                                                     |
| validation.element                | transactionType           | Defines which element in the payload defines against which xsd this payload should be validated |
| validation.namespace              | <http://securit.biz/stb>  | Optional namespace of the element                                                               |
| xsd.home                          |                           | Optional absolute path containing xsd's defined for every type                                  |
| transactionType                   | transactionType.xsd       | The relative path from xsd.home to validate against                                             |
| transactionType.element           | Data (TransactionDataSet) | The name of the element that contatins the data that is to be validated                         |
| transactionType.element.namespace | URI                       | The optional namespace of the Data if needed                                                    |

##### Requests

Within each request that is sent to TrustBuilder the body will be searched for the validation.element, for instance a transactionType. The value of this element will be looked up with a relevant namespace if appropriate. Which will determine:

* If this type of request should be validated (ie. is there a key found in the properties file)

* The location of the XSD file to validate this request (dependent upon 1)

* The part of the request that should be validated (dependent upon 1)

##### Kerberos authentication

In order to enable kerberos authentication on an http endpoint the following steps is required. In TB*HOME a trustbuilder.properties should be created with the following parameters: (note: all paths are relative from TB*HOME) After modifying this file, a restart of trustbuilder is required.

    // krb5 config, eg. /etc/krb5.conf
    krb5Conf= 
    // login config, jaas configuration file containing the configuration for the kerberos modules
    krb5LoginConf=
    // module to use in the jaas configuration file (referrably using keytab)
    krb5Module=
    // if basic auth is permitted, not recommended
    krb5AllowBasic= 

Now trustbuilder will 'negotiate' with clients asking for a kerberos ticket.

An example krb5.conf could look like:

    [libdefaults]
            default_realm = TRUSTBUILDER

    [realms]
            TRUSTBUILDER = {
                    kdc = kdc01.trustbuilder
                    admin_server = kdc01.trustbuilder
            } 

Example jaas.config

    SignedOnUserLoginContext
    {
        com.sun.security.auth.module.Krb5LoginModule required debug = true
                tryFirstPass = true doNotPrompt = true
                principal = "HTTP/trustbuilder"
                storeKey = true useKeyTab = true keyTab = "/Users/koen/tb.keytab"
                debug = true;
    };

---
language: "en"
---
# Export and Download

Much of the the export functionality is provided with buttons that are local to the elements to be exported; beside a script, in the script editor and in the workflow console for instance. There are some main buttons such as **Export Configuration** that apply to a broader scope.

Another option for export is the **Export Changed** console which lists changes to files so that recent changes can be easily exported regardless of type.

*Export and Import buttons are only shown if a configuration is related to at least one TB Server and the authenticated user has the TBAGExporter role.*

*A list of all TB servers that a configuration is related to, and thus will be exported to, will be displayed before export.*

*With export there is also the option to export and restart. Export will just export the file and not reload it into the currently running engine.*

## Export Changed console

To access the export changed click the **Export Changed** button in the top right of in the configuration console. This button is only available if the configuration is related to at least one TB server.  
![image-20230425-145323.png](https://docs.trustbuilder.com/__attachments/a_09a38d7745560a5491b72f360eff66c1616738149bfc724cf34c57ef8886299c/image-20230425-145323.png?cb=5e58f1acf1e2ea76ac2d239ca5f9b442)

The Export Changed console shows changes to all files since the last export or the changes were last cleared. There are two sections that display the same data in different formats. **Changed Files** displays a list of the changed files in a table the **File Tree** shows the changed files as they are stored in the file system.

### Changed Files

The Changed Files tab shows a list of all the files that have changed since the last export or the list was last reset. This can be good to use if the type of file to be exported is known, or just the most recent changes are wanted. Every column can be sorted by clicking on the column header so that changes can be located by type of file, date, name, path etc. The column that is currently sorted is highlighted with a pink line and the arrow shows the sort direction.  
![image-20230425-145347.png](https://docs.trustbuilder.com/__attachments/a_edcbe4505567e5805159417f0f482b74549109b3f76f9aab340a18fd91317d6c/image-20230425-145347.png?cb=bea7cdb3d638e9d1bbd55719f9037fd6)
Here the table is sorted by updated date descending.

There is also a filter for each row. Click below the table header to reveal the table input fields. To filter a specific column type in the input field and the table data will be filtered.  
![image-20230425-145410.png](https://docs.trustbuilder.com/__attachments/a_16dab8fc62c46a2962a69be357e5e88faf993ce9d2af31bdd97498b25bf221a9/image-20230425-145410.png?cb=a0cc8af5c319f1882eeb253561ac54f9)
Here the table is filtered on Path by script.

To clear the filter either delete the text or click the X to the right side of the filter input field.

To export files from the Changed Files tab check the check boxes to the left of each row. If a directory is checked then all the files within that directory will automatically be checked. Also if a directory is un-checked then all the files within that directory are also un-checked. To select all files check the box that is found in the table header. Once files have been selected click the **Export Selected Files** button. The override properties form will then be displayed if applicable.  
![image-20230425-145442.png](https://docs.trustbuilder.com/__attachments/a_c952a78457f94317ee7b02adc49bd8c420c6b971484a6700d8149df473859678/image-20230425-145442.png?cb=3eae6ad06e3c379dde504ad491c7730e)
Here the layout directory has been selected and all files within that directory.  
![image-20230425-145521.png](https://docs.trustbuilder.com/__attachments/a_9db31aa9068e0bcd08e3ee7a604e45226eda088fc2a61a408f1bcbcc481e5784/image-20230425-145521.png?cb=288a4cb5c90a26be59469e1575d6e6c2)
Here a single file has been selected in the layout directory.

Clicking the **Clear all Changes/Reset** will clear the change list so that there are no changed files. Changes to files will restart.  
![image-20230425-145554.png](https://docs.trustbuilder.com/__attachments/a_5e4bb4b3ce7ca2e8714b9f7e7fab2c92a0e0682fa041602181c4df3ac9a4324f/image-20230425-145554.png?cb=71633c6214764a7e91990c460615a4a1)

#### Change File Tree

The File Tree tab displays all the files within the configuration directory and highlights those that have been changed with either blue or orange (blue represents an edit and orange an add action). Files are selected for export by checking the check boxes to the left of each directory or file. If a directory is checked or un-checked all the files within that directory are checked or un-checked. Directories can be collapsed using the arrows to the left of each directory node.  
![image-20230425-145611.png](https://docs.trustbuilder.com/__attachments/a_da6370dc3067e8ff6a33c11dbd62905cc89e34757b3bedec5126aff8e88ab123/image-20230425-145611.png?cb=467ccc657eeb30ff0370f14a0be56dd0)
Here the layout directory has been selected and all the files therein.  

![image-20230425-145632.png](https://docs.trustbuilder.com/__attachments/a_3a56e80b72d158d27f7717feba159c6d0970b646399f25f2cbf844c35b6a5bd5/image-20230425-145632.png?cb=33fd69555a2b4d367699d6652a80f290)
Here the layout directory is closed

Once files have been selected click the **Export Selected Files** button. The override properties form will then be displayed if applicable.

Clicking the **Clear all Changes/Reset** will clear the change list so that there are no changed files. Changes to files will restart.  
![image-20230425-145554.png](https://docs.trustbuilder.com/__attachments/a_5e4bb4b3ce7ca2e8714b9f7e7fab2c92a0e0682fa041602181c4df3ac9a4324f/image-20230425-145554.png?cb=71633c6214764a7e91990c460615a4a1)

### Export Configurations

A complete configuration can be exported by clicking the **Export Complete Configuration** button at the top of the configuration screen.

This will export the config.xml, all workflow, all workflow layout files, all workflow tests, all scripts and all templates that exist within this configuration.

The export will be made to all the TB servers. A list is first shown of the servers that will be exported to.

If there is a TB server that the configuration should not be exported to then return to the Configs \& Servers screen and break the relationship between the two.  
![image-20230425-145740.png](https://docs.trustbuilder.com/__attachments/a_5daa0f0cced3d3233553c84876e2a82dbf1dbf7e61fdf468e1cd7a41f327c2af/image-20230425-145740.png?cb=dd17649bec708415aa5188a62a4523a0)

A complete configuration can also be exported by individual TB Server from the Config \& Servers page. If a TB Server is related to a configuration there will be **Export** and **Restart** buttons available at the bottom of the TB Server box.

Click the **Export** button to export the complete configuration just to that server.  
![image-20230425-145749.png](https://docs.trustbuilder.com/__attachments/a_8919de9ca505137c12fe3e89fbcd24c13aed050c89e1aefd2cefd22034ae1ca4/image-20230425-145749.png?cb=1afe540d1a1ebeff81e32d9f027a42fe)

Configurations can also be exported to all servers from the servers screen. If a configuration is related to one or more servers then an **Export** button will show on the configuration block. Click this button to open the standard export screen.  
![image-20230425-145802.png](https://docs.trustbuilder.com/__attachments/a_1368f93c8157ea516fc34385a6877a2b4fde2d10da74b79527820c0cc1112da1/image-20230425-145802.png?cb=fa9260fb7b346c08d386d0d50ef669c2)

Additional options:

* **Export Only Configuration File** : There is an option to just export the configuration file. For instance if only the license has been updated. For this use the **Export Configuration Only** button found on the configuration tab. This will not export workflows, scripts, templates, properties etc. just the config.xml file.

  Note that an error may occur if only the configuration is exported and it refers to a new workflow that has not yet been exported.  
  ![image-20230425-145811.png](https://docs.trustbuilder.com/__attachments/a_ec55ca0379d893c66108327b5bff4b4138a19321a921d92c944d31e67405267f/image-20230425-145811.png?cb=d5623e9b63592e303f1d290023119e06)
* Cleaning TB_HOME on Export: When exporting the complete configuration from the configuration page using the **Export All** button there is the option on the export screen to clean TB*HOME. What this will do is to delete the contents of TB*HOME before exporting the new files.

  ![image-20230425-150133.png](https://docs.trustbuilder.com/__attachments/a_03ed1331cf23652aa66a74c653caeca58004cf0b582ca48a34e814c471b33cc8/image-20230425-150133.png?cb=9cb8466e1328ab5a281f4cbccfed5431)

Downloads:

* There are two ways that a complete configuration can be downloaded both intended for different purposes. **Download to Share** is intended to share files between different TrustBuilder Administrators (TBA) **Download for Export** is intended to be used to manually export to a TB_HOME via external means. Both these options result in a zip file.

  ![image-20230425-150145.png](https://docs.trustbuilder.com/__attachments/a_88a24a89e574a5825d4e3d94b248a2e7b888c56414e08417e3885cacf9e2ac84/image-20230425-150145.png?cb=5b167855bf48316b63acabd3abb05aa2)
  * When using Download to Share override properties and ignored,

  * When using Download for Export override properties as specified and populated.

Click either download button *(the Download for Export is only available if this configuration is relate to one or more servers)* at the top of the configuration screen then save the zip file which is named TB-\[NameOfConfig\]-\[yyymmdd\]-\[hhmmss\].zip  
![image-20230425-150159.png](https://docs.trustbuilder.com/__attachments/a_2b10991b5ea5b8c6c3b9809f6a35348f9d900a1cfa9be7e0a144064b495b1f3b/image-20230425-150159.png?cb=cdccd7b02541627b021ae377bc051cb3)

### Export Workflows

Single workflows can be exported from the workflow tab on the configuration page.

Check the box beside each workflow that is to be exported, then click the **Export Selected** button.

The file can just be exported by clicking the **OK Export** button or the **Ok Export and Restart** button can be used to export and reload the workflow.  
![image-20230425-150211.png](https://docs.trustbuilder.com/__attachments/a_723659e96eab9ce59178f7bebe5c8e5ba3587edc6676fdfbd4a1f2df2aecb434/image-20230425-150211.png?cb=49b49ae14b939b432f58974ce6fbdf89)

Workflows can also be exported from within the workflow console. Click the Export button (folder with up arrow) on the top right of the workflow editing screen. The TB Servers will be listed as usual.  
![image-20230425-150221.png](https://docs.trustbuilder.com/__attachments/a_01f39a2040bb61628087a2755163f6f06153dcd5693c1a4e61e8d9d641e1af91/image-20230425-150221.png?cb=664bd3e405c5a0dd07e67e0297bed213)

Download: Layout files can be downloaded directly from within the workflow console by clicking the download button (file with down arrow). This will start a download dialogue for the layout XML file.

This can then be used to distribute to other users if required. This is of course not needed if TBA is being used correctly as a web application as all users can use the same workflow.  
![image-20230425-150238.png](https://docs.trustbuilder.com/__attachments/a_15c27773867a294cfcd333be1c44ed46b39f7006210f73e04d599031d340bae8/image-20230425-150238.png?cb=052f43c9c0bf55b09696e9726351b606)

### Export Scripts

Scripts can be exported from the configuration screen by checking the box beside each script to be exported and then clicking the Export Selected button.

Scripts can also be exported directly from within the Script Editor by using the Export button in the top right corner of the Script Editor  
![image-20230425-150248.png](https://docs.trustbuilder.com/__attachments/a_81c84f74ff9c97ae07f934cc94435c9458224deccae6ce841fc92fb89e002803/image-20230425-150248.png?cb=d83d200be59293f1bcb9c6a2286a3ca2)

### Export Templates

Templates can be exported from the configuration screen by checking the box beside each template that is to be exported and then clicking the **Export Selected** button.  
![image-20230425-150258.png](https://docs.trustbuilder.com/__attachments/a_30f9afd550b1c4a75ee3f3e4a2f477db6c68f6c0b21ee6739493e1e918cdc507/image-20230425-150258.png?cb=38391304bd2620dcd0f85f1f3e881c63)

### Export Warning Messages

After export the TB engine will reload it's resources. If there are errors in configuration or scripts when the engine reloads these will be reported back to TBA and displayed in a list as a warning.

## Import

Where applicable items can be imported from TB Servers. This includes complete configurations, scripts, templates and workflows.

*If a configuration is related to more than one TB Server then a single TB Server must be selected to import from.*

### Import Configurations

Configurations can be imported from already established TB Servers with populated TB Homes.

For the import to be able to function the TB Server must have a management port enabled and listening.

To import a complete configuration including any present workflow layout and workflow test files click **Import** button on the TB Server box.  
![image-20230425-150318.png](https://docs.trustbuilder.com/__attachments/a_d9ae11ca590a8cafed22eb82161fdc94274159888ce829eea0cd0aacf8a315d3/image-20230425-150318.png?cb=a8470d04114c10ae818051cd418c9dbb)

When a configuration is imported this way it is automatically related to the TB Server that it is related to. It can be related to other TB Servers or the relationship broken with the original importing TB Server without effecting the configuration.  
If a TB Server is already related to a configuration the import will overwrite the current configuration within TBA

### Import Workflows

If you have received a workflow from an external source this can be added to the current configuration but uploading it.

Click the **Upload and Import Workflow** button on the workflows tab of the configuration screen. A new screen will be displayed with a form.  

|         Field Name          |                                                                              Description                                                                              | Is Required? |
|-----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|
| Layout File Name            | This is the name of the XML file that will be created by TBA which is a representation of the workflow.                                                               | yes          |
| Workflow ID                 | This ID will be used by the configuration to reference the workflow                                                                                                   | yes          |
| Select Workflow File        | Here select the workflow.xml file that you have from your local machine.                                                                                              | yes          |
| Select Existing Layout File | If a layout file has also been supplied with the workflow.xml file this can also be uploaded. This will automatically format the layout of the workflow to this file. | no           |

![image-20230425-150347.png](https://docs.trustbuilder.com/__attachments/a_b22aa8ac42f4a7246b6d6f4fac0efba318a2acbdb416033baf330644feeda0c9/image-20230425-150347.png?cb=aa0990d3b6b1877eb51a42216bec5b2b)

If no layout file is supplied then the workflow will be converted by TBA as per a usual import.

If there is a layout file already within the folder, in TBA, related to this configuration then that will be used if no layout file is supplied.

Once the Import button is clicked then the workflow will be uploaded and the workflow console screen displayed with the new workflow.  
![image-20230425-150356.png](https://docs.trustbuilder.com/__attachments/a_359984329529179b6967410b4036ba3677830d6bb20f7532c6b018fac56dfc8b/image-20230425-150356.png?cb=9697fa36f4b769e2a635f406f65fb9d9)

* Import from TB Server → To import from a TB Server click the **Import** button beside the relevant workflow.

  A new screen will then be displayed with a form to select the TB Server to import from. As this is a previously created or imported workflow the layout file name is already known.

  ![image-20230425-150403.png](https://docs.trustbuilder.com/__attachments/a_57b44d83347d9ac287dac10b3f0a616ea6c9df5f2e264786e1e849967395d5b1/image-20230425-150403.png?cb=8955824fb8ccfb8809e4d0fd6d445462)

  Once the desired server is selected click the Import button and the workflow console will be opened with the imported workflow.
* Importing without Layout File → For any imported workflow to be used within the TrustBuilder Administrator it must have a layout file that represents the workflow in a graphical manner. If an imported workflow is imported without a layout file the option to create a layout file will be provided.

  ![image-20230425-150412.png](https://docs.trustbuilder.com/__attachments/a_b0c0a7f005fe9dc41c613c1b3a3f6210d9d3d742dc9d4ed70edb0d4a1988346c/image-20230425-150412.png?cb=1c4d0e3233e1008c49f09105b6bf5b7d)

  Click the **Convert to Layout** button and a form is presented, click the Import button to import the workflow and the workflow console will be displayed:

|         Form Field          |                                                                                  Description                                                                                   | Required |
|-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
| Layout File Name            | Name of the layout file that is to be created                                                                                                                                  | yes      |
| Select Existing Layout File | If a layout file has been provided it can be uploaded from the local machine. If it is valid this layout file will be used to arrange the workflow activities and connections. | no       |

![image-20230425-150420.png](https://docs.trustbuilder.com/__attachments/a_15e032521ef71d2032ef2a0101c508d2834606b91380c71df386e512f4c06100/image-20230425-150420.png?cb=f31198e398d72541b6a0f9c5c10d2c61)

### Import Scripts

Scripts can be imported from a related TB Server. If a script is imported then it overwrites the current script in TBA.

If there is more than one server the the desired server to import from must be selected.  
![image-20230425-150438.png](https://docs.trustbuilder.com/__attachments/a_df22bbcfc68312bd65252a94146a382b1337864e8a2a17463e3dd92f40b11377/image-20230425-150438.png?cb=3f1ea7346fdd8aade8014930334b1dd6)  
![image-20230425-150448.png](https://docs.trustbuilder.com/__attachments/a_4e839436b7e6ee26716dbb7213ff969f80e210878ea4d8490a75aab9cfdf96e0/image-20230425-150448.png?cb=f2d28451290cd1adae964fd1dd117470)

There is also the option to import all the scripts from one TB Server by clicking the **Import All Scripts** button.  
![image-20230425-150457.png](https://docs.trustbuilder.com/__attachments/a_027f09bf93f7d50610e0b8f4dec0b04a9145a512f498520eab0308f70d462479/image-20230425-150457.png?cb=bcf15473954be5674d0fdc90335ff156)

### Import Templates

Templates can be imported from a related TB Server. If a template is imported then it overwrites the current template in TBA.

If there is more than one server the the desired server to import from must be selected.  
![image-20230425-150509.png](https://docs.trustbuilder.com/__attachments/a_68df57858479e71b23d3dbce3ab9bf9e6b0fc46eb6a05051b9322d3b12a57f88/image-20230425-150509.png?cb=7b663ea27b3f227edde83f2f9be9edb6)

There is also the option to import all the scripts from one TB Server by clicking the **Import All Templates** button.  
![image-20230425-150517.png](https://docs.trustbuilder.com/__attachments/a_aca14bcc77a81c1025f1ba99cb63ea27967411ba7d7095097c55a0f500d9fa38/image-20230425-150517.png?cb=2ee6c7e19785c78ccdaffb35aeca2431)

## Overriding

Adapter elements defined in a configuration can be overridden by properties defined in a separate properties file.

This allows for different environments to use the same configurations with environment sensitive settings overridden for each specific server.

For instance if there are two environments dev and test. They both used a JDBC adapter but the datasource names are different in each environment.

The datasource element of the JDBC adapter can be overridden so each environment references the correctly named datasource yet the same configuration and the same adapter are used in both.

When data is overridden the values that are to be used are requested on export with a form for each TB Server that is to be exported to.

### Overriding Adapter Elements

Individual settings of an adapter can be overridden by simply checking the override option beside each label on the adapter form:  
![image-20230425-150844.png](https://docs.trustbuilder.com/__attachments/a_61534535f921845808051ff51e0b183c4dca24421054d3863a21fb3596c11bdc/image-20230425-150844.png?cb=b83ed9a8c5d553607e63e77e875e94c3)

*If Override is checked any values in the form will be overridden*

When exporting the following form is displayed. Each overridden field will be listed as a form input so that the value that is to be used for each server can be entered.

The adapter property takes the name of adapterID.field(server name).

The server name is only present when a server element is being overridden such as an http server or ldap server. Due to the fact that there can be multiple servers.  
![image-20230425-150903.png](https://docs.trustbuilder.com/__attachments/a_86cd85704d4e254d74de810463eb611e20c51400d4a77ea75871cf93f6e478c4/image-20230425-150903.png?cb=e9ffa38e8c5d8b797005a0ac79db3cc6)

The form is validated before submitting. No override fields are mandatory but numeric fields must have a numeric value, if not the validation fails:  
![image-20230425-150910.png](https://docs.trustbuilder.com/__attachments/a_5eafc5d0ecd6566fde8c0eda3f6da9cf75711cb87ce49ab608c1fc8c082a2b4c/image-20230425-150910.png?cb=beef174a2be58e0430d0b2fb23de19e5)

For boolean the options are restricted to true or false and for lists (enum) the appropriate values are displayed in a select box.  
![image-20230425-150918.png](https://docs.trustbuilder.com/__attachments/a_9295e4f6ea876b3567aec1c44d6a2f238e05f96f727aeb5153d47847de07cbc2/image-20230425-150918.png?cb=21f2969c8b639d87d05afeb1dd3526e5)

On export the config-override.properties file is created and populated with the provided values for each TB Server.

    ##Override properties each property is in the format of adapterID.field so if there is more than one HTTP adapter properties can be overridden individually. 
    simpleHTTP.Port-number=8080
    simpleHTTP.AllowOtherHosts-boolean=true
    simpleHTTP.Address=10.23.45.80
    simpleHTTP.SecurityProtocol-enum=sslv3
    simpleHTTP.ServerRequestAttempts-number=2 

### Overriding Components

Component values can also be overridden when it is configured. In the same manner for adapters check the Override check box beside the input field that should be overridden.  
![image-20230425-151021.png](https://docs.trustbuilder.com/__attachments/a_4a06b37bfab93636e7d19425ab761af38c80c0a35f868b82cfc6ff170a0bed1a/image-20230425-151021.png?cb=16e8c15c66a786b08b44d92114c56618)

When the configuration is exported the override properties form will be displayed with the fields named after the component id and property label. For instance if there is a component with an id of idHub with a property of Username that is overridden then the override form will contain a field idHub.Username. If the component is de-configured the override properties are removed.  
![image-20230425-151033.png](https://docs.trustbuilder.com/__attachments/a_6f31b86b8cd5c3de8390c4a977f947f094b6ef22dfd773eb80c95c1d9e3988ab/image-20230425-151033.png?cb=12f64513b85489954f9a309e694c60f6)

### Persisting Override Properties

When the values for override properties are specified these are automatically saved to the database related to the specific server. When another export is made to the same server the override properties are pre-populated with the previous values so they do not need to be entered every time an export is made.  
![image-20230425-151043.png](https://docs.trustbuilder.com/__attachments/a_f3ed4e1e540eedf0d20b6824a6ea66a946eaea9ef5ec579726375ebd3f1c51db/image-20230425-151043.png?cb=28d1af52a3421d47c8446f5c78df2660)

The saved values can also be used when downloading the complete configuration for export using the **Download for Export** button. If there are servers that have values then a select box is shown listing the servers whose values can be used. Selecting a server populates the fields and the override properties are processed in the traditional manner using those values.  
![image-20230425-151052.png](https://docs.trustbuilder.com/__attachments/a_ca1d1178c80639b5058c97af88fffe9b0645f72030a8bbfedd6ffd29e4bffe61/image-20230425-151052.png?cb=ec63f005b99d7ac977dd85503676410d)

---
language: "en"
---
# Gemalto adapter

The GemaltoAdapter allows TrustBuilder to send various requests to a Gemalto server. As the Gemalto server is an HTTP server, the GemaltoAdapter re-uses most of the default HttpAdapter behaviour.

## Configuration

**Runtime parameters**

As the Gemalto reuses most of the HTTP-adapter settings, please read HTTP-Adapter chapter.

**Session Authentication**

In addition to the regular HttpAdapter server options, configuring a Gemalto server includes the (optional) step of specifying username and password (plain text) to create Gemalto sessions.

### Workflow Settings

A request for the adapter is prepared by specifying the following properties/scripts in the adapter activity:

* Input Property: the variable containing the instructions the adapter have to execute

* Output Property: the variable the adapter will store the response in after execution

* Before Adapter Script: script that will be executed before calling the adapter

* After Adapter Script: script that will be executed after the adapter fulfilled its task

#### Request - API

Identical to HTTP Adapter

#### Response - API

Identical to HTTP Adapter

#### Response Codes

Identical to HTTP Adapter

---
language: "en"
---
# GeoIpService

|----------------|------------------------------------------------------|
| **Name**       | GeoIpService                                         |
| **Class Path** | `be.securit.trustbuilder.service.geoip.GeoIpService` |
| **Versions**   | 9 10 11                                              |

## Overview

The `GeoIpService` provides functionality for resolving IP addresses to geographic locations using a GeoIP database. It allows for loading a database file and performing lookups to retrieve city-level location information.

*** ** * ** ***

## Available Functions

### `setDatabaseFileLocation(String databaseFileLocation)`

Sets the location of the GeoIP database file and initializes the database reader.

* **Parameters:**

  * `databaseFileLocation` (`String`): The file path of the GeoIP database.

* **Exceptions:**

  * Throws `RuntimeException` if the file cannot be read.

*** ** * ** ***

### `resolveIpToLocation(String ip): String`

Resolves an IP address to a geographic location.

* **Parameters:**

  * `ip` (`String`): The IP address to look up.

* **Returns:**

  * `String`: A JSON string representing the resolved location details.

  * `{"error" : "invalid IP"}` if the provided IP address is invalid.

  * `{"error" : "Not found"}` if no location data is found for the IP.

  * Throws `RuntimeException` if there is an issue reading the database.

*** ** * ** ***

## **Internal Components**

*(For internal processing, not intended for direct use.)*

* `GeoDatabaseReaderFactory`

  A factory interface for creating `DatabaseReader` instances.

* `DatabaseReader databaseReader`

  The MaxMind `DatabaseReader` instance used to look up IP addresses.

*** ** * ** ***

## **Summary**

The `GeoIpService` allows applications to:

* Load a GeoIP database file.

* Perform city-level lookups for given IP addresses.

* Handle invalid or missing IP data gracefully.

This service is essential for integrating geographic IP resolution into security or analytics workflows.

---
language: "en"
---
# Getting started

* [Register your first user](https://docs.trustbuilder.com/tb-io/register-your-first-user.md)
* [Creating Rules and Policies](https://docs.trustbuilder.com/tb-io/creating-rules-and-policy.md)

---
language: "en"
---
# Hosted Login

TrustBuilder comes with pre-configured end-user journeys to manage their security. A journey is an end-to-end workflow invoked by an end user or device. TrustBuilder offers a whole suite of templates for the security aspects of the user journey, including registration, identification, authentication, and authorization. These templates can be customized so as to blend the security user journey into the journeys you are building for your apps.

In designing the authentication experience for your application, you can choose between Hosted Login or native login. To implement native login in a mobile app, please refer to [TB.Identity SDK](https://docs.trustbuilder.com/tb-io/tb-identity-sdk.md). To enable a common, universal login experience across all your apps and web pages, and to ensure top-level security for managing credentials, TrustBuilder offers Hosted Login.

## Hosted Login

TrustBuilder Hosted Login defines your login flow, including multi-factor authentication and credential lifecycle management. Each time a user needs to prove their identity, your applications redirect to Hosted Login and TrustBuilder will do what is needed to guarantee the user's identity.

By choosing TrustBuilder Hosted Login, you don't have to do any integration work to handle the various flavors of authentication. You can start off using a simple username and password. You can also add other features such as social login and multi-factor authentication (MFA). All of this is dynamic and adjustable in real-time without requiring application-level changes because all functionality is driven by the web pages served by TrustBuilder Hosted Login. Your application will benefit from any improvements TrustBuilder makes in the login flow without the need for you to change your code.

TrustBuilder Hosted Login lets you create a consistent, branded login experience by customizing the login page appearance and behavior starting the procedure and playground on [TrustBuilder Web Component Docs](https://web-components.trustbuilder.io/). For more advanced use cases, you can change the code of each page using the TrustBuilder Web Components.

### Pros \& cons of Hosted Login

With Hosted Login, users are redirected to a central login domain when they try to login. Afterwards, they are redirected back to your app. You can find an example of this experience with Google's G-Suite: no matter which service you are trying to access such as Gmail, Google calendar, or Google docs, you will always be redirected to [https://accounts.google.com](https://accounts.google.com/) for login and once you successfully log in you are redirected back to the calling app.

Conversely, a native login flow does not redirect the user somewhere central. The login experience is served by each app and web page individually, without redirecting the user to another domain. The credentials are then sent to the authentication provider for authentication. In a web app, this represents a so-called cross-origin request.

#### SSO across apps

Hosted Login provides SSO out-of-the-box for all your apps and web pages. With native login you'd have to collect the user credentials in an application served from one origin and then send them to another origin, which can present certain security vulnerabilities, including the possibility of a phishing attack. Furthermore, with native login you would have to manage the dangers of cross-origin attack vectors.

#### Consistency and Maintenance

Hosted Login offer a single and therefor consistent UX to your users and to your developers. With native login you must implement more than one login page, namely one for each application that needs login. You will also have to maintain and manage these pages. Besides the extra effort it can also introduce inconsistencies which results in bad UX.

#### Security risks

Hosted Login is intrinsically more secure than native login. Authentication takes place over the same domain, eliminating cross-origin requests. Cross-origin authentication is inherently more dangerous. Collecting user credentials in an application served from one origin and then sending them to another origin can present certain security vulnerabilities. Phishing attacks are more likely, as are bucket brigade attacks. Hosted Login does not send information between origins, thereby negating cross-origin concerns.

Self-coded user agents are unsafe for third parties and the authorization grant and end user credentials are exposed to the app. As a consequence, this data is left vulnerable to recording or malicious use. Even if the app is trusted, allowing it to access the authorization grant as well as the user's full credentials is unnecessary. This violates the principle of least privilege and increases the potential for attack.

## TrustBuilder Template Library

TrustBuilder offers a suite of templates (so-called Default Templates) for Hosted Login and the Self-Service Portal. The templates for Hosted Login are built using Web Components, which are covered by this document.  
The procedure to engage and customize the Web Components can be found on [TrustBuilder Web Component Docs](https://web-components.trustbuilder.io/), which includes "Try it out" playgrounds to test out your customization.

Note that the library of Default Templates supplied by TrustBuilder and the custom versions you have created are found under Admin Portal \> Configuration \> Templates. You can link a default or a custom template to a set of invocation points in Admin Portal \> Settings \> Templates. This is the place where you indicate which of templates must actually be invoked by TrustBuilder during a user's journey. The template to supply username/password is linked via Admin Portal \> Identity Providers \> Edit section, since "username/password" is considered just one of the identity providers supported by TrustBuilder.

## About Web Components

Web Components introduce a set of web platform APIs as reusable, encapsulated HTML tags for use in web pages and web apps. They work across all common version and brands of browsers, and can be used with any JavaScript library or framework that works with HTML. For example, React, Vue.js, Angular and AngularJS support the use of Web Components. The fact that Web Components are framework agnostic, makes them future proof and reusable. Support for Web Components is present in Chrome and Safari since 2016, in Firefox since 2018, and in Edge since 2020. Backward compatibility with older browsers like Microsoft Internet Explorer 11 is also achieved using JavaScript-based polyfills.

According to [webcomponents.org - Discuss \& share web components](http://webcomponents.org/), Web Components introduce following concepts:

1. **Custom elements** - a set of JavaScript APIs that allow the creation of new HTML tags, improve existing ones, define custom elements behavior, and expand components built by other programmers so they best match the UI. Custom elements have their own semantics and markup and exist without third-party frameworks.

2. **Shadow DOM**- separates CSS and JavaScript and provides encapsulation. This way you can isolate the markup structure, style, and behavior of a custom element from other code on the page, making sure that different parts won't clash and simultaneously keeping the code clean. With the Shadow DOM API you can also attach a hidden DOM to a given element.

3. **HTML templates** -- used in the custom elements, the \<template\> lets you create markup templates with dynamic content which are not rendered right away at a page load. These can be further reused multiple times and are called upon during runtime. There is also the so called \<slot\> which facilitates how you manage the content of an element.

## TrustBuilder Web Components

The TrustBuilder library of Default Templates are built using TrustBuilder Web Components. These Web Components:

* are responsive and renderable by versions and brands of browsers and in-app browsers that are commonly used by end users

* can be rebranded in terms of colors, fonts, graphical elements

* can support other languages beyond English, including non-Western alphabets

* adopt security best practice.

The TrustBuilder Web Components should not be confused with a framework or a rendering library. TrustBuilder Web Components should rather be considered as:

* Low Level Browser APIs

* Standard Component Interfaces

* Framework-agnostic rich user experience

The TrustBuilder Web Components library introduce a suite of encapsulated HTML tags. For example, `<tb-idp-select/>` provides an off-the-shelf login panel that can be rebranded and further customized. This `<tb-idp-select/>` can be used in any JavaScript framework or library and works across all common versions and brands of browsers.

The following example shows how a customized login screen for a fictional company called Narrows:  
![image-20230602-093341.png](https://docs.trustbuilder.com/__attachments/a_b79709550b6194debff9e1e437277228f88d7487618dd4dbc9f789fd6c0a99cb/image-20230602-093341.png?cb=da0f576b9dd1d5338fca71ea7dc914ee)

The procedure and playground to customize the Default Templates for Hosted Login and let them blend with your design system is described on [TrustBuilder Web Component Docs](https://web-components.trustbuilder.io/). The playbook lets you tweak, configure, and preview every step of the customer authentication experience. From sign-up to password recovery, preview how your custom branding looks across different authentication flows.  
![image-20230602-095339.png](https://docs.trustbuilder.com/__attachments/a_89e5697bd5e3a7ea2f8e2b9cb1403e2539f7b97aaa785773d966864d710d2063/image-20230602-095339.png?cb=44db441e2bc308f106b80a3d0afeae41)

## Settings

### Location parameters

When specifying a location or a template, TB.Connect will include several parameters in the URL by default. Which parameters are included depends on the use case of the location. The locations can be defined in "Settings \> Authentication \> Templates"  

|                 Use case                  |                         Parameters                         |           Default Template Location           |
|-------------------------------------------|------------------------------------------------------------|-----------------------------------------------|
| Select IDP                                | code (code of the sp), comparison, authnmethod, relaystate | N/A                                           |
| ERROR                                     | code (error code)\[, idp (displayname of the idp)\]        | N/A                                           |
| LOGOUT                                    | code (logout status code)                                  | /idhub/authenticate/logout/                   |
| CONSENT                                   | ConsentID, Request_URI (\*)                                | /idhub/oidc/v1/authorize                      |
| SELFSERVICE                               | -                                                          | /idhub/selfservice/                           |
| RESET_PASSWORD                            | -                                                          | /idhub/resetpassword/                         |
| CHANGE_PASSWORD                           | -                                                          | /idhub/passwordchange/                        |
| REGISTER                                  | -                                                          | /idhub/register/                              |
| MOBILE_REGISTRATION                       | idpCode, idpName                                           | /idhub/admin/api/v1/mobileregistration (\*\*) |
| SAML_2_POST (template only)               | relaystate, destination, type, token                       | N/A                                           |
| OIDC_POST (template only)                 | destination, params                                        | N/A                                           |
| Login User/PW (location not configurable) | relayState, idpCode, authenticationContext, username       | N/A                                           |

\*: Redirect URL, was added in 9.5.0. Needs an active Consent Request

\*\*: POST Request

### Templates

In the templates you can apply customization on pages rendered by TB.Connect. You get the choice between loading a templating or to redirect to a predefined URL.

* **Select IDP** -- This is a redirect to the Select IDP Page

* **Password Login** -- This is a redirect to the Password Login Page

* **Duplicate Subject** -- This is a redirect to the Duplicate Subject Page

* **Authorisation Failed** -- This is a redirect to the Authorisation Failed Page

* **Error** -- This is a redirect to the Error Pages

* **Logout** -- This is a redirect to the Logout Page

* **Consent** -- This is a redirect to the Consent Page

* **Self Service** -- This is a redirect to the Self Service Page

* **Reset Password** -- This is a redirect to the Reset Password Page

* **Change Password** -- This is a redirect to the Change Password Page

* **Register** -- This is a redirect to the New User Registration Page

Possible error codes passed to the error page:

**ACCESS_DENIED**

internal code: ACCESS_DENIED

Message: Access denied

**ACCOUNT_BLOCKED**

internal code: ACCOUNT_BLOCKED

Message: Account is blocked

**AUTHN_FAILED**

internal code: AUTHN_FAILED

Message: The responding provider was unable to successfully authenticate the principal.

**CERTIFICATE_NOT_FOUND**

internal code: CERTIFICATE_NOT_FOUND

Message: A required certificate was not found

**INSTALL_NOT_OK**

internal code: INSTALL_NOK

Message: Installation is not completed, complete installation and retry

**INTERNAL_SERVER_ERROR**

internal code: essageKeys.INTERNAL_SERVER_ERROR

Message: Internal server error

**INVALID_ATTR_NAME_OR_VALUE**

internal code: urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue

Message: Unexpected or invalid content was encountered within a \<saml:Attribute\> or \<saml:AttributeValue\> element.

**INVALID_NAME_ID_POLICY**

internal code: urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy

Message: The responding provider cannot or will not support the requested name identifier policy.

**INVALID_PARAMETERS**

internal code: INVALID_PARAMETERS

Message: There are some parameters with invalid values in the request.

**MESSAGE_VALIDATION_FAILED**

internal code: MESSAGE_VALIDATION_FAILED

Message: The parsing of a third party message has failed.

**MISSING_PARAMETERS**

internal code: MISSING_PARAMETERS

Message: There are some parameters missing in the request.

**NO_AUTHN_CONTEXT**

internal code: NO_AUTHN_CONTEXT

Message: The specified authentication context requirements cannot be met by the responder.

**NO_AVAILABLE_IDP**

internal code: urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP

Message: Used by an intermediary to indicate that none of the supported identity provider \<Loc\> elements in an \<IDPList\> can be resolved or that none of the supported identity providers are available.

**NO_AVAILABLE_IDP**

internal code: NO_IDPS

Message: Used by an intermediary to indicate that none of the supported identity provider \<Loc\> elements in an \<IDPList\> can be resolved or that none of the supported identity providers are available.

**NO_PASSIVE**

internal code: urn:oasis:names:tc:SAML:2.0:status:NoPassive

Message: Indicates that the responding provider cannot authenticate the principal passively, as has been requested.

**NO_PROXY_SP**

internal code: NO_PROXY_SP

Message: No Gateway Service Provider found

**NO_SUBJECT**

internal code: SP_SUBJECT_NOT_FOUND

Message: There is no value present for the attribute used as subject for the Service Provider you are trying to access

**NO_SUPPORTED_IDP**

internal code: urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP

Message: Used by an intermediary to indicate that none of the identity providers in an \<IDPList\> are supported by the intermediary.

**PROXY_COUNT_EXCEEDED**

internal code: urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded

Message: Indicates that a responding provider cannot authenticate the principal directly and is not permitted to proxy the request further.

**REQUEST_DENIED**

internal code: REQUEST_DENIED

Message: The SAML responder or SAML authority is able to process the request but has chosen not to respond. This status code MAY be used when there is concern about the security contents of the request message or the sequence of request messages received from a particular requester.

**REQUEST_UNSUPPORTED**

internal code: urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported

Message: The SAML responder or SAML authority does not support the request.

**REQUEST_VERSION_DEPRECATED**

internal code: urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated

Message: The SAML responder cannot process any requests with the protocol version specified in the request.

**REQUEST_VERSION_TOO_HIGH**

internal code: urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh

Message: The SAML responder cannot process the request because the protocol version specified in the request message is a major upgrade from the highest protocol version supported by the responder.

**REQUEST_VERSION_TOO_LOW**

internal code: urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow

Message: The SAML responder cannot process the request because the protocol version specified in the request message is too low.

**RESOURCE_NOT_RECOGNIZED**

internal code: urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized

Message: The resource value provided in the request message is invalid or unrecognized.

**TOO_MANY_RESPONSES**

internal code: urn:oasis:names:tc:SAML:2.0:status:TooManyResponses

Message: The response message would contain more elements than the SAML responder is able to return.

**UNKNOWN_ATTR_PROFILE**

internal code: urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile

Message: An entity that has no knowledge of a particular attribute profile has been presented with an attribute drawn from that profile.

**UNKNOWN_PRINCIPAL**

internal code: urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal

Message: The responding provider does not recognize the principal specified or implied by the request.

**UNKNOWN_ARTIFACT_ISSUER**

internal code: UNKNOWN_ARTIFACT_ISSUER

Message: The issuer of a SAML artifact response could not be identified.

**UNKNOWN_SP**

internal code: UNKNOWN_SP

Message: The Service provider that sent the message is not known to us.

**UNSUPPORTED_BINDING**

internal code: urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding

Message: The SAML responder cannot properly fulfill the request using the protocol binding specified in the request.

**WRONG_AUTHENTICATION_METHOD**

internal code: WRONG_AUTHENTICATION_METHOD

Message: There was a problem finding the authentication method

**WRONG_USER**

internal code: IDP_WRONG_USER

Message: Mismatch between logged on user and incoming user

### reCaptcha

reCaptcha is a process that helps distinguish bot users from actual users. It can be included in web forms or authentication or authorization processes to help filter out bots.

The check is executed on the front-end as well as the back-end, making sure the process cannot be bypassed.

We apply the following process:

1. Upon form post, the Captcha string is included in the form post

2. If the captcha check is required in the settings, the back-end will validate the Captcha string provided by the Front-end on the configured Captcha validation endpoint.

3. After a successful captcha check, the registration can be completed, or the login can be handled.

There is also a ReCaptcha service that can be accessed by workflows.  

|        Field        |                                          Description                                           |
|---------------------|------------------------------------------------------------------------------------------------|
| Secret Key          | The secret used to query the reCaptcha endpoint                                                |
| Validation Endpoint | The recaptcha validation endpoint                                                              |
| Key                 | The site key your receive from the reCaptcha service.                                          |
| Hostnames           | The hostnames that are registered that can use this key to run a reCaptcha check.              |
| **Required Pages**                                                                                                  ||
| Below are the templates which can execute a ReCaptcha                                                               ||
| ADLogin             | This enables the backend captcha check on the Active Directory Login Template                  |
| IdpSelection        | This enables the backend captcha check on the IDP Selection template                           |
| Login               | This enables the backend captcha check on the TrustBuilder Username \& Password login Template |
| MobileRegistration  | This enables the backend captcha check on the Mobile Registration Template                     |
| PasswordReset       | This enables the backend captcha check on the Password Reset Template                          |
| Registration        | This enables the backend captcha check on the TrustBuilder User registration Template          |

**Applying Captchas to templates**

If you enable a reCaptcha check in a template, you must also verify that the Captcha element is added to the template code.

Go to the specific template and make sure the following code is present:

    <!-- CAPTCHA -->
      <div id="captchaWidget" class="row" show-element="<%captchaShow%>">
        <div class="col-lg-12">
           <div class="form-group">
              <div class="g-recaptcha" data-sitekey="<%captchaSiteKey%>" data-callback="onCaptchaResponse">
              </div>
           </div>
         </div>
       </div>

[Next Page](https://docs.trustbuilder.com/llms-full.txt/1)
