# Authentication

Learn how to authenticate the Mojo SDK with SurrealDB using access tokens and the signin RPC.

The Mojo SDK authenticates in one of two ways: with an access token supplied on the connection, or with the `signin` RPC over a stateful WebSocket session.

## Access tokens

The `access_token` field on `ConnectOptions` is placed in the `Authorization` header. If the value already starts with `Bearer `, `Basic `, or `Digest `, it is passed through verbatim. Otherwise the SDK treats it as a raw JWT and prepends `Bearer `.

```python
# Basic auth (root user, dev fixtures)
ConnectOptions(access_token=Optional(String("Basic cm9vdDpyb290")))

# JWT from a previous signin
ConnectOptions(access_token=Optional(String("Bearer eyJhbGciOi...")))

# Raw JWT (the SDK prepends "Bearer ")
ConnectOptions(access_token=Optional(String("eyJhbGciOi...")))
```

This is the recommended approach for the HTTP and HTTPS transports.

## Signing in with credentials

Over a WebSocket session, you can authenticate with the `signin` RPC. Credentials are encoded as a CBOR map with `CborCodec`. On success, `signin()` stores the returned token on the client for subsequent requests.

```python
from surrealdb import AsyncSurrealClient, CborCodec, ConnectOptions
from std.collections import Optional, List


def main():
    var client = AsyncSurrealClient()
    _ = client.connect(
        "ws://localhost:8000/rpc",
        ConnectOptions(
            namespace=Optional(String("test")),
            database=Optional(String("test")),
        ),
    )

    # Encode the credentials map {"user": "root", "pass": "secret"}.
    var codec = CborCodec()
    var pairs = List[Tuple[String, List[UInt8]]]()
    pairs.append(Tuple(String("user"), codec.encode_text("root")))
    pairs.append(Tuple(String("pass"), codec.encode_text("root")))
    _ = client.signin(codec.encode_map(pairs))
    client.use("test", "test")
```

> [!NOTE]
> `signin`, `signup`, `authenticate`, and `invalidate` operate on a stateful session, which is provided by the WebSocket transport. WebSocket support is rolling out.

## Other auth methods

- `signup(credentials_cbor)` creates a new record-access account and signs in.
- `authenticate(token)` authenticates the current connection with a token, and stores it on the client.
- `invalidate()` clears the current token and invalidates the session.

```python
client.authenticate("eyJhbGciOi...")
client.invalidate()
```

See the method reference for [`signin`](/docs/reference/mojo/methods/signin.md), [`signup`](/docs/reference/mojo/methods/signup.md), [`authenticate`](/docs/reference/mojo/methods/authenticate.md), and [`invalidate`](/docs/reference/mojo/methods/invalidate.md).
