Authentication
Every endpoint except POST /auth/login and POST /auth/refresh needs credentials, and you can send one of two kinds on each request. They reach the same endpoints; what differs is who you are and what you are allowed to do.
Send exactly one kind per request. A request that carries both an
Authorization: Bearerheader and anX-API-Keyheader is refused with400 ambiguous_credentials. This usually means a proxy or HTTP client adds a header you did not intend.
A company admin creates the key in the dashboard (Enable the API). You send two headers on every request:
| Header | Value |
|---|---|
X-API-Key |
The key, starting with lmc_live_ |
X-API-Secret |
The secret shown once when the key was created |
curl "https://api.goldrock.live/api/public/v1/auth/me" \
-H "X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
-H "X-API-Secret: YOUR_API_SECRET"const response = await fetch("https://api.goldrock.live/api/public/v1/auth/me", {
method: "GET",
headers: {
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET"
},
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/auth/me';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'X-API-Secret: YOUR_API_SECRET',
],
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"GET",
"https://api.goldrock.live/api/public/v1/auth/me",
headers={
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
},
timeout=30,
)
print(response.status_code, response.json())- Both headers are required. A key without its secret answers
401 unauthorized, and so does a wrong secret, a revoked key or an expired key. The message tells which. - What the key may do is decided by its scopes. Calling something outside them answers
403 forbiddenwithdetails.requiredScope. - Requests are rate limited per key, see Conventions.
- Whether the company is suspended or expired is checked on every request: a valid key or token of a blocked company answers
403 tenant_blockeduntil the company is reactivated. - The key identifies an integration, not a person. It acts for the company, and for any merchant of that company.
A dashboard user signs in and receives a token pair. This includes a merchant login: a user that belongs to one merchant of your company.
curl -X POST "https://api.goldrock.live/api/public/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{
"username": "ahmed@your-company.example",
"password": "YOUR_PASSWORD"
}'const response = await fetch("https://api.goldrock.live/api/public/v1/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"username": "ahmed@your-company.example",
"password": "YOUR_PASSWORD"
}),
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/auth/login';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'username' => 'ahmed@your-company.example',
'password' => 'YOUR_PASSWORD',
], JSON_UNESCAPED_UNICODE),
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"POST",
"https://api.goldrock.live/api/public/v1/auth/login",
json={
"username": "ahmed@your-company.example",
"password": "YOUR_PASSWORD",
},
timeout=30,
)
print(response.status_code, response.json()){
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "q3kZ0m8w...",
"tokenType": "Bearer",
"expiresIn": 900
}accessTokenis a JWT. Send it asAuthorization: Bearer <accessToken>untilexpiresInseconds have passed.refreshTokenis single use. When you use it, you receive a new pair and the old refresh token stops working. Always store the new one.usernameis the dashboard username or the e-mail address.- What the user may do is decided by the dashboard permissions of that user.
GET /auth/melists the scopes those permissions cover. - For the shipment write operations the permission is checked exactly:
POST /shipmentsneedsorders:create,PUT /shipments/{trackingNumber}needsorders:updateandPOST /shipments/{trackingNumber}/cancelneedsorders:cancel. Holding only some other permission of the same area is not enough, and the answer is403 forbidden. An API key is different: its scope alone decides (shipments:writecovers all three).
curl "https://api.goldrock.live/api/public/v1/auth/me" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"const response = await fetch("https://api.goldrock.live/api/public/v1/auth/me", {
method: "GET",
headers: {
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
},
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/auth/me';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_ACCESS_TOKEN',
],
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"GET",
"https://api.goldrock.live/api/public/v1/auth/me",
headers={
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
},
timeout=30,
)
print(response.status_code, response.json()){
"authMethod": "password",
"company": {
"id": "0f8fad5b-d9cb-469f-a165-70867728950e",
"name": "Fast Express",
"slug": "fast-express"
},
"user": {
"id": "16fd2706-8baf-433b-82eb-8c7fada847da",
"name": "Ahmed Ali"
},
"apiKey": null,
"scopes": [
"geography:read",
"merchants:read",
"pricing:read",
"shipments:read"
],
"permissions": [
"merchants:view",
"orders:read"
]
}When the access token is about to expire (or an API call answers 401), exchange the refresh token. Do it on your server, and serialise it: if two requests refresh with the same token at the same time, only one wins.
curl -X POST "https://api.goldrock.live/api/public/v1/auth/refresh" \
-H "Content-Type: application/json" \
-d '{
"refreshToken": "YOUR_REFRESH_TOKEN"
}'const response = await fetch("https://api.goldrock.live/api/public/v1/auth/refresh", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"refreshToken": "YOUR_REFRESH_TOKEN"
}),
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/auth/refresh';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'refreshToken' => 'YOUR_REFRESH_TOKEN',
], JSON_UNESCAPED_UNICODE),
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"POST",
"https://api.goldrock.live/api/public/v1/auth/refresh",
json={
"refreshToken": "YOUR_REFRESH_TOKEN",
},
timeout=30,
)
print(response.status_code, response.json())If the refresh token is rejected (401 auth.invalid_refresh_token) the session is over: ask the user to sign in again.
// Server-side token manager for the password login (Node.js 18+).
// Keeps one session, refreshes it shortly before it expires, and never refreshes twice at the same time.
const API = `${process.env.LASTMILE_API_URL}/api/public/v1`;
let session = null; // { accessToken, refreshToken, expiresAt }
let inflight = null; // the refresh or login that is currently running
async function post(path, body) {
const response = await fetch(`${API}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw Object.assign(new Error(data.message), { code: data.code, status: response.status });
return data;
}
function store(tokens) {
// Refresh one minute early. The refresh token is single use: always keep the new one.
session = {
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
expiresAt: Date.now() + (tokens.expiresIn - 60) * 1000,
};
return session.accessToken;
}
async function signIn() {
return store(await post("/auth/login", { username: process.env.LASTMILE_USER, password: process.env.LASTMILE_PASSWORD }));
}
export async function getAccessToken() {
if (session && Date.now() < session.expiresAt) return session.accessToken;
inflight ??= (async () => {
try {
if (session) {
try {
return store(await post("/auth/refresh", { refreshToken: session.refreshToken }));
} catch (error) {
if (error.status !== 401) throw error; // the session is over: sign in again below
}
}
return await signIn();
} finally {
inflight = null;
}
})();
return inflight;
}
export async function lastmile(path, options = {}) {
const token = await getAccessToken();
return fetch(`${API}${path}`, {
...options,
headers: { ...options.headers, Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
});
}A merchant login can only see and book its own merchant's shipments, read its own merchant record and addresses, and quote prices. It cannot edit or cancel shipments, manage merchants or read other merchants: those answer 403 or 404. When it creates a shipment it always sends as its own merchant, and it cannot use a custom sender. This makes it the right tool for a merchant portal.
Failed sign-ins count towards the same account lock and per-network throttling as the dashboard. Repeated failures answer 429 auth.login_temporarily_blocked or 403 auth.account_locked. login is limited to 30 requests per minute per IP address and refresh to 10. The company must have the API channel on, otherwise login answers 403 channel_disabled and no token is issued.
| You are building | Use |
|---|---|
| A company website or web shop that tracks, quotes and books shipments | API key, called from your server |
| A back-office integration, a script, a spreadsheet automation | API key |
| A portal where each merchant sees only its own shipments | Password login with the merchant logins |
| Something that must act as one specific dashboard user | Password login |
As a rule: if no human types credentials into your system, use a key. If a human does and you want the platform to decide what they may see, use the login.
- Never put the key or secret in browser or mobile code. Anything shipped to a device can be read. Call the API from your own server and let the browser call your server. The website tutorial shows the pattern. Browser calls to the API are also subject to CORS, which is another reason to go through a server.
- One key per integration. Name it after what uses it. Then you can revoke one without breaking the rest, and you can see which integration is calling.
- Least scopes. A tracking page needs
shipments:readonly. A price calculator needspricing:readandgeography:read. Do not tick everything. - Store secrets as secrets. Environment variables or a secret manager, never source control, logs or support tickets. Mask them in logs.
- Rotate and revoke. Set an expiry date on keys when you can, create a replacement before the old one expires, and revoke any key that may have leaked. A revoked key stops working immediately.
- Do not store passwords. Keep refresh tokens in an encrypted server-side session, not in
localStorage. - Verify webhooks. Check the signature of every delivery, see Webhooks.