Skip to main content

Start, refresh and end a customer session

What you will build​

Your server signs a customer in by making a one-time sign-in token, and the customer's page exchanges it for a customer session. You then keep the session alive with the refresh token and end it when the customer signs out.

A session is a pair of tokens: an access token that opens the customer's own calls of the Client API, and a refresh token that renews the pair. Every call here is a direct HTTP call: cURL from your server, fetch from the page.

Before you start​

You need an app with a publishable key: see Manage an app's keys and allowed origins. The page runs on one of the app's allowed origins.

Your server's API client needs the customer_sessions.create permission. The owner role holds it, and so does the admin role of an account made recently; no other default role does. A token made with it lets its holder act as the customer, so give it to few clients.

If your app already signs people in and can sign a token, read Sign customers in with your own sign-in instead.

Steps​

Start a session​

  1. Make the sign-in token on your server. Send a POST request to /v1/customer-sessions with either customer (the customer's ID) or customer_reference (your own reference), one of the two. The response is 201 and holds token, customer and expires_at. The token works once, for 5 minutes. See Create a customer sign-in token.

A customer that is unknown or deleted answers 404, naming the field. A blocked customer answers 409 with blocked.

  1. Hand the token to the customer's page by your own way, such as the answer to your own sign-in call. Never keep it: it is the whole credential for one sign-in.

  2. Exchange it from the page. Send a POST request to /v1/client/auth/token with the publishable key in Black-Publishable-Key and the token. A page sends no Authorization header. The response is 201 and holds the customer's session. See Exchange a sign-in token for a customer session.

const response = await fetch('https://api.black.example/v1/client/auth/token', {
method: 'POST',
headers: {
'Black-Publishable-Key': 'pk_test_…',
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: signInToken }),
});

const session = await response.json();
  1. Read the session. It holds id, customer, app, access_token and access_token_expires_at, refresh_token and expires_at. Both tokens are shown once, with Cache-Control: no-store.

A sign-in token that is malformed, unknown or of another environment answers 401 with sign_in_token_invalid. One used before answers 401 with sign_in_token_used, and one older than 5 minutes sign_in_token_expired. Make a new token for each of them.

Use the access token​

  1. Send the access token with the key in every call about the customer, as Authorization: Bearer <access token>. For example, GET /v1/client/customer reads the customer's own profile: see Show a signed-in customer their own account.

The access token lasts an hour and never past the session's end. The refresh token lasts until the session ends, which is by default 30 days after the sign-in. The account's customer_session_days setting changes that from 1 to 90 days, and use never extends it.

A call without a token answers 401 with customer_session_required. A value that is not a token of this app and environment answers customer_session_invalid. A token past its hour, a session that ended and a session of a customer who is blocked or deleted answer customer_session_expired: refresh, and when the refresh is refused too, sign the customer in again.

Refresh the pair​

  1. Renew the pair before the hour ends. Send a POST request to /v1/client/auth/refresh with the key and the refresh_token. Send the refresh_token in the JSON body, never in the address: a request to /v1/client/auth/refresh with refresh_token in the query string is refused with 400 and credentials_in_query_string. The response is 200 and holds a new pair. See Refresh a customer session.
const response = await fetch('https://api.black.example/v1/client/auth/refresh', {
method: 'POST',
headers: {
'Black-Publishable-Key': 'pk_test_…',
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: session.refresh_token }),
});

if (response.status === 401) {
signTheCustomerInAgain();
}
  1. Replace both tokens with the new pair. A refresh token works once.

Know what a refresh used twice does​

  1. Expect a repeat inside 10 seconds to be answered. Two tabs of one site, or a retry after a lost answer, send the same refresh token again. A repeat within 10 seconds of the first use gets the same pair the first use made, 200, and nothing new is made. Black counts whole seconds, so the window can run to 11 seconds; rely on 10.

  2. Expect a later repeat to end the session. The same refresh token sent after the window, or once its pair is no longer valid, ends the whole session at once and answers 401 with customer_session_expired. Black records customer_session.reused_refresh_token, because a stolen copy and the real one cannot both stay signed in. The customer signs in again.

