Goal
You want to run oci commands from your laptop as yourself, with your normal console sign-in and MFA, without creating and storing an API signing key for your user. That is what session token (security token) authentication does.
The CLI opens a browser, you sign in like you would to the console, and the CLI stores a short-lived token in a profile. Commands run with --auth security_token use that token.
| Method | Good for | Not good for |
|---|---|---|
| API key | Service accounts, long-running automation | Personal use: the key lives on disk for months |
| Session token | Engineers at a terminal, federated users, MFA-enforced tenancies | Cron jobs and unattended pipelines |
| Instance / resource principal | Code running on OCI | Laptops |
| Cloud Shell | Quick one-off commands | Local scripts and your own toolchain |
Prerequisites
- OCI CLI installed (
oci --version). If you don't have it yet, install it first. You don't need to runoci setup config. - A browser on the same machine. The CLI listens on
localhostport 8181 for the sign-in callback, so that port must be free. - A console user that can sign in. Federated users work, which is often the main reason to use this method.
Step 1: sign in and create a profile
oci session authenticate --region eu-frankfurt-1 --profile-name ops
What happens:
- The CLI generates a key pair for this session and opens your browser.
- You choose your identity domain or identity provider and sign in, MFA included.
- The browser shows that authentication completed. The CLI writes the token and the profile.
Without --region, the CLI shows a numbered list of regions and asks you to pick one. Without --profile-name, it asks for a name.
Look at what it wrote:
cat ~/.oci/config
ls -l ~/.oci/sessions/ops/
The new profile looks like this:
[ops]
fingerprint=aa:bb:cc:...
key_file=/home/you/.oci/sessions/ops/oci_api_key.pem
tenancy=ocid1.tenancy.oc1..aaaa...
region=eu-frankfurt-1
security_token_file=/home/you/.oci/sessions/ops/token
The security_token_file line marks this as a session profile. The key in sessions/ops/ belongs to this session only. It is not uploaded to your user, and it is useless once the token expires.
Step 2: run commands with the token
Every command needs both the profile and the auth type:
oci os ns get --profile ops --auth security_token
oci iam region-subscription list --profile ops --auth security_token --output table
If you leave out --auth security_token, the CLI tries API key signing with the session key. That fails with 401 NotAuthenticated, which confuses people the first time.
To avoid typing the flags each time, set them for the shell:
export OCI_CLI_PROFILE=ops
export OCI_CLI_AUTH=security_token
oci compute instance list -c "$COMPARTMENT_OCID" --output table
PowerShell:
$env:OCI_CLI_PROFILE = "ops"
$env:OCI_CLI_AUTH = "security_token"
oci os ns get
Tip
Name session profiles after the tenancy and region, for example
prod-fraanddev-ams. Your shell history then shows which tenancy each command ran against.
Step 3: check and refresh the session
The default token is valid for one hour. You can refresh it while it is still valid, up to 24 hours from the first sign-in. The exact limits can vary with your identity provider settings, so check your own session.
# Is the session still valid, and until when?
oci session validate --profile ops --auth security_token
# Extend it (only works before it expires)
oci session refresh --profile ops
After the token expires, refresh fails and you have to run oci session authenticate again. A small wrapper keeps a long working session alive:
#!/usr/bin/env bash
# oci-keepalive.sh: refresh the ops session every 50 minutes while you work
while oci session validate --profile ops --auth security_token >/dev/null 2>&1; do
sleep 3000
oci session refresh --profile ops || break
done
echo "Session expired: run 'oci session authenticate --profile-name ops'" >&2
Run it in a spare terminal. Don't use it as a reason to run unattended jobs on your personal session. Those should use a service account or an instance principal.
Step 4: use the same profile in Terraform and Python
Terraform
The OCI provider reads the same config file:
provider "oci" {
auth = "SecurityToken"
config_file_profile = "ops"
region = "eu-frankfurt-1"
}
Validate or refresh the session before a long terraform apply. If the token expires during the apply, the remaining API calls fail with 401 and some resources are left half done.
Warning
Run
oci session refresh --profile opsright beforeterraform applyon anything large, such as a full landing zone or many instances. A token that expires mid-apply leaves state that you have to reconcile by hand.
Python SDK
import oci
profile = "ops"
config = oci.config.from_file(profile_name=profile)
with open(config["security_token_file"]) as f:
token = f.read()
private_key = oci.signer.load_private_key_from_file(config["key_file"])
signer = oci.auth.signers.SecurityTokenSigner(token, private_key)
os_client = oci.object_storage.ObjectStorageClient(config={"region": config["region"]}, signer=signer)
print(os_client.get_namespace().data)
Headless machines and jump hosts
On a server without a browser, port 8181 has nobody to call back to. You have two options:
- Forward the callback port. SSH to the server with
ssh -L 8181:localhost:8181 user@host, runoci session authenticatethere, and open the printed URL in your local browser. - Authenticate locally and copy the session. Use
oci session exportandoci session import:
# On your laptop
oci session export --profile ops --output-file ops-session.zip
# On the server
oci session import --session-archive ops-session.zip
Caution
The exported archive contains a working token and its private key. Anyone who copies it can act as you until the token expires. Delete it from both machines after you import it, and never commit it or attach it to a ticket.
oci session authenticate --no-browser also exists. It uses an existing API key profile to mint a session token, and the session lasts at most 60 minutes. It is useful for testing token-based code paths, but it doesn't remove the API key.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
401 NotAuthenticated right after sign-in | --auth security_token missing | Add the flag or set OCI_CLI_AUTH=security_token |
| Worked for an hour, then 401 | Token expired | oci session refresh if still inside the window, otherwise authenticate again |
refresh fails | Token already expired or the 24-hour limit reached | oci session authenticate --profile-name ops |
| Browser never opens, CLI waits | No browser, or port 8181 in use | Free the port, use SSH port forwarding, or export and import |
404 NotAuthorizedOrNotFound | Authenticated, but your groups lack a policy | Check IAM policies for your user's groups |
| Wrong tenancy or region in results | Another profile or OCI_CLI_PROFILE is set | echo $OCI_CLI_PROFILE, and pass --profile explicitly |
To end a session early, for example on a shared machine:
oci session terminate --profile ops
Prevent it next time
- Use session profiles for people and API keys only for service users. Then a leaked laptop exposes a token that expires within the day, not a key that is valid for months.
- Where engineers have moved to session tokens, delete the old API keys from their users (
oci iam user api-key list --user-id <ocid>). - Put a
validatecheck at the top of your personal scripts so they fail with a clear message, not a mid-run 401. - Keep
~/.oci/sessions/out of backups and dotfile repositories.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get