Session Management - shahmal1yev/blueskysdk GitHub Wiki

Efficient session management is a key feature of the SDK, enabling you to authenticate and reuse sessions seamlessly.

Saving a Session

After authenticating a client, you can export the session to persist it for later use:

$saveToDatabase(json_encode($client->authenticated()));

Restoring a Session

To reuse a saved session, deserialize it and provide it to the client during authentication:

use Atproto\Responses\Com\Atproto\Server\CreateSessionResponse;

$savedSession = new CreateSessionResponse(json_decode($savedSessionJSON, true));

$client = new Client();
$client->authenticate(
    getenv('BLUESKY_IDENTIFIER'),
    getenv('BLUESKY_PASSWORD'),
    $savedSession
);

Session Validation Workflow

When a session is used, the SDK validates it automatically following this workflow:

  1. accessJwt: Checks the validity of the accessJwt token.

    • If valid, the session is used.
    • If invalid, it proceeds to the next step.
  2. refreshJwt: Validates the refreshJwt token.

    • If valid, a new session is generated.
    • If invalid, it proceeds to the next step.
  3. Credentials: If tokens are invalid, the SDK uses the provided credentials to create a new session.

    • If successful, the new session is used.
    • If unsuccessful, an exception is thrown.

Example Workflow

use Atproto\Client;
use Atproto\Responses\Com\Atproto\Server\CreateSessionResponse;

// Fetch session from storage
$savedSessionJSON = $fetchFromDatabase();
$savedSession = new CreateSessionResponse(json_decode($savedSessionJSON, true));

$client = new Client();
$client->authenticate(
    getenv('BLUESKY_IDENTIFIER'),
    getenv('BLUESKY_PASSWORD'),
    $savedSession
);

// Automatically handles token validation and session refresh
$profile = bskyFacade($client)->getProfile()
    ->actor($client->authenticated()->handle())
    ->send();

echo $profile->displayName();

[!IMPORTANT] If no session is provided, the SDK will always use credentials to create a new session.

Additional Resources