• Start

Concepts

Authentication

Learn how to sign in, sign up, authenticate and resume sessions with the SurrealDB Swift SDK.

SurrealDB supports a number of methods for authenticating users and securing the database. The Swift SDK exposes these through signin, signup, authenticate and invalidate.

The signin method accepts a credentials enum describing the level you wish to authenticate at.

let tokens = try await client.signin(.root(username: "root", password: "root"))
let tokens = try await client.signin(.namespace(
    namespace: "myapp",
    username: "ns_user",
    password: "secret"
))
let tokens = try await client.signin(.database(
    namespace: "myapp",
    database: "mydb",
    username: "db_user",
    password: "secret"
))
let tokens = try await client.signin(.accessVariables(
    namespace: "myapp",
    database: "mydb",
    access: "account",
    variables: ["email": .string("user@example.com"), "pass": .string("secret")]
))
let tokens = try await client.signin(.accessBearer(
    namespace: "myapp",
    database: "mydb",
    access: "account",
    key: "bearer-token-value"
))

New record-access users sign up with signup:

let tokens = try await client.signup(.accessRecord(
    namespace: "myapp",
    database: "mydb",
    access: "account",
    variables: ["email": .string("new@example.com"), "pass": .string("secret")]
))

You can re-authenticate an existing client with a previously issued access token:

try await client.authenticate(tokens.access)

Alternatively, provide a token when constructing the client through a SessionContext:

let client = try SurrealHTTPClient(
    endpoint: "http://localhost:8000",
    session: SessionContext(
        namespace: "myapp",
        database: "mydb",
        accessToken: "existing-jwt"
    )
)

To clear the current authentication state:

try await client.invalidate()

Was this page helpful?