Manage personal access tokens¶
Use a Keycloak access token to create, list, inspect, rotate, and revoke personal access tokens (PATs). Use a scoped PAT for a notebook or an unattended job. NOMAD authentication guide
| Action | Required scope |
|---|---|
| Read the signed-in account | users:read |
| Create a PAT | tokens:create |
| List or inspect PATs | tokens:read |
| Rotate a PAT | tokens:create and tokens:delete |
| Revoke a PAT | tokens:delete |
Connect and check your account¶
Set NOMAD_KEYCLOAK_ACCESS_TOKEN to a valid access token obtained through
your deployment's sign-in flow. The examples use endpoint = "prod"
for NOMAD Central. For a self-hosted NOMAD Oasis, replace that value with
the issuing deployment's complete HTTPS API v1 URL. You can also use a browser credential
to acquire the access token interactively. Each example opens and
closes its own client.
import os
from nomad_python_api import NomadClient
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
# Read the account linked to the Keycloak access token.
me = client.identity.me()
print(me.username, me.as_user().name)
The command prints your username and optional display name.
The Account also provides fields such as affiliation and creation time
when NOMAD returns them. as_user() produces a local profile model
without calling NOMAD again.
Create a PAT¶
Choose the permissions the job needs. Pass enum members and scope strings together as needed.
| Scope granted to the job PAT | What it lets the job do |
|---|---|
users:read |
Read its account profile |
uploads:read |
Read Project metadata it can access |
import os
from nomad_python_api import NomadClient, Scope
from nomad_python_api.identity import BearerTokenCredential, PatCreateOptions
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
# Grant the permissions needed by the research job.
options = PatCreateOptions(
name="Diffraction analysis",
description="Read account and project metadata from an HPC job",
scopes=[Scope.USERS_READ, "uploads:read"],
expires_in_days=30,
)
issued = client.identity.pats.create(options)
print(issued.pat.name, issued.pat.expired_at)
Create returns the PAT metadata and the one-time secret. The result's
representation and default JSON export exclude the secret. Use
BearerTokenCredential.from_issued(issued) to use it directly, or
explicitly extract it with issued.raw_token.get_secret_value() when
transferring it to a protected secret store.
List and filter PATs¶
Both listing methods return a lazy iterable. A plain loop fetches
additional results as needed. limit caps the total number consumed.
.filter() builds another listing with additional server-side filters.
It leaves the original reusable and rejects a conflicting value for a
filter already set.
import os
from nomad_python_api import NomadClient
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
# Get the signed-in account and use either listing method.
me = client.identity.me()
pats = client.identity.pats
for pat in me.get_all_pats():
print(pat.name, pat.revoked)
for pat in pats.list(state="active", limit=5):
print(pat.id, pat.expired_at)
filters = {"search": "Diffraction", "created_after": "2026-04-01T00:00:00Z"}
selected = pats.list(order_by="created_desc").filter(**filters).filter(revoked=False)
for pat in selected:
print(pat.name, pat.created_at)
The list reference covers every filter, including creation, last-use, and expiration bounds, as well as sorting.
Inspect, use, rotate, and revoke¶
The example creates a temporary PAT, uses it to check the job's account,
rotates it, and revokes the replacement. The original Keycloak client
manages the PAT. The job credential carries the PAT metadata ID so it
can also identify the rotation target. Revocation accepts metadata as well.
delete() is another name for revoke().
import os
from nomad_python_api import NomadClient
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
pats = client.identity.pats
# Issue a temporary PAT for this example.
issued = pats.create({"name": "Temporary diffraction job", "scopes": ["users:read"]})
job_credential = BearerTokenCredential.from_issued(issued)
with NomadClient(credential=job_credential) as job:
print(job.identity.me().username)
metadata = pats.get(issued.pat.id)
# Rotate the PAT before handing the replacement to the job.
replacement = pats.rotate(job_credential)
new_job_credential = BearerTokenCredential.from_issued(replacement)
with NomadClient(credential=new_job_credential) as job:
print(job.identity.me().username)
# Run this when the replacement is no longer needed.
pats.revoke(replacement.pat)
Rotation invalidates the old PAT when NOMAD processes the request.
Update the jobs that used it with the replacement. NOMAD can also revoke
the original PAT before replacement creation fails with HTTP 400.
If rotation raises PatWriteOutcomeUnknownError, use
pats.get(job_credential).revoked to check the original PAT before another
write. Inspect the PAT list in NOMAD if you need to reconcile the outcome.
Revocation invalidates the selected PAT.
Advanced dictionaries for bulk workflows¶
When a workflow prepares several PATs, put the shared fields in a Python
dictionary and add each run's name and lifetime. Pass each dictionary directly
to pats.create(). Each iteration sends one request and issues one PAT.
If a later request fails, the PATs already issued stay active.
import os
from nomad_python_api import NomadClient
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
# Reuse the same scopes for both research runs.
pats = client.identity.pats
shared_options = {"scopes": ["users:read", "uploads:read"]}
runs = [
{"name": "Diffraction preview"}, # Use the deployment's default expiry.
{"name": "Diffraction refinement", "expires_in_days": 7},
]
issued_by_run = {}
for run in runs:
issued_by_run[run["name"]] = pats.create({**shared_options, **run})
Keep each issued result in memory until the job consumes its credential or the
secret is transferred to a protected store. Omitting expires_in_days uses the
server default. Passing None explicitly sends JSON null, which the deployment
interprets according to its expiry policy. The same dictionary pattern works
for .filter(**filters) when several runs reuse search criteria.
Advanced paging and checkpointing¶
page_size controls how many entries NOMAD returns per request. Use
.by_page() for whole batches and store the opaque cursor after a batch
is processed. Resume with the same deployment, account, filters, and
sort order. A listing with limit is for item iteration.
A PAT cursor resumes against the current results
NOMAD uses an offset into the current sorted list. Additions or removals
before that offset can skip or repeat records even with identical filters
and sorting. For complete coverage, scan while the results are stable.
If the list changed after your checkpoint, restart from the first page
and deduplicate by pat.id.
import os
from nomad_python_api import NomadClient
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
with NomadClient(credential=credential) as client:
# Start from the first page with a fixed filter.
listing = client.identity.pats.list(state="active", page_size=20)
first_page = next(listing.by_page())
for pat in first_page.items:
print(pat.name)
# Save this cursor only after processing the whole page.
checkpoint = first_page.next_cursor
if checkpoint is not None:
for page in listing.by_page(continuation_token=checkpoint):
for pat in page.items:
print(pat.name)
Diagnose an authorization error¶
A PAT can authenticate NomadClient for job operations. PAT management
requires a Keycloak access token with the scopes in the table above.
To see how the SDK reports rejected PAT management, set NOMAD_PAT
and replace the example pat_id with its metadata ID.
401 means NOMAD rejected the credential. 403 means NOMAD refused
the action for the authenticated caller.
import os
from nomad_python_api import NomadClient
from nomad_python_api.exceptions import AuthorizationError, ClientAuthenticationError
from nomad_python_api.identity import BearerTokenCredential
# Use the issuing deployment and the metadata ID of your PAT.
endpoint = "prod"
pat_id = "507f1f77bcf86cd799439011"
credential = BearerTokenCredential(
os.environ["NOMAD_PAT"], endpoint=endpoint,
)
with NomadClient(credential=credential) as job:
try:
job.identity.pats.get(pat_id)
except AuthorizationError:
print("Sign in with a management access token to read PAT metadata.")
except ClientAuthenticationError:
print("Check the token and its issuing deployment.")
See PAT errors for local policy, deployment mismatches, ambiguous write outcomes, and recovery.
The next example attempts a rotation using a Keycloak access token.
Replace pat_id with the metadata ID of a PAT you intend to replace.
If the outcome is uncertain, reconcile it before making another write.
import os
from nomad_python_api import NomadClient
from nomad_python_api.exceptions import PatNotFoundError, PatWriteOutcomeUnknownError
from nomad_python_api.identity import BearerTokenCredential
# For an Oasis, replace "prod" with its full HTTPS API v1 URL.
endpoint = "prod"
credential = BearerTokenCredential(
os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"],
endpoint=endpoint,
)
# Supply the metadata ID of the PAT you intend to replace.
pat_id = "507f1f77bcf86cd799439011"
with NomadClient(credential=credential) as client:
pats = client.identity.pats
try:
replacement = pats.rotate(pat_id)
except PatNotFoundError:
print("Check the target's PAT metadata ID and account.")
except PatWriteOutcomeUnknownError:
print("Check the original PAT with pats.get(pat_id) before another write.")