Keep the tokens​

  1. Keep the tokens where your app keeps a session secret, and nowhere else. Black sets no cookie on the Client API, so your page or app holds them.
  • In a web page, keep the access token in a variable in memory, and the refresh token in the storage you choose for a session. Any script on the page can read browser storage, so keep scripts you do not control off the page.
  • In a mobile app, keep both in the phone's secure storage, the Keychain on iOS and the Keystore on Android.
  • Never write a token to a log, an error report or a URL.

Sign out and end every session​

  1. Sign the customer out. Send a POST request to /v1/client/auth/sign-out with the key and the customer's access token. The response is 204. It ends every session of the customer in the environment, on every app and device, not only this one. See Sign out a customer. Signing out twice ends nothing more.

  2. End every session from your server. Send a POST request to /v1/customers/{id}/end-sessions. The response is 200 and holds the customer. Each session ends with the reason ended_by_account. See End a customer's sessions.

Blocking or deleting a customer ends every session too, and unblocking brings none back. A password reset ends every session, and a change of password every other one. Turning a sign-in method off does not end the sessions it made. Each end records customer_session.ended, with the reason.

A runnable sample​

This sample makes a customer, makes the sign-in token on the server, exchanges it as the page does, reads the customer's own profile, refreshes the pair, sends the same refresh token again inside the 10 seconds, signs out and shows the access token refused. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads the IDs, the key and the tokens from the responses, and needs sed. The customer's reference is made new on each run, and each write waits a second because a test environment takes five writes a second.

TOKEN=PLACEHOLDER_ACCESS_TOKEN
REFERENCE="session-$(date +%s)"

APP=$(curl --silent --request POST https://api.black.example/v1/apps \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Session Demo","kind":"web","allowed_origins":["https://app.example.com"]}' \
| sed -n 's/.*"id":"\(app_[0-9a-z]*\)".*/\1/p')
sleep 1

KEY=$(curl --silent --request POST "https://api.black.example/v1/apps/$APP/publishable-keys" \
--header "Authorization: Bearer $TOKEN" \
| sed -n 's/.*"\(pk_test_[0-9A-Za-z]*\)".*/\1/p')
sleep 1

curl --silent --request POST https://api.black.example/v1/customers \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"name\":\"Sana\",\"email\":\"$REFERENCE@example.com\",\"external_reference\":\"$REFERENCE\"}"
sleep 1

SIGN_IN_TOKEN=$(curl --silent --request POST https://api.black.example/v1/customer-sessions \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"customer_reference\":\"$REFERENCE\"}" \
| sed -n 's/.*"token":"\(cst_[0-9A-Za-z]*\)".*/\1/p')
sleep 1

SESSION=$(curl --silent --request POST https://api.black.example/v1/client/auth/token \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"token\":\"$SIGN_IN_TOKEN\"}")
ACCESS=$(echo "$SESSION" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')
REFRESH=$(echo "$SESSION" | sed -n 's/.*"refresh_token":"\([^"]*\)".*/\1/p')

curl --silent --request GET https://api.black.example/v1/client/customer \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Authorization: Bearer $ACCESS"

REFRESHED=$(curl --silent --request POST https://api.black.example/v1/client/auth/refresh \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"refresh_token\":\"$REFRESH\"}")
NEW_ACCESS=$(echo "$REFRESHED" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')

curl --silent --request POST https://api.black.example/v1/client/auth/refresh \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"refresh_token\":\"$REFRESH\"}"

curl --silent --request POST https://api.black.example/v1/client/auth/sign-out \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Authorization: Bearer $NEW_ACCESS"

curl --silent --request GET https://api.black.example/v1/client/customer \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Authorization: Bearer $NEW_ACCESS"

The app, its key, the customer, the sign-in token and the session answer 201. The profile read answers 200. The refresh answers 200 with a new pair, and the same refresh token sent again at once answers 200 with that same pair. The sign-out answers 204. The read with the refreshed access token then answers 401 with customer_session_expired, because the session has ended.

What to do next​