API authentication
LibrePhotos secures most API endpoints and requires authentication by default. If you see 401 Unauthorized or 403 Forbidden responses when calling API endpoints, you likely need to authenticate using one of the supported methods below.
Authentication methods​
- JWT (recommended): Obtain a short-lived access token via
/api/auth/token/obtain/and present it as a Bearer token. The obtain and refresh endpoints also set anHttpOnlyjwtcookie that the browser can reuse (see Cookie flags). - Basic authentication: For simple scripts or local testing, you can use HTTP Basic auth. Do not use Basic auth across untrusted networks.
Session authentication is not enabled for API endpoints. The frontend uses JWT behind the scenes, not Django sessions.
Obtain a JWT access token​
Request an access token using your LibrePhotos username and password:
curl -X POST "http://<backend>/api/auth/token/obtain/" \
-H 'Content-Type: application/json' \
-d '{"username":"myuser","password":"mypassword"}'
You will receive a JSON response with access and refresh tokens. The response also sets a jwt cookie with the access token for browser use.
Example response:
{
"refresh": "<refresh_token>",
"access": "<access_token>"
}
Refresh the access token when it expires using:
curl -X POST "http://<backend>/api/auth/token/refresh/" \
-H 'Content-Type: application/json' \
-d '{"refresh":"<refresh_token>"}'
Access tokens are short-lived and expire after 5 minutes; refresh tokens are valid for 7 days by default. Refreshing returns a new access token only, so keep reusing the same refresh token until it expires. A long-running script should refresh at least every 5 minutes, or simply retry once against /api/auth/token/refresh/ whenever a call returns 401. The access-token lifetime is fixed; the refresh-token lifetime can be changed with the REFRESH_TOKEN_DAYS environment variable on the backend container.
New in 1.5.0 Add "remember_me": true to the obtain request for a refresh token that lasts REMEMBER_ME_DAYS (30 by default) instead, as the Remember me checkbox on the login page does. Its tokens carry a remember_until claim with the refresh token's expiry, the obtain and refresh responses give the jwt cookie a matching Max-Age, and the web app does the same for its access and refresh cookies. With REMEMBER_ME_DAYS=0 the flag is ignored. See Sign-in sessions.
Usernames ignore case​
Every way to sign in finds an account whatever the case of the username: the token endpoint, Basic auth and the Django admin. The account with the exact name is tried first, then every other account of that name, the lower-case one before the oldest, until the password fits (AnyCaseUsernameBackend). Two names are the same when they are equal after Unicode NFKC normalisation and lower-casing, so Jürgen and JÜRGEN are one name too, on PostgreSQL and on SQLite. Failed attempts with different spellings of one name count against the same limit.
Not released yet (comes after 1.7.0) POST /api/user/ (sign-up, first-time setup and an admin adding a user) and a new username in PATCH /api/manage/user/<id>/ store the name in lower case, so the username in the answer can differ from the one you sent. A name that another account has in any case answers 400 with the error on username. Sending a user's current name back unchanged keeps it as it is. Up to 1.7.0, sign-up and renaming compared the exact name and stored it as sent.
Not released yet (comes after 1.7.0) POST /api/user/ needs password and first_name only. Without a username the server makes one from the name (username_for in api/accounts/usernames.py, under the same lock as every sign-up) and sends it back in the answer, so {"first_name": "Heinz", "last_name": "Müller", "password": "..."} answers with "username": "heinz". email and last_name may be left out. Up to 1.7.0 all five were required.
Not released yet (comes after 1.7.0) The username field of a sign-in also takes the full name of an account (first_name and last_name, one space between them, any case) when no username matches. When two active accounts have that name, the one whose password was sent signs in; when both have it, or more than two accounts have the name, nobody does. Failed attempts are limited per client address and the first name that was typed (sign_in_identity in api/accounts/usernames.py), so heinz and Heinz Müller share a limit whether or not there is such an account. With Basic auth, a successful sign-in with a name two accounts share counts as an attempt too.
Not released yet (comes after 1.7.0) GET /api/firsttimesetup/ also says what runs there: installation is windows_installed, windows_zip, macos or server (Docker and source).
Not released yet (comes after 1.7.0) The endpoints under /api/own-computer/ belong to the Windows and Mac apps and their use without a password. They are for the sign-in page on the computer that runs LibrePhotos, not for scripts: an account without a password has no API access except through the window the program opened. Docker answers 409 not_supported.
Code that makes or renames an account calls hold_signups() in its transaction, then is_taken() and new_username() from api/accounts/usernames.py; the model is verification/auth/UsernameCase.tla.
Revoke a refresh token (logout)​
To invalidate a refresh token — on logout, or to revoke one you think has leaked — blacklist it:
curl -X POST "http://<backend>/api/auth/token/blacklist/" \
-H 'Content-Type: application/json' \
-d '{"refresh":"<refresh_token>"}'
No Authorization header is needed; the refresh token itself is the credential. On success you get HTTP 200 with an empty JSON body. Blacklisting stops the refresh token from minting new access tokens, but any access token it has already issued stays valid until it expires (5 minutes by default), so revocation is not instantaneous. This is the same endpoint the web frontend calls when you log out.
The response also clears the jwt, access and refresh cookies, whatever the blacklist answers: a refresh token that is already blacklisted (401), expired, or missing from the body (400) still signs the browser out. The web app calls the endpoint on every logout, because the jwt cookie is HttpOnly and only the server can delete it. Clearing the cookie does not revoke the access token in it: a copy taken before logout keeps working until it expires.
New in 1.4.0 Up to 1.3.0, the endpoint only blacklisted the token and the web deleted the cookies itself.
Not released yet (comes after 1.7.0) A session ends when the account's password changes. Every refresh token carries a password_fingerprint claim, a keyed hash of the stored password hash, and every access token minted from it copies the claim. /api/auth/token/refresh/ answers 401 when the claim no longer matches the account, and so does every request authenticated with such an access token (Authorization: Bearer or the jwt cookie), with the code password_changed. So a token from before the change, or from a sign-in with the old password that was still running when the password changed, stops working at once, whichever way the password changed (manage.py changepassword included). On top of that, /api/auth/password/reset/confirm/, a PATCH of /api/user/<id>/ with a new password, /api/manage/user/<id>/ for someone else, and manage.py createuser --update and createadmin --update blacklist the account's refresh tokens. Sending the password the account already has changes nothing. A refresh token of an account that was deleted answers 401 too.
Not released yet (comes after 1.7.0) To change your own password or email address with PATCH /api/user/<id>/, send your current password as current_password; without it the answer is 400 with the code current_password_required, and with a wrong one 400 with current_password_incorrect. Wrong current passwords have a budget of their own per sign-in, whatever address they come from (CURRENT_PASSWORD_THROTTLE_RATE, 10 an hour), and a looser one for the whole account (CURRENT_PASSWORD_ACCOUNT_THROTTLE_RATE, 30 an hour). A sign-in is the session a token comes from: the tokens a sign-in and its refreshes give out carry the same sign_in_id claim. Once a budget is used up the answer is 429, also to the right password, until the window moves on; the account's other sign-ins can still make the change until the account's budget is spent too. Only wrong ones are counted, and they do not count against sign-in, nor sign-ins against them. The has_password field of /api/user/<id>/ says whether the account has a password of its own. An account without a password of its own (one that only ever signed in over SSO) has nothing to confirm with, so it may change its password or email address only within 10 minutes of signing in; later the answer is 403 with the code reauthentication_required, and signing in again fixes it. When the password changes between the check and the save (a reset link used at the same moment), the change is refused with 409 and the code password_changed. An admin changing another user's details does not need it, and /api/manage/user/<id>/ refuses changes to your own password or email address (code use_profile). The answer to a change of your own password sets new jwt, access and refresh cookies, which the web app picks up, so the browser that made the change stays signed in; the new session ends when the old one would have, "Remember me" included. A client that does not read cookies signs in again with the new password, as the mobile app does. Django rehashes a password at its next sign-in when a Django update raises the hashing cost; that also ends the account's other sessions once.
Not released yet (comes after 1.7.0) Tokens issued before 1.8.0 carry no fingerprint: they are accepted, and a password change ends them through the blacklist only. That exception goes away in the first release made REMEMBER_ME_DAYS (30 by default) or more after 1.8.0, when the last of those tokens has expired.
Call APIs using the JWT access token​
Include the token in the Authorization header:
curl -H 'Authorization: Bearer <access_token>' \
"http://<backend>/api/photos/"
In a browser, the jwt cookie set by the obtain and refresh endpoints is sent automatically, which is how <img> and <video> requests for media authenticate. For the standard JSON endpoints the frontend adds an Authorization: Bearer header, just as a script would, and those endpoints ignore the cookie. A few endpoints accept the cookie as well — see Endpoints that also accept the jwt cookie below.
Endpoints that also accept the jwt cookie​
These endpoints accept an Authorization: Bearer <access_token> header like every other endpoint, and fall back to the jwt cookie when there is no bearer header. When both are sent, the header wins:
- Media files —
GET /media/photos/<image_hash>(originals), plus the thumbnail, square-thumbnail, face-crop, avatar and embedded-media paths (/media/thumbnails_big/...,/media/square_thumbnails/...,/media/faces/...,/media/avatars/...,/media/embedded_media/...) and generated archives at/media/zip/<name>. Basic auth (curl -u user:pass) works here too. - Chunked uploads —
POST /api/upload/andPOST /api/upload/complete/.
Media belonging to an active public or shared album, and photos made public, are served without any credential. An expired or otherwise unusable cookie counts as no credential there: public media is still served, and anything else answers 403 with an X-Media-Error: authentication header, telling you to sign in again. An invalid bearer header answers 401, as on every other endpoint.
Releases before 1.2.0 read only the cookie on the media endpoints and ignore the header there. The cookie works on every version.
From a script, capture the cookie when you obtain the token and replay it:
curl -c cookies.txt -X POST "http://<backend>/api/auth/token/obtain/" \
-H 'Content-Type: application/json' \
-d '{"username":"myuser","password":"mypassword"}'
curl -b cookies.txt "http://<backend>/media/photos/<image_hash>" -o photo.jpg
or send it explicitly with -H "Cookie: jwt=<access_token>". The cookie carries the short-lived access token, so refresh it the same way you refresh the header token.
Cookie flags​
The backend sets these cookies:
| Cookie | Set by | Flags |
|---|---|---|
jwt | /api/auth/token/obtain/, /api/auth/token/refresh/, the SSO login, the answer to a change of your own password | HttpOnly, SameSite=Lax, Path=/, Secure (see below) |
access, refresh | the SSO login and the answer to a change of your own password (renew_session); the web app sets them itself after a password login and a refresh | SameSite=Lax, Path=/, Secure (see below); not HttpOnly, because the web app reads them to send them as bearer tokens |
The cookies are session cookies, which the browser drops when it closes, except after a sign-in with remember_me: then they get a Max-Age that ends with the refresh token. HttpOnly keeps the jwt cookie away from scripts on the page; only the server reads it. SameSite=Lax still sends the cookies on top-level navigations and on <img> and <video> requests from the same site, which is all the media endpoints need, and keeps them off requests other sites trigger. Ports do not count, so a web app on localhost:3000 and a backend on localhost:8001 are the same site.
The cookies are Secure (sent over HTTPS only) when the request reached the backend over HTTPS, or when AUTH_COOKIE_SECURE is on. Behind the bundled proxy the backend always sees plain HTTP, also when your own proxy in front of it terminates TLS: it does not trust a forwarded scheme (Django's SECURE_PROXY_SSL_HEADER is not set). If your users reach LibrePhotos only over HTTPS, set AUTH_COOKIE_SECURE=1; see Secure auth cookies. Leave it off when the install is also reached over plain HTTP, such as on the LAN: browsers refuse a Secure cookie there, and media would stop loading.
New in 1.4.0 Up to 1.3.0, the cookies had no HttpOnly, SameSite or Secure flag.
Call APIs using Basic auth (optional)​
curl -u myuser:mypassword "http://<backend>/api/photos/"
Basic auth works on the standard DRF endpoints and on the media endpoints, but not on the chunked uploads.
Every Basic auth request is a password check, so wrong passwords count against the same limit as sign-in (AUTH_THROTTLE_RATE, per address and username; see Sign-in rate limits). Once it is used up, requests with that username from that address answer 429 Too Many Requests with a Retry-After header, even with the right password, until the window moves on. Requests with the right password are not counted, so a script can send its credentials on every request.
New in 1.4.0 Up to 1.3.0, wrong Basic auth passwords were not rate limited.
Helpful endpoints​
These routes are only registered when the backend runs with DEBUG=1 (development builds). The standard docker-compose deployment runs with DEBUG=0, where they all return 404:
- API help:
http://<backend>/api/help— structured JSON with authentication instructions and examplecurlcommands. - Schema:
http://<backend>/api/schema - Swagger UI:
http://<backend>/api/swagger - Redoc:
http://<backend>/api/redoc
For the same reason, the extra auth hint that development builds append to a 401/403 error body is not present on a production install, so a production 401 will not point you at /api/help.
Without a development build, read the OpenAPI schema from the repository: apps/backend/openapi.json is generated from the code and kept current by CI (on the dev branch; every release since 1.4.0 has it too). Load it into any OpenAPI viewer, such as the Swagger Editor.
Error responses​
Every API error (a status of 400 or above) has the same JSON body:
{
"errors": [{ "field": "new_password", "message": "This password is too short.", "code": "weak_password" }]
}
fieldnames the request field at fault, or isnon_field_errorsordetailwhen the error is about the request as a whole.messageis meant for people and may change between releases. Do not compare it in code.codeis meant for programs. Most errors carry DRF's generic codes (invalid,not_found,permission_denied,not_authenticated,parse_error,throttled); the ones a client is expected to act on have their own:
| Code | Status | Endpoint | Meaning |
|---|---|---|---|
invalid_cursor | 400 | /api/sync/* | The cursor cannot be decoded. |
cursor_expired | 410 | /api/sync/* | Not released yet (comes after 1.7.0) The cursor was issued more than 90 days ago, older than the deletion log (up to 1.7.0: its last row was modified then); pull again without one. |
weak_password | 400 | /api/auth/password/reset/confirm/ | The password validators refused the new password; the link is still good. |
invalid_reset_link | 400 | /api/auth/password/reset/confirm/ | The link was used already, expired or was mangled. |
not_this_computer | 403 | POST /api/own-computer/* | Not released yet (comes after 1.7.0) The request did not come directly from the computer that runs LibrePhotos. |
key_refused | 403 | POST /api/own-computer/enter/ | Not released yet (comes after 1.7.0) The key of the window was used, is too old, or a password is needed by now. |
password_first | 409 | POST /api/own-computer/devices/, endpoints that create a user | Not released yet (comes after 1.7.0) The first account has no password yet. It needs one before anybody else gets in. |
model_downloading | 503 | /api/photosedit/generateim2txt/ | The captioning model is being downloaded; retry after the Retry-After seconds. |
email_send_failed | 502 | /api/email-config/test/ | The mail server refused the test email; message is its own answer. |
job_start_failed | 500 | job endpoints (/api/scanphotos/, /api/trainfaces/, ...) | The background job could not be queued. |
job_already_running | 409 | job endpoints (/api/scanphotos/, /api/trainfaces/, ...) | A job of this kind is already queued or running for you, or, for a job over the whole server, for anyone; or a scan of yours is refused while a move or rename of your photos runs, and the other way round. The entry also carries that job's job_id; follow it instead of starting another. |
selection_changed | 409 | DELETE /api/photosedit/delete/ | Not released yet (comes after 1.7.0) With select_all and expected_count, the query (only photos trashed at or before trashed_before, the snapshot_at of the trash listing from GET /api/days/?in_trashcan=true) matches another number of photos than expected_count; nothing was deleted. The entry carries the current count and snapshot_at as strings; send them as expected_count and trashed_before to delete those. |
queue_busy | 409 | job endpoints | A job over the whole server that someone else started, and you cannot open, is running. The entry carries no job_id: start yours again when it has finished. |
Development builds append an extra entry with field auth (code authentication_help) to a 401 or 403; read the first entry. Media file requests (/media/...) are the exception: they answer without a body, as described above.
New in 1.4.0 Up to 1.3.0, a second start of a job that was still queued queued it again instead of answering job_already_running, and duplicate and stack detection (/api/duplicates/detect, /api/stacks/detect/) answered without a job_id. Many endpoints answered errors as {"error": "..."} or {"status": false, "message": "..."}, entries had no code, and three failures (face training that could not be queued, the captioning model download and a refused test email) answered with a 200.
Troubleshooting 401/403​
- Ensure you are including
Authorization: Bearer <access_token>or using Basic auth. - Verify the access token is current; refresh if needed.
- A 403 from
/media/...carrying anX-Media-Error: authenticationheader means the request had no usable credential: send a current bearer token orjwtcookie (see Endpoints that also accept thejwtcookie). A 404 there means you are signed in but may not see that photo. Not released yet (comes after 1.7.0) A 404 withX-Media-Error: drive_not_connectedmeans the drive with the file is not connected: try again when it is. WithX-Media-Error: another_driveanother drive is there in its place. - If testing cross-origin from a separate frontend, ensure CORS and credentials are configured properly and that cookies are allowed if relying on the
jwtcookie.