Endpoint Bearer token

Hi all,

Is this a “correct” way of using bearer token with anvil api endpoint (code below works)? As i understand, Bearer token is prefered over Basic authentication.

Any input is appreciated :slight_smile:

import anvil.server

@anvil.server.http_endpoint("/monitor")
def monitor():
    # Get all headers to log them, helpful for debugging
    all_headers = anvil.server.request.headers
    print("All Headers:", all_headers)  # This will show all headers received by the server

    # Retrieve the Authorization header from the incoming request
    auth_header = all_headers.get('authorization')

    if auth_header:
        print("Authorization Header:", auth_header)  # Debug output to see what the server receives

        if auth_header.startswith("Bearer "):
            token = auth_header[7:]  # Extract the token
            print("Extracted Token:", token)  # Log the extracted token

            if token == "A-GENEREATED-JSON-WEB-TOKEN":
                return anvil.server.HttpResponse(200, "Correct code")
            else:
                return anvil.server.HttpResponse(401, "Unauthorized: Invalid token")
        else:
            return anvil.server.HttpResponse(401, "Unauthorized: Bearer not found")
    else:
        return anvil.server.HttpResponse(401, "Unauthorized: No token provided")

Endpoint is called with

curl -i https://<myapp>.anvil.app/_/api/monitor -H "Authorization: Bearer A-GENEREATED-JSON-WEB-TOKEN"
1 Like

That is 100% the correct way to use a bearer token.

There are additional steps often done to provide more security. Usually pertaining to how the user gets that token, and how that token is validated.

Here is Client Credential method.

But there are plenty of different ways to slice the apple :slight_smile:

1 Like