Sub topic 8
Authenticating Callers and Granting Class Access
This chapter covers who can call your Apex REST service and what they need before a request reaches your code. It assumes you can write a basic @RestResource class (covered in earlier chapters), know what a bearer token is, and are familiar with profiles and permission sets.
Two separate checks
A call to an Apex REST endpoint passes two gates before your method runs:
- Authentication. Salesforce must recognize the caller. The request carries a valid OAuth access token or session ID, which resolves to a specific user.
- Authorization to the class. That user must have access to the Apex class that holds the
@RestResourceannotation.
Your code is never reached if either gate fails. A third layer, sharing and field-level security, applies inside the method. The next chapter covers it. Keep the layers apart in your head, because each one fails with a different symptom.
Every call to Apex REST runs as a real Salesforce user. There is no anonymous access to /services/apexrest/ on the core platform domain. (Guest access exists for Experience Cloud and Salesforce Sites, but it is a separate setup and is not covered here.)
How a caller authenticates
Apex REST uses the same authentication as the standard Salesforce REST API. The client sends the token in the Authorization header:
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"The token is obtained through an OAuth 2.0 flow. Which flow you choose depends on who the caller is.
| Caller | Typical flow | Notes |
|---|---|---|
| External server application, no user present | Client credentials flow or JWT bearer flow | Runs as a designated integration user. Best for system-to-system calls. |
| Web application acting for a signed-in user | Authorization code flow (with PKCE for public clients) | The token represents the person who approved access. |
| Command-line tool or script run by a developer | Authorization code with PKCE, or a CLI login | Avoid storing passwords in scripts. |
| Another Salesforce org | Named Credential with an External Credential | Handles token retrieval and refresh for you. |
| Code running inside the same org | Session ID of the running user | Not for external callers. |
The username-password flow still works in some orgs, but Salesforce discourages it. It sends a password through the integration, it cannot satisfy multi-factor authentication, and it is disabled by default in newer orgs. Prefer a flow in the table above.
Use the My Domain URL
Send requests to your org's My Domain host, such as https://MyDomainName.my.salesforce.com. The token response also includes an instance_url field. Clients should build the request URL from that value instead of hard-coding a host. A token is only valid for the org that issued it, so a sandbox token sent to a production host fails.
Setting up a connected app or external client app
For an OAuth flow to work, the org needs an application record that represents the client. Salesforce calls this a connected app. Newer orgs can also use an external client app, which is the newer packaging for the same purpose. The exact setup screens differ between the two, but the decisions are the same.
- Enable OAuth settings for the app and set the callback URL if the flow redirects.
- Select the OAuth scopes. The scope
apilets the token call Apex REST. The scoperefresh_token(oroffline_access) lets the client renew the token without asking the user again. The scopewebis not needed for API calls. - Choose who can use the app. Set the policy to admin-approved users, then assign the app through profiles or permission sets. This limits which users can obtain a token.
- For server-to-server flows, set a run-as user (client credentials) or upload a certificate (JWT bearer). Use a dedicated integration user, not a named employee's account.
The scope check is easy to miss. A token that has only the id or openid scope can identify the user but cannot call your service. The call fails even though the token is real.
Granting access to the Apex class
Authentication proves who the caller is. It does not give that person the right to run your code. Access to an Apex class is a permission, and it is granted in one of two places:
- Permission sets (preferred). Under the permission set's Apex Class Access section, add the class.
- Profiles. Under the profile's Apex Class Access section, add the class.
Use a permission set. A dedicated set such as Account_API_Access can be assigned to the integration user and to nobody else. You can see exactly who can call the service, and you can revoke access without editing a profile.
A user with the Modify All Data permission or a system administrator profile can run any class, but you should not rely on that. An integration user that works only because it is an administrator is over-privileged.
What a missing grant looks like
When the user lacks class access, the platform returns an error before your method executes:
[
{
"errorCode": "NOT_FOUND",
"message": "Could not find a match for URL /v1/Accounts/001XXXXXXXXXXXXXXX"
}
]The status is 404. This message is the one callers see when the class is not accessible, and it looks identical to a URL typo. A 404 from /services/apexrest/ therefore has several causes. The URL mapping may not match, the class may not be deployed, the user may lack class access, or you are calling the wrong org. Check the class access first when the URL is correct.
Common authentication failures
The status code and error body help you identify the layer that failed.
| Symptom | Likely cause | Fix |
|---|---|---|
| `401` with `INVALID_SESSION_ID` | Token expired, revoked, or sent to the wrong org | Refresh or reissue the token. Confirm the host matches the token's `instance_url`. |
| `401` with no token response | The `Authorization` header is missing or malformed | Use the exact form `Bearer <token>`. |
| `403` with `REQUEST_LIMIT_EXCEEDED` | The org exceeded its daily API request allocation | Reduce calls or review the org's API usage. |
| `403` with `INSUFFICIENT_ACCESS` or similar | The user is blocked from the object, field, or record inside your code | Review sharing and field-level security in the next chapter. |
| `404` `NOT_FOUND` on a correct URL | The user has no class access, or the class is not deployed | Add the class to a permission set. Confirm deployment. |
| `400` `invalid_grant` when requesting a token | The user is not approved for the app, the certificate does not match, or the run-as user is wrong | Check the app's policies and the user's assigned permission set. |
| `400` `invalid_scope` or a call that returns an authorization error | The token lacks the `api` scope | Add the scope to the app and request a new token. |
Restricting access beyond the class
Class access is coarse. It answers "may this user call any method on this class?" Sometimes you need a finer check.
Custom permissions
A custom permission is a named flag that you create in Setup and assign through permission sets. Your code can check it with FeatureManagement.checkPermission. This lets one class serve users with different rights, such as read-only callers and callers who may delete.
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpDelete
global static void deleteAccount() {
RestResponse res = RestContext.response;
if (!FeatureManagement.checkPermission('Delete_Accounts_Via_API')) {
res.statusCode = 403;
res.responseBody = Blob.valueOf('{"message":"Delete is not permitted for this user."}');
return;
}
String accountId = RestContext.request.requestURI.substringAfterLast('/');
Account acc = [SELECT Id FROM Account WHERE Id = :accountId WITH USER_MODE LIMIT 1];
delete as user acc;
res.statusCode = 204;
}
}The custom permission Delete_Accounts_Via_API must exist in the org and be granted through a permission set. If the name does not exist, checkPermission returns false, so a typo denies access instead of granting it. That is the safe failure direction, but it can be hard to spot.
In this example, a missing record makes the SOQL query throw a QueryException that you would normally catch. The next chapters on status codes and error handling show how to do that.
Check identity when it matters
UserInfo.getUserId() returns the running user, and UserInfo.getUserType() and related methods describe that user. Use them when the response depends on who is calling, for example to write an audit field. Do not use identity checks as a replacement for permissions. Hard-coded user IDs break when you move the code between sandboxes and production.
Protecting tokens and credentials
Authentication is only as strong as the handling of the secret behind it.
- Store client secrets and private keys in a secret manager or in the calling platform's credential store. Do not commit them to source control.
- Give each integration its own connected app and its own integration user. When one leaks, you revoke one thing.
- Give the integration user the smallest permission set that works. If the client only reads accounts, do not grant the delete custom permission.
- Keep access tokens out of logs. A debug log that prints the full
Authorizationheader exposes a working credential. - Set a session timeout and a refresh token policy that match the risk. A refresh token that never expires is a long-lived credential.
Calling out to another service
Authentication also runs in the other direction when your Apex code calls an external system. For that, use a Named Credential. It stores the endpoint and the authentication details outside your code and handles token refresh. The details are a separate topic from exposing your own service, so this chapter mentions it only to prevent a common mistake: do not embed a secret in an Apex string to call another API.
Authentication flow at a glance
A practical checklist
Before you hand a service to a client team, confirm each item:
- A connected app or external client app exists with the
apiscope and the right flow. - The app is limited to approved users.
- A dedicated integration user exists, assigned only the permission set for this service.
- The permission set lists the Apex class under Apex Class Access.
- Any custom permissions the code checks are created and assigned.
- You tested with the integration user's token, not an administrator's token. An administrator passes checks that the real caller will fail.
The last item matters most. Many services pass every test during development and fail on the first real call, because the developer tested with an account that has far more rights than the integration user.
Exercise
A client calls GET /services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX with a valid access token and receives a 404 NOT_FOUND. The URL matches the urlMapping exactly and the class is deployed. Name two things you would check about the user and the token, and explain why a 404 appears instead of a 403.
Show answer
First, check whether the running user has the Apex class in a permission set or profile under Apex Class Access. Second, check that the token belongs to the same org as the host in the URL, and that it has the api scope. When the user cannot access the class, the platform does not expose that the endpoint exists, so it reports that no resource matches the URL. The result looks like a 404 instead of a 403. A 403 appears only when the request reaches your code and the code, or the platform on its behalf, denies access to data.
Exercise
Why should an integration user receive a dedicated permission set for the Apex class, instead of being given the System Administrator profile?
Show answer
A dedicated permission set grants only the access the service needs, so a leaked token can do limited damage. It also makes it clear who can call the service and lets you revoke access without changing a profile. The System Administrator profile bypasses class access checks and grants broad data access, which hides missing grants during testing and exposes far more than the integration requires.