Authentication
import { Aside } from ‘@astrojs/starlight/components’;
All auth methods return a PBResponse. Methods that issue HTTP requests require .collection() to be set to the auth collection name (typically "users").
authWithPassword()
Section titled “authWithPassword()”Authenticate with an identity (email or username) and password.
PBResponse authWithPassword(const char* identity, const char* password);| Parameter | Type | Description |
|---|---|---|
identity | const char* | Email address or username of the user. |
password | const char* | Account password. |
On success, the JWT is extracted from the response body and stored internally. All subsequent requests automatically include Authorization: Bearer <token> until clearAuthToken() is called.
PocketBase endpoint: POST /api/collections/{collection}/auth-with-password
PBResponse auth = pb.collection("users").authWithPassword( "user@example.com", "yourpassword");
if (!auth.ok) { Serial.println("Login failed (" + String(auth.statusCode) + "): " + auth.error); return;}
// Token is now stored — all subsequent requests carry it automaticallySerial.println("Token: " + pb.getAuthToken());The response body contains both the token and the full user record:
{ "token": "eyJhbGciOiJIUzI1NiJ9...", "record": { "id": "abc123", "email": "user@example.com", "name": "Alice" }}authRefresh()
Section titled “authRefresh()”Exchange the current token for a new one with a renewed expiry.
PBResponse authRefresh();Requires an existing valid token (set via authWithPassword() or setAuthToken()) and the correct collection to be selected. The new token is stored automatically on success.
PocketBase endpoint: POST /api/collections/{collection}/auth-refresh
PBResponse refreshed = pb.collection("users").authRefresh();
if (refreshed.ok) { Serial.println("Token refreshed");} else { // Token has expired — must log in again Serial.println("Refresh failed: " + refreshed.error);}setAuthToken()
Section titled “setAuthToken()”Manually set the auth token — for example, a token restored from flash storage (Preferences, EEPROM) after a reboot.
void setAuthToken(const String& token);| Parameter | Type | Description |
|---|---|---|
token | String | JWT token string. |
// Save to flash after loginString token = pb.getAuthToken();preferences.putString("pbToken", token);
// Restore on next bootString saved = preferences.getString("pbToken", "");if (saved.length() > 0) { pb.setAuthToken(saved);}getAuthToken()
Section titled “getAuthToken()”Retrieve the currently stored auth token.
String getAuthToken() const;Returns an empty String when not authenticated.
String token = pb.getAuthToken();if (token.isEmpty()) { Serial.println("Not authenticated");}clearAuthToken()
Section titled “clearAuthToken()”Clear the stored token. Subsequent requests will not include an Authorization header.
void clearAuthToken();pb.clearAuthToken();Serial.println("Logged out");