Sub topic 18
Monitoring OAuth usage and managing sessions
This chapter shows how to see which apps and users hold OAuth tokens in your org, how to read the audit trail those tokens leave, and how to end access quickly when something looks wrong. It assumes you can already create a connected app or external client app (ECA), know the flows from earlier chapters, and can run curl and the Salesforce CLI (sf). You also need a user with the Manage Connected Apps permission, plus API access for the queries.
What you can observe
An OAuth integration leaves evidence in four places. Each answers a different question.
| Source | Question it answers | Where |
|---|---|---|
| OAuth usage page | Which apps hold tokens, how many users, how often used? | Setup, Connected Apps OAuth Usage |
| `OAuthToken` object | Which user authorized which app, and when was it last used? | SOQL |
| `LoginHistory` | Did an OAuth login succeed, from which IP and app? | Setup or SOQL |
| Event Monitoring | What did the session do after login? | Event log files and real-time events (extra license) |
Start with the cheapest source that answers your question. The first three come with every org. The fourth is a paid add-on.
The OAuth usage page
In Setup, search for Connected Apps OAuth Usage. The page lists each app with a user count and a use count. Opening an app shows each user's token, how many times it was used, and when it was last used.
Use this page for three tasks:
- Inventory. Find apps that nobody in the business remembers approving. An app with a high user count and an unfamiliar name needs an owner.
- Dormancy. Tokens with an old last-used date are candidates for revocation.
- Containment. The page lets you revoke a single user's token, revoke all tokens for an app, or block the app. Blocking prevents new tokens and also stops existing ones from working. Unblocking later restores the app.
ECAs follow the same model, but the page where you review them can differ by release. Check the External Client App Manager entry for the app and its OAuth usage view in your org. Do not assume that a block set on a connected app carries over to its ECA replacement.
Querying tokens with SOQL
The OAuthToken object exposes the same data the usage page shows. A query is easier to schedule, diff, and export than a page.
sf data query \
--target-org ci-org \
--query "SELECT AppName, UserId, UseCount, LastUsedDate FROM OAuthToken ORDER BY LastUsedDate ASC NULLS FIRST LIMIT 200"The oldest and never-used tokens come first. To find the owner of a stale token, join it with the user by UserId:
sf data query \
--target-org ci-org \
--query "SELECT Id, Username, Email FROM User WHERE Id IN (SELECT UserId FROM OAuthToken WHERE LastUsedDate < LAST_N_DAYS:90)"A token that has not been used for 90 days, belonging to an app that is still approved, is a quiet risk. Decide on a retention rule such as "revoke after 90 days unused" and run this query on a schedule.
Reading login history
Every OAuth login creates a LoginHistory row. Query it to see failures and unusual sources:
sf data query \
--target-org ci-org \
--query "SELECT LoginTime, UserId, Application, LoginType, Status, SourceIp FROM LoginHistory WHERE LoginTime = LAST_N_DAYS:7 AND LoginType LIKE '%Remote Access%' ORDER BY LoginTime DESC LIMIT 200"The exact LoginType strings can vary, so run an unfiltered query once and look at the values your org returns. Then adjust the filter.
Read the results for these patterns:
- Repeated failures for one user and app. Check the
Statustext, then see the troubleshooting chapter. - A JWT or client credentials integration logging in from an IP that is not your server. This often means a leaked key or secret.
- A burst of logins just after a policy change. Your change may have invalidated tokens, and clients are re-authorizing.
Note that LoginHistory records the login, not the API calls that follow it. For those, you need Event Monitoring.
Event Monitoring for API activity
With the Event Monitoring license you get LoginEvent, ApiEvent, and event log files. These show which API calls an integration made, with timestamps and IP addresses. They are the evidence you need to decide how far a compromise reached. Without the license, you can only infer scope from the integration user's permissions, so least-privilege setup matters more.
Managing sessions and tokens
An OAuth login creates a session, and the flow may also issue a refresh token. Ending access means dealing with both. Revoking only the session leaves a refresh token that can create a new one.
Revoking from the API
The revoke endpoint accepts either token type. Revoking a refresh token also invalidates the access tokens issued from it.
curl -X POST https://MyDomain.my.salesforce.com/services/oauth2/revoke \
-d token="$REFRESH_TOKEN"A successful call returns HTTP 200. Build this call into your integration's disconnect or decommission step.
Inspecting a token
Token introspection tells you whether a token is active and who it belongs to. The caller authenticates with the app's consumer key and secret.
curl -X POST https://MyDomain.my.salesforce.com/services/oauth2/introspect \
-d token="$ACCESS_TOKEN" \
-d token_type_hint=access_token \
-d client_id="$CONSUMER_KEY" \
-d client_secret="$CONSUMER_SECRET"The response includes an active flag. A value of false means the token is expired or revoked.
Ending sessions in Setup
Open Session Management in Setup to list active sessions. You can end a single session or several. For a user, open their detail page and review the OAuth connected apps list, where you can revoke each app individually.
Session lifetime settings
Two settings control how long a token works without your intervention:
- The app policy's session timeout and refresh token policy (valid until revoked, expire after a set time, or expire if not used). Set the shortest lifetime the integration can tolerate.
- The org's session settings, which apply when the app policy does not override them.
Changing a policy does not make every client behave well. A client that does not handle invalid_grant or an expired session will fail until someone fixes it, so test with the integration owner.
An incident response sequence
When you suspect that an integration is compromised, work from containment to cleanup.
- Block the app or revoke the affected tokens first, since that stops further use.
- End active sessions so existing access tokens stop working.
- Rotate the consumer secret, or replace the certificate for a JWT bearer app.
- Use login history and event logs to find what was accessed.
- Unblock only after the new credentials are in place and the integration owner confirms.
Common mistakes
- Relying on the usage page alone. It shows counts, not what an app did.
- Revoking an access token while leaving the refresh token. The client simply gets a new access token.
- Blocking an app during business hours without telling its owner. Blocking breaks production jobs immediately.
- Filtering
LoginHistoryon a guessedLoginTypeand concluding there is no activity. - Forgetting the integration user itself. Client credentials and JWT apps run as a fixed user, so deactivating or freezing that user also stops them.
Exercise
A JWT bearer integration is suspected of being compromised, and its private key may have leaked. List the order of actions you take and explain why revoking tokens alone is not enough.
Show answer
Block the app or revoke its tokens and end active sessions to stop current access. Then replace the certificate on the app and generate a new private key, because the leaked key can still sign new JWTs and get new access tokens even after old tokens are revoked. Review LoginHistory (and Event Monitoring if licensed) to see what the key was used for, then unblock the app and deploy the new key to the integration.
Exercise
Write a SOQL query that returns tokens not used in the last 60 days, oldest first, with the app name and user ID.
Show answer
SELECT AppName, UserId, UseCount, LastUsedDate FROM OAuthToken WHERE LastUsedDate < LASTNDAYS:60 ORDER BY LastUsedDate ASC