Sub topic 3
Authorizing endpoints: Remote Site Settings
Salesforce blocks every Apex callout unless the destination has been authorized by an administrator. This chapter covers why the rule exists, how Remote Site Settings satisfy it, how URLs are matched, and how to diagnose the error you get when a callout is not authorized. It assumes you can write basic Apex, read an HTTP status code, and open Setup. The next chapter covers Named Credentials, which are the preferred alternative.
Why the platform requires authorization
Apex runs inside Salesforce's multitenant platform, and callouts send data from your org to a server you do not control. If any developer could point code at any host, one mistake or one malicious change could send customer records anywhere. The platform makes the destination an explicit, reviewable setting. Developers write the code, and an administrator decides which hosts the org may contact.
There are two ways to authorize an endpoint:
| Mechanism | Endpoint in code | Typical use |
|---|---|---|
| Remote Site Setting | The full URL, such as `https://jsonplaceholder.typicode.com/todos/1` | Public or simple endpoints with no stored credentials |
| Named Credential | `callout:Todo_API/todos/1` | Endpoints that need authentication, or any new work |
A Remote Site Setting authorizes a destination and nothing else. It stores no username, token or secret, so your code still has to supply credentials, usually in a header. That is the main reason Named Credentials are preferred for anything that authenticates.
What the failure looks like
If you call an endpoint that is not authorized, the send method throws a System.CalloutException:
System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings.The exception is thrown before any network traffic leaves Salesforce, so the remote server never sees the request. It is an ordinary exception and you can catch it. The error is a configuration problem, not a transient one, so retrying will not help.
This minimal class sends a request and reports an authorization failure clearly. It uses the public JSONPlaceholder test API, which has no authentication.
public with sharing class EndpointProbe {
public static String probe(String url) {
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
req.setTimeout(10000);
try {
HttpResponse res = new Http().send(req);
return 'Reached ' + url + ' with status ' + res.getStatusCode();
} catch (CalloutException e) {
if (e.getMessage().contains('Unauthorized endpoint')) {
return 'Not authorized: add a Remote Site Setting for ' + url;
}
throw e;
}
}
}Run EndpointProbe.probe('https://jsonplaceholder.typicode.com/todos/1') in Anonymous Apex before and after creating the setting below. Before, you get the "Not authorized" message. After, you get a status code.
Creating a Remote Site Setting
In Setup, search for Remote Site Settings and choose New Remote Site. The form has these fields:
| Field | Meaning |
|---|---|
| Remote Site Name | An API-style name with letters, numbers and underscores. It cannot start with a digit or contain spaces. |
| Remote Site URL | The base URL of the destination, including the scheme, such as `https://jsonplaceholder.typicode.com` |
| Disable Protocol Security | When checked, allows data to pass between HTTPS and HTTP sessions. Leave it unchecked unless you have a specific reason. |
| Description | A note for the next administrator. Say which integration needs the site. |
| Active | Only active settings authorize callouts. Clearing it switches the site off without deleting it. |
Use the following values for the examples in this tutorial:
- Remote Site Name:
JSONPlaceholder - Remote Site URL:
https://jsonplaceholder.typicode.com - Active: checked
The change takes effect as soon as you save. No deployment or cache flush is needed.
How URLs are matched
A callout is allowed when its endpoint falls under an active Remote Site Setting. Matching works on the origin, which is the scheme, host and port. Three consequences follow.
- The path is not what you authorize. One entry for
https://jsonplaceholder.typicode.comcovers/todos,/posts/5and every other path on that host. - Each host needs its own entry. An entry for
https://example.comdoes not coverhttps://api.example.com. Subdomains are separate hosts. - The scheme and port matter. An entry for
https://example.comdoes not authorizehttp://example.com. A different port, such ashttps://example.com:8443, also needs its own entry.
Callouts can use port 80, port 443, or a port from 1024 to 66535. Services on other ports cannot be reached from Apex, however you configure them.
The diagram below shows the order of checks when send is called.
Redirects need authorization too
Apex does not follow HTTP redirects for you. If the server answers with a 301 or 302, the response contains a Location header, and your code decides whether to make a second request. That second request is a new callout, so its host must also be authorized.
public with sharing class RedirectAwareClient {
public static HttpResponse get(String url) {
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
HttpResponse res = new Http().send(req);
Integer status = res.getStatusCode();
if (status == 301 || status == 302) {
String next = res.getHeader('Location');
req.setEndpoint(next);
res = new Http().send(req);
}
return res;
}
}This follows a single redirect only. If the target is on a different host, such as a CDN or a regional server, it throws the unauthorized-endpoint exception until you add that host. A loop that follows redirects without a limit will also consume your callout limit quickly, which later chapters cover.
Deploying Remote Site Settings as metadata
Remote Site Settings are metadata, so you can keep them in source control and deploy them with the rest of your project. The metadata type is RemoteSiteSetting. In a source-format project, the file lives at force-app/main/default/remoteSiteSettings/JSONPlaceholder.remoteSite-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">
<description>JSONPlaceholder test API used by the Todo examples</description>
<disableProtocolSecurity>false</disableProtocolSecurity>
<isActive>true</isActive>
<url>https://jsonplaceholder.typicode.com</url>
</RemoteSiteSetting>Keeping the file in the repository matters because a callout that works in your sandbox fails in production if the setting was only created by hand in the sandbox. Treat the setting as a dependency of the Apex class that uses it, and deploy them together.
Protocol security and why to leave it on
The Disable Protocol Security option exists for the case where a request moves between HTTPS and HTTP, for example a secure page that must contact an insecure service. With the box unchecked, Salesforce keeps the data on secure connections. Checking it lets the data cross to plain HTTP, where it can be read or altered in transit.
Remote Site Settings compared with Named Credentials
A Remote Site Setting is quick to create, and it is reasonable for a public, unauthenticated API. It has real limits.
- It holds no credentials, so tokens or passwords end up in Apex, custom settings or custom metadata, where they are easier to leak.
- It authorizes a whole host. You cannot restrict it to one path or one integration.
- Any Apex in the org can call that host once the setting is active.
A Named Credential covers the same authorization need through the callout: prefix, and it also stores the authentication details. When an endpoint uses callout:, you do not need a separate Remote Site Setting for it. That is why the Topic's examples after this chapter use callout:Todo_API. You will still meet Remote Site Settings in older code and in orgs that have not migrated, so you need to read and maintain them.
Remote Site Settings and tests
Tests that call Test.setMock never reach the network, so the platform does not need the endpoint to be authorized for them to pass. A suite with a perfect pass rate says nothing about whether the org has the Remote Site Setting. Mocked tests are the right way to test your logic, as a later chapter shows. They cannot replace a manual or integration check that the real endpoint is authorized in each environment.
Troubleshooting checklist
When you see "Unauthorized endpoint", work through these in order:
- Read the exact URL the code sends. Log
req.getEndpoint()if you build it from several parts. - Check that a Remote Site Setting exists in this org, not only in another sandbox.
- Check that the setting is Active.
- Compare the scheme, host and port character by character.
httpagainsthttpsandwww.prefixes are common mismatches. - If the first call succeeds and a later one fails, look for a redirect to another host.
- If the endpoint needs credentials, consider a Named Credential instead of adding another Remote Site Setting.
Exercise
Your class calls https://api.example.com/v1/orders. An administrator has an active Remote Site Setting for https://example.com. The callout throws "Unauthorized endpoint". Why, and what is the smallest fix?
Show answer
The setting is matched by scheme, host and port, and api.example.com is a different host from example.com. Subdomains are not covered. Add a Remote Site Setting for https://api.example.com. The path /v1/orders does not need to be included. If the API requires authentication, use a Named Credential instead.
Exercise
A test that uses Test.setMock passes in a new sandbox, but the same code throws CalloutException in that sandbox when run from Anonymous Apex. What is the likely cause?
Show answer
The Remote Site Setting, or Named Credential, was never created or deployed to that sandbox. The mock bypasses the network, so the test never checks authorization. The real callout does, and it fails. Deploy the RemoteSiteSetting metadata with the code.