Add Auth Endpoints

Learn how to create the necessary auth endpoints needed to integrate your application with Wristband.

To implement login and logout flows with Wristband, you'll need to use the Wristband SDK to create the following four endpoints in your FastAPI application:

  • Login Endpoint
  • Callback Endpoint
  • Logout Endpoint
  • Session Endpoint

Login Endpoint

The Login Endpoint initiates login requests to Wristband. It constructs the authorization request and redirects the user to Wristband's Authorize Endpoint. From there, the user is directed to Wristband's hosted login page to complete the login process.

Below is a code snippet showing how to use Wristband's SDK to implement the Login Endpoint.

# src/routes/auth_routes.py
from fastapi import APIRouter, Request, Response
from wristband.fastapi_auth import (
    CallbackData,
    CallbackResult,
    CallbackResultType,
    get_session,
    LogoutConfig,
    Session,
    SessionResponse
)
from auth.wristband import wristband_auth

router = APIRouter()

# Login Endpoint
@router.get('/login')
async def login(request: Request) -> Response:
    # Call the Wristband login() method which will generate the Response that 
    # should be used to redirect to Wristband's Authorize Endpoint.
    return await wristband_auth.login(request)

...

Callback Endpoint

After the user successfully authenticates, Wristband redirects to your application's Callback Endpoint. Calling wristband_auth.callback() returns a CallbackResult object containing the user's tokens and claims.

Use the get_session dependency to access the request's session object. Then, create the user's session by calling session.from_callback().

Below is a code snippet showing how to use Wristband's SDK to implement the Callback Endpoint.

# src/routes/auth_routes.py (continued)

# ...

# Callback Endpoint - The get_session dependency provides access to the 
# session object without performing validations on the session.
@router.get('/callback')
async def callback(request: Request, session: Session = Depends(get_session)) -> Response:
    # Call the Wristband callback() method to check if the user
    # successfully authenticated.  If the user did authenticate successfully, 
    # the user's tokens and claims can be retrieved from the CallbackResult.
    callback_result: CallbackResult = await wristband_auth.callback(request)

    # For some edge cases, such as if an invalid grant was passed to the token
    # API, the SDK will return a redirect URL. Your code should redirect to it
    # in order to restart the login flow.
    if callback_result.type == CallbackResultType.REDIRECT_REQUIRED:
        return await wristband_auth.create_callback_response(
            request,
            callback_result.redirect_url,
        )
    
    # Create a session for the authenticated user. If needed, custom fields can 
    # be stored in the session using the custom_fields parameter of the 
    # from_callback() method.
    session.from_callback(callback_result.callback_data)

    # Once the Callback Endpoint has completed, redirect to your app's
    # default return URL (typically your app's home page) or to an explicit
    # return URL, if one was specified in the original login request.
    redirect_url = callback_result.callback_data.return_url or "<replace-with-default-return-url>"
    return await wristband_auth.create_callback_response(request, redirect_url)

...

Logout Endpoint

When a user logs out of your application, you must ensure that all authenticated state associated with the user is cleared. The Logout Endpoint needs to perform three tasks to accomplish this:

  1. Clear the application's local session state.
  2. Revoke any refresh tokens associated with the user.
  3. Redirect to Wristband's Logout Endpoint to terminate the user's Wristband auth session.

Below is a code snippet showing how to use Wristband's SDK to implement the Logout Endpoint.

# src/routes/auth_routes.py (continued)

...

# Logout Endpoint
@router.get('/logout')
async def logout(request: Request, session: Session = Depends(get_session)) -> Response:
    # Get all the necessary session data needed to perform the logout operation.
    logout_config = LogoutConfig(
        refresh_token=session.refresh_token,
        tenant_custom_domain=session.tenant_custom_domain,
        tenant_name=session.tenant_name,
    )

    # Clear your application's local session.
    session.clear()

    # Call the Wristband logout() method. This will revoke any refresh tokens
    # associated with the user and return a Response to redirect to Wristband's 
    # Logout Endpoint.  Redirecting to Wristband's Logout Endpoint will terminate 
    # Wristband's auth session associated to the user.  When Wristband is done
    # logging out the user it will redirect back to your application's login 
    # URL or to an explicitly provided redirect URL.
    return await wristband_auth.logout(request, logout_config)

...

Session Endpoint

The Session Endpoint verifies that an incoming request contains a valid session and, if so, returns a response that includes the user's session data. This endpoint is used primarily by the frontend for the following two purposes:

  1. To allow the frontend to determine whether the user has a valid session.
  2. To provide the frontend with the user's session data for use within the browser.

Below is a code snippet showing how to use Wristband's SDK to implement the Session Endpoint.

# src/routes/auth_routes.py (continued)

...

# Session Endpoint - The require_session_auth dependency verifies that the 
# request has a valid session and also provides access to the session object.
@router.get("/session")
async def get_session_response(session: Session = Depends(require_session_auth)) -> SessionResponse:
    # Call the Wristband get_session_response() method to extract the user's 
    # session data and populate a SessionResponse. If needed, you can add 
    # additional data to the SessionResponse by using the metadata parameter 
    # of the get_session_response() method.
    return session.get_session_response()

Map Auth Endpoints

After implementing the auth endpoints, make sure to include them in your FastAPI application main.py file.

# src/main.py
from fastapi import FastAPI
from wristband.fastapi_auth import SessionMiddleware
from routes.auth_routes import router as auth_router

def create_app() -> FastAPI:
    app = FastAPI()

    app.add_middleware(SessionMiddleware, secret_key="<your-generated-secret>")

    # NEW: Include auth routes - path prefix can be whatever you prefer.
    app.include_router(auth_router, prefix="/auth")

    # Your other application setup...

Register Your Login Endpoint and Callback Endpoint With Wristband

For several authentication flows, Wristband will need to redirect to your application's Login Endpoint and Callback Endpoint. Therefore, we need to inform Wristband of the URLs for these two endpoints. To do that, we'll need to update the following two fields within the Wristband dashboard:

  • Application Login URL
  • Client Redirect URIs

In the sections below, we'll go over how to update these two fields.

Updating the Application Login URL

To update the Application Login URL, follow these steps.

  1. From the Dashboard Home Page, select the appropriate application.
Select application
  1. Next, on the Application Settings page, locate the Login URL field and set its value to the URL of your application's Login Endpoint. When you are finished, click the "Save" button.
Application login URL

Updating the Client Redirect URIs

To update the Client Redirect URIs, follow these steps.

  1. Select "OAuth2 Clients" from the left navigation bar, then select the client whose ID matches the client ID that was registered with the SDK.
Select application
  1. On the Edit Client page, navigate to the Redirect URIs section and click the "Add+" button. Then enter the URL of your application's Callback Endpoint. When you are finished, click the "Save" button.
Register redirect URI

What’s Next

With your application's authentication endpoints in place, let's verify that they're working correctly