Authentication Flows

To authenticate you will need an access token from the fediverse instance you are connecting to. Minimal-activitypub supports two different ways of generating access tokens:

  1. Username and Password - Direct authentication with username and password
  2. Authorization URL - OAuth-like flow where a user visits a URL to authorize the application

Username and Password

The sample code below shows the steps needed to generate an access token using username and password authentication.

from minimal_activitypub.client_2_server import ActivityPub
from httpx import AsyncClient

async def get_access_token(mastodon_domain, user_name, password):
    async with AsyncClient(http2=True) as client:
        # Create app
        client_id, client_secret = await ActivityPub.create_app(
            instance_url=mastodon_domain,
            client=client,
        )

        # Get access token
        access_token = await ActivityPub.get_auth_token(
            instance_url=mastodon_domain,
            username=user_name,
            password=password,
            client=client,
        )

        return access_token

Authorization URL

The sample code below shows the steps needed to generate an access token using the authorization URL flow, where a user visits a URL and inputs the authorization code provided on that URL.

from minimal_activitypub.client_2_server import ActivityPub
from httpx import AsyncClient
from minimal_activitypub import USER_AGENT

async def get_access_token(mastodon_domain):
    async with AsyncClient(http2=True) as client:
        # Create app
        client_id, client_secret = await ActivityPub.create_app(
            instance_url=mastodon_domain,
            client=client,
        )

        # Get Authorization Code / URL
        authorization_request_url = (
            await ActivityPub.generate_authorization_url(
                instance_url=mastodon_domain,
                client_id=client_id,
                user_agent=USER_AGENT,
            )
        )
        print(
            f"Please go to the following URL and follow the instructions:\n"
            f"{authorization_request_url}"
        )
        authorization_code = input("[...] Please enter the authorization code:")

        # Validate authorization code and get access token
        access_token = await ActivityPub.validate_authorization_code(
            client=client,
            instance_url=mastodon_domain,
            authorization_code=authorization_code,
            client_id=client_id,
            client_secret=client_secret,
        )

        # Verify access token works
        mastodon = ActivityPub(
            instance=mastodon_domain,
            access_token=access_token,
            client=client,
        )
        await mastodon.determine_instance_type()
        user_info = await mastodon.verify_credentials()

        return access_token

Method Signatures

ActivityPub.create_app(instance_url: str, client: AsyncClient) -> tuple[str, str]

Creates an OAuth application on the specified instance and returns (client_id, client_secret).

ActivityPub.get_auth_token(instance_url: str, username: str, password: str, client: AsyncClient) -> str

Gets an access token using username and password authentication.

ActivityPub.generate_authorization_url(instance_url: str, client_id: str, user_agent: str) -> str

Generates an authorization URL that users need to visit to authorize the application.

ActivityPub.validate_authorization_code(client: AsyncClient, instance_url: str, authorization_code: str, client_id: str, client_secret: str) -> str

Validates an authorization code and returns an access token.

ActivityPub.determine_instance_type() -> None

Determines the type of instance (Mastodon, Pleroma, or Takahe) and sets instance-specific parameters.

ActivityPub.verify_credentials() -> dict

Verifies that the access token is valid and returns the authenticated user's information.

Usage Example

Here's a complete example of how to authenticate and use the library:

import asyncio
from httpx import AsyncClient
from minimal_activitypub.client_2_server import ActivityPub

async def main():
    instance_url = "https://mastodon.social"
    username = "your_username"
    password = "your_password"

    async with AsyncClient() as client:
        # Get access token
        access_token = await get_access_token(instance_url, username, password)

        # Create ActivityPub instance
        ap = ActivityPub(
            instance=instance_url,
            client=client,
            access_token=access_token
        )

        # Verify credentials
        user_info = await ap.verify_credentials()
        print(f"Authenticated as: {user_info.get('username')}")

if __name__ == "__main__":
    asyncio.run(main())

Notes

  • The authorization URL method is more secure as it doesn't require handling user passwords directly.
  • Always store access tokens securely and never commit them to version control.
  • Access tokens may expire and need to be refreshed (refresh token support may vary by instance).