Sign customers in with email and password
What you will build
You let a customer sign up and sign in to your app with an email and a password, with no sign-in of your own. Black keeps the password, emails the links that prove an email and reset a password, and answers each sign-up or sign-in with a customer session: an access token and a refresh token that the customer's page or app uses for the calls of the Client API.
You turn the method on, build the sign-up and sign-in calls, handle the verification and reset links, let a customer change a password, read each refusal, and list or remove a customer's identities from your server. An identity is one way a customer signs in: for this method, the customer's email and password.
Before you start
You need an app with a publishable key, in the environment where you sign customers in. Create the app with Register an app and its key with Create a publishable key. A publishable key is an identifier, not a secret: your page or app sends it in the Black-Publishable-Key header. A web app is called from a page whose origin is one of its allowed origins.
The page that receives the links must be on one of the app's allowed origins, because Black puts each link's token in the address of that page.
A mobile app (kind ios or android) has no allowed origins. It receives the links on its return URLs, or it receives a code instead: see "Use the links and codes in a mobile app".
The settings are changed by the account's own API client, or by its vendor with Black-Account, as every other setting is: see Change account settings.
Steps
Turn the method on
-
Turn on the password method. Send a
PATCHrequest to/v1/settingswith{"sign_in":{"password":true}}. The response holds all the settings as they are after the change. See Change an environment's settings. The method is off in a new environment. -
Choose what sign-up asks for. In the
sign_upobject of the same settings,nameandphoneeach takeoff,optionalorrequired, and both startoff. The email is always asked. A field set tooffis refused when a sign-up sends it, anoptionalfield may be left empty and arequiredfield must be sent.
While the method is off, every call of this guide except the email verification answers 403 with sign_in_method_disabled, before Black reads the request. Turning the method off does not end the sessions it already made.
Sign a customer up
-
Send the sign-up. From the customer's page or app, send a
POSTrequest to/v1/client/auth/sign-upwith the publishable key inBlack-Publishable-Keyand the customer'semail,passwordandredirect_url, and thenameandphoneyour settings ask for. A page sends noAuthorizationheader.redirect_urlis the address of your page that receives the verification link. A mobile app follows its own rule: see "Use the links and codes in a mobile app". See Sign up an auth of a client. -
Read the session. The response is
201and holds the customer's session: itsid, itscustomer, itsapp,access_tokenandaccess_token_expires_at,refresh_tokenandexpires_at. Both tokens are shown once: keep them where the customer's page or app keeps its session, and never in a log. The access token lasts an hour. Renew the pair before the hour ends with Refresh a customer session.
The sign-up makes a new customer, with the email as their email identity, and emails the customer a link that proves the email. A sign-up never joins a customer you already made with the same email, because nothing yet shows that the person owns the inbox: that customer stays apart.
Choose a password
A password is at least 12 characters, is not in the public list of breached passwords, and is at most 72 bytes. A letter outside plain English counts as two bytes or more, so a password of such letters reaches the limit sooner. Black asks the breach list with only the first five characters of a fingerprint of the password, never the password. A password that breaks the rule is refused with 422 and parameter_invalid, naming password.
An email that holds a letter outside plain English that changes when lowered, such as the Kelvin sign, is refused with 422 and parameter_invalid, naming email, on the sign-up, the sign-in and the request for a reset link. Such a letter could name another person's mailbox.
Sign a customer in
- Send the sign-in. From the customer's page or app, send a
POSTrequest to/v1/client/auth/sign-inwith the publishable key and the customer'semailandpassword. The response is201and holds a session, as the sign-up's does. See Sign in an auth of a client.
A wrong password, an email that no customer signs in with and a body that is malformed answer the same 401 with sign_in_failed, after the same wait, so the answer tells nothing about which emails exist. Black takes about a second to answer a refusal. Five failed sign-ins in a minute for one email give 429 with rate_limited and a Retry-After header that holds the seconds to wait; a sign-in that succeeds clears the count.
Prove an email with the verification link
Black emails the link at sign-up, from the account's name. The link is your redirect_url with the token in its fragment, #black_verify=<token>, so neither your servers nor any log between them sees the token. The link works once and for 24 hours.
-
Read the token on your page. The page at
redirect_urlreadsblack_verifyfrom the fragment of its own address. -
Send it to Black. Send a
POSTrequest to/v1/client/auth/email/verifywith the publishable key and thetoken. The response is204. See Create an email confirmation of an auth. The email counts as proved from then on, and keeps the moment of the first proof. This call answers whichever sign-in methods are on.
The call may also carry the customer's session in Authorization: Bearer. A session that is sent and is not valid answers 401, with the code of the refusal (see the call's page), and the link is not used. With no Authorization header the call works as before. The session decides whether the customer's password counts as proved: see the next section.
Know what secures an account
A sign-up can name an email that belongs to someone else, and the person who signs up chooses the password. Black does not let that password take the account over. A password counts as proved only when the owner of the inbox has shown it is theirs, in one of two ways:
- A reset completed with the emailed link sets it.
- The email is proved with the verification link, sent with the session of the same customer that the password started, at sign-up or at sign-in. A link used with no session, or with the session of another customer, proves the email and leaves the password unproved.
When a customer later signs in with a method that proves their email, and their password is not proved, Black secures the account. Every session of the customer ends, on every device, with the end reason account_secured, and each ended session records customer_session.ended. The password is removed, and Black emails the owner of the email that their account was secured. From then on only the method that proves the email signs the customer in. The customer sets a new password with a reset. A proved password stays, and no session ends.
A link that is expired, already used, of the other kind or for a customer that was deleted answers 422 with link_invalid, naming token, and changes nothing.
Ask for a new link or code
Ask for a new verification link, or a new code, when the one Black emailed has expired or the customer lost it.
-
Send the request. Send a
POSTrequest to/v1/client/auth/email/verify/requestwith the publishable key and the customer's access token inAuthorization: Bearer. The call needs the customer's session. The body holdsredirect_url, by the rule of the sign-up: a website sends an address on one of the app's allowed origins, and a mobile app with return URLs sends exactly one of them. A mobile app with noreturn_urlssends noredirect_url, and Black emails it a code instead: see "Use the links and codes in a mobile app". See Send the signed-in customer's email verification again. -
Read the answer. The response is always
202, whatever the state of the customer's email, so the answer does not show it. A customer whose email is not proved gets a new link or code by email, valid for 24 hours. Every earlier link and code stops working: only the newest one proves the email. A customer whose email is already proved is sent nothing.
One request a minute is taken for one customer: a second request inside the minute answers 429 with rate_limited and a Retry-After header that holds the seconds to wait. The limit on sign-ins for one caller address counts the call as well. The call takes no Idempotency-Key.
Reset a password
-
Ask for a link. Send a
POSTrequest to/v1/client/auth/password-reset/requestwith the publishable key, the customer'semailand aredirect_url. The response is always202, in the same time, whether or not the email is a customer's, so the answer does not show who has an account. Black emails a link only to a customer who is neither deleted nor blocked. One request a minute is taken for one email: more give429. See Create a password reset link of an auth. -
Read the token on your page. The link leads to your
redirect_urlwith#black_reset=<token>in the fragment. It works once and for 60 minutes. -
Send the new password. Send a
POSTrequest to/v1/client/auth/password-resetwith the publishable key, thetokenand the newpassword, which follows the rule above. The response is204. See Create a password reset of an auth.
A reset ends every session of the customer, on every device, and counts their email as proved. A reset also makes every earlier reset link unusable: an older link answers 422 with link_invalid.
Use the links and codes in a mobile app
A mobile app opens the emailed link from its own universal link (iOS) or app link (Android). You register the addresses it opens, then the app sends one of them as redirect_url. An app with no registered address gets a code instead of a link.
-
Register the return URLs. Send a
POSTrequest to/v1/appswithkindset toiosorandroid, thebundle_idorpackage_name, andreturn_urls: 1 to 10 addresses, each anhttpsaddress on a domain name. A custom scheme of the app's own is refused, because any other app on the phone can claim it and the link carries the token. An IP address, a single-word host such aslocalhost, a user name, a query and a fragment are refused too. To change the list, send aPATCHrequest to the app with the newreturn_urls. A link already emailed keeps working until it expires. See Register an app. -
Send the return URL. At the sign-up and at the request for a reset link, the app sends a
redirect_urlthat is exactly equal to one of itsreturn_urls: no longer path, no shorter path, no query. Any other address answers422withparameter_invalid, namingredirect_url, and nothing is sent. The email then holds that address with the token in its fragment, as on a website. -
Read the link in the app. The app reads the full link it is opened with and takes the token from the part after
#, then sends it as in the steps above. Test this on a device, iOS and Android, before you ship: check that your app receives the whole link, fragment included, when the customer opens it from the mail. If the app is not installed, the link opens the address in the browser.
A mobile app with no return_urls sends no redirect_url: a redirect_url sent by such an app answers 422 with parameter_invalid. The sign-up and the request for a reset link then email an 8-digit code, shown as two groups of four, such as 1234 5678. The code is in the body of the email only. A web app is unchanged and always sends its redirect_url.
-
Prove an email with the code. Send a
POSTrequest to/v1/client/auth/email/verifywith the publishable key, the customer's session inAuthorization: Bearerand thecode, in place of thetoken. The response is204. Without a session the call answers401withcustomer_session_required. -
Reset a password with the code. Send a
POSTrequest to/v1/client/auth/password-resetwith the publishable key, the customer'semail, thecodeand the newpassword, in place of thetoken. The response is204. Send either atokenor acode, never both. -
Use the same rule for the other two mail paths. The emailed sign-in link and the change of a customer's email follow the rule of steps 11 to 15: with
return_urls, theredirect_urlequals one of them and the mail holds a link; without them, the app sends noredirect_urland the mail holds a code. A card'sreturn_urlfollows it too. See Sign customers in with an email link and Show a signed-in customer their own account.
A code lives as long as the link it replaces: 24 hours for an email's proof and 60 minutes for a reset. One code is live at a time: a new request replaces the earlier code. A code is used once. A space between the two groups is accepted.
A code that is wrong, used, expired, replaced or tried too often, and an email that is no customer's, all answer 422 with link_invalid, naming code. Five wrong tries end the live code, and the customer asks for a new one. Ten requests that send a code in an hour for one email give 429 with rate_limited and a Retry-After header.
Let a customer change their password
- Send the change. From the customer's page or app, send a
POSTrequest to/v1/client/auth/passwordwith the publishable key, the customer's access token inAuthorization: Bearer, thecurrent_passwordand the newpassword. The response is204. See Password an auth of a client.
A wrong current_password is refused with 422 and parameter_invalid, naming current_password. Five wrong tries in a minute for one customer give 429 with rate_limited and Retry-After, so a stolen session cannot guess the password; a change that succeeds clears the count. A change ends every other session of the customer and keeps the one it was made in. It also makes any reset link that was emailed before it unusable.
List and remove a customer's identities
From your server, with a server credential, read the identities a customer signs in with, the oldest first: send a GET request to /v1/customers/{id}/identities, which needs the permission customers.read. See List the identities of a customer. Each identity names its provider, its email, whether the email is proved in email_verified and the moment in verified_at. The password is never shown.
To stop one identity signing the customer in, send a DELETE request to /v1/customers/{id}/identities/{identity}, which needs customers.write. See Delete an identity of a customer. The response is 200 and holds the identity as it was. Black records customer_identity.removed and an activity entry that names the caller. The sessions that identity made go on until they end: to end them, see End a customer's sessions. An identity of another customer, or a customer of another environment, answers 404.
Handle each refusal
Each refusal is an error with a code: see Errors for every code.
403sign_in_method_disabled. The password method is off. Turn onsign_in.password, then send the call again.409email_in_use. A customer who signs in with Black already uses the email, or the email is proved on another customer. Send the customer to sign in, or to reset the password.401with a session sent to the email verification. The session is expired, ended or not valid. The link is not used. Ask the customer to sign in again, then send the call again, or send it with no session.401sign_in_failed. The email and password do not match. Ask the customer to try again or to reset the password.422parameter_invalid. A field is wrong. The error'sparamnames it: thepassword, theemail, theredirect_url(a website's must be on one of the app's allowed origins, a mobile app's must equal one of its return URLs, and a mobile app with none sends none), or anameorphonethat your settings do not allow.422link_invalid. The link or the code is expired, used, replaced, or of the other kind, or the code was tried wrongly five times. Ask for a new link or a new code.409blocked. The customer is blocked, and the password is right. No session is made. Unblock the customer first: see Block a customer.429rate_limited. The limit of the call is reached. Wait for the secondsRetry-Aftergives, then send the call again. Too many tries of a code give the same answer.403origin_not_allowedand401publishable_key_invalid. The request does not come from one of the app's allowed origins, or the key is missing, unknown or revoked. Send the call from the app's page with the app's current key.
A runnable sample
The links arrive by email, so a sample cannot read a token from a link, and this sample does not verify an email or reset a password. It registers an app and its publishable key, turns the method on, signs a customer up and in, asks for a new verification link, changes the password, signs in with the new password, lists the customer's identities from the server, and turns the method off. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads the IDs, the key and the customer's session from the responses, and needs sed. The email is made new on each run, the passwords are for the sample only, and each write waits a second because a test environment takes five writes a second.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
EMAIL="demo-$(date +%s)@example.com"
APP=$(curl --silent --request POST https://api.black.example/v1/apps \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Password Demo","kind":"web","allowed_origins":["https://app.example.com"]}' \
| sed -n 's/.*"id":"\(app_[0-9a-z]*\)".*/\1/p')
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')
curl --silent --request PATCH https://api.black.example/v1/settings \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"sign_in":{"password":true}}'
SIGN_UP=$(curl --silent --request POST https://api.black.example/v1/client/auth/sign-up \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"email\":\"$EMAIL\",\"password\":\"sample-password-one\",\"redirect_url\":\"https://app.example.com/verify\"}")
CUSTOMER=$(echo "$SIGN_UP" | sed -n 's/.*"customer":"\(cus_[0-9a-z]*\)".*/\1/p')
SIGNED_IN=$(curl --silent --request POST https://api.black.example/v1/client/auth/sign-in \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"email\":\"$EMAIL\",\"password\":\"sample-password-one\"}")
SESSION=$(echo "$SIGNED_IN" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')
curl --silent --request POST https://api.black.example/v1/client/auth/email/verify/request \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Authorization: Bearer $SESSION" \
--header "Content-Type: application/json" \
--data '{"redirect_url":"https://app.example.com/verify"}'
curl --silent --request POST https://api.black.example/v1/client/auth/password \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Authorization: Bearer $SESSION" \
--header "Content-Type: application/json" \
--data '{"current_password":"sample-password-one","password":"sample-password-two"}'
curl --silent --request POST https://api.black.example/v1/client/auth/sign-in \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"email\":\"$EMAIL\",\"password\":\"sample-password-two\"}"
curl --silent --request GET "https://api.black.example/v1/customers/$CUSTOMER/identities" \
--header "Authorization: Bearer $TOKEN"
curl --silent --request PATCH https://api.black.example/v1/settings \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"sign_in":{"password":false}}'
The first two requests answer 201: the app, then its key. The settings change answers 200 and holds sign_in.password as true. The sign-up and the sign-in answer 201 with a session. The request for a new verification link answers 202. The change of password answers 204 with no body. The sign-in with the new password answers 201. The list answers 200 and holds the customer's one email identity, and the last settings change answers 200 and switches the method off.
What to do next
- Read each call's fields and answers in Sign up an auth of a client and Sign in an auth of a client.
- Read how a customer you already sign in elsewhere gets a session in Sign customers in with your own sign-in.
- Read how to change settings, and which client may change which, in Change account settings.
- Read how to end a customer's sessions in End a customer's sessions.
- Read every error code in Errors.