API Keys provide an alternative authentication credential for AI agents, scripts, and client code accessing LabKey Server via various APIs. Rather than using your LabKey password, an API Key is a dedicated, revocable token that can be used independently of how you log in interactively. When desired, a single user can have multiple simultaneous API Keys for different purposes.

Overview

API Keys have several security advantages over passwords:

  • They are independent of your login password and can be revoked without affecting your account
  • They are usually configured to expire, limiting the window of exposure if compromised
  • They are tied to a specific server
  • They are well-suited for use with dedicated service accounts, where issuing a personal password would be inappropriate
  • They provide API access for users who authenticate via single sign-on mechanisms such as CAS and SAML
  • They also provide API access for servers configured for two-factor authentication (such as Duo or TOTP)
  • They can be restricted to a specific security role at creation time, letting you control the access granted to AI agents, tools, and scripts
Since an API Key provides access to your data and actions, it should be kept secret

Administrators can configure the server to allow logged in users to obtain API Keys. Administrators also specify an expiration duration for API Keys.

Users can delete API Keys that they have created. Administrators can delete API Keys created by any user.

In cases where access must be tied to the current browser session and run under the current context (e.g., your user, your authorizations and if applicable, your declared terms of use and PHI level, your current impersonation state, etc.), such as some compliance environments, you will need to use a session key. Session keys expire at the end of the session, whether by timeout or explicit logout.

Configure API Keys (Administrator)

  • Select > Site > Admin Console.
  • Under Configuration, click Site Settings.
  • Under Configure API Keys, check the box for Let users create API Keys.
  • Select when to Expire API Keys. Options:
    • Never (default)
    • 7 days (1 week)
    • 30 days (1 month)
    • 90 days (3 months)
    • 180 days (6 months)
    • 365 days (1 year)
  • Click Save.

Generate an API Key

The API Key is a long, randomly generated token. A valid API Key provides access to your data and actions, so it should be kept secret.

Once enabled, a logged-in user can retrieve an API Key via username > External Tool Access:

Click Generate API Key to create one. In the popup, you can provide your own description of the usage of that key, which can help you later if you need to determine which key(s) may have expired.

Use the Restrict Permissions dropdown to limit what the key can do. This is especially useful when issuing a key to an AI agent, tool, or script, since it lets you cap the key's access below your own account's access. Options are:

  • No Restrictions (default): the key has the same access as your account.
  • Reader: the key can only read data.
  • Author: the key can read and insert data, but cannot update or delete.
  • Editor without Delete: the key can read, insert, and update data, but cannot delete.
  • Editor: the key can read, insert, update, and delete data.
When a restriction role is selected, all interactions authenticated by that API Key receive the permissions you have been granted in each folder, further limited to the permissions granted by the restriction role. For example, if you are an Editor in a folder and restrict a key to Reader, that key can only read data there, regardless of your own account's access level.

Click Generate API Key again.

Click the button to copy it to the clipboard. Important: the key itself will not be shown again and is not available for anyone to retrieve, including administrators. If you lose it, you will need to regenerate a new one.

Click Done at the bottom of the page. Your key with any description and restriction role will now be listed.

If needed, you can generate multiple API Keys and use them in different contexts at the same time to provide the same access under your credentials, or different restricted access for different tools and agents.

Note: When an administrator is impersonating a user, group or role, they cannot generate an API Key.

Using an API Key

In the examples below, replace API_KEY with your actual API Key value.

netrc File

The recommended method for scripts and client libraries is to store the API Key in a netrc file. This avoids embedding credentials directly in your code and is compatible with all LabKey client libraries. Use apikey as the username and the API Key as the password:

machine <your-server-hostname>
login apikey
password API_KEY

Basic Authentication Header

API Keys work with any client that supports HTTP Basic authentication. Base64-encode the string apikey:API_KEY and pass it as the value of the Authorization header:

Authorization: Basic <Base64 encoded "apikey:API_KEY">

For example, in Python:

import base64, requests

token = base64.b64encode(b"apikey:API_KEY").decode("utf-8")
headers = {"Authorization": f"Basic {token}"}
response = requests.get("https://<server>/labkey/...", headers=headers)

apikey Header

Pass the API Key directly in a custom apikey request header:

apikey: API_KEY

For example, in Python:

import requests

headers = {"apikey": "API_KEY"}
response = requests.get("https://<server>/labkey/...", headers=headers)

Bearer Token (Authorization Header)

Pass the API Key as a Bearer token in the standard Authorization header:

Authorization: Bearer API_KEY

For example, in Python:

import requests

headers = {"Authorization": "Bearer API_KEY"}
response = requests.get("https://<server>/labkey/...", headers=headers)

Troubleshooting

If you see an error like one of these:

Error in handleError(response, haltOnError) :
HTTP request was unsuccessful. Status code = 401, Error message = User does not have permission to perform this operation.

labkey.exceptions.RequestAuthorizationError: '401: User does not have permission to perform this operation.'

Check to see if you are using an invalid API Key, either one that has expired, been revoked, or has additional characters (such as the "apikey|" prefix that was previously used with API Keys and is no longer used). The invalid key could be in your script or in the netrc file.

If a request fails with a permissions error even though your account has sufficient access, check whether the API Key you are using has a Restriction Role applied. A restricted key limits you to that role's permissions regardless of your account's actual access level.

A site administrator can set the org.labkey.api.security.SecurityManager.Authentication logger to DEBUG level on the Admin Console -> Loggers page to enable detailed logging of every authentication attempt. This can help track down issues with API keys and other credentials.

Manage API Keys (Administrator)

A site administrator can manage API Keys generated on the server using the APIKey query. Link to it from the top of the username > External Tool Settings page.

You will see the keys that have been generated on this server, listed by username and displaying the time of creation as well as expiration (where applicable), last usage, a description if one was included, and the Restriction Role applied to the key, if any. Note that session keys are not listed here.

To revoke an API Key, such as in a case where it has been compromised or shared, select the row and click (Delete). To revoke all API Keys, select all rows and delete.

Related Topics

Was this content helpful?

Log in or register an account to provide feedback


previousnext
 
expand allcollapse all