• Start

Languages

/

Kotlin

/

Concepts

Authentication

Sign up, sign in, and manage authentication tokens with the SurrealDB Kotlin SDK.

The Kotlin SDK supports the full range of SurrealDB authentication methods: root, namespace, and database users, as well as record (scoped) access. Credentials are supplied as a JsonObject, built with buildJsonObject.

MethodDescription
client.signup(params)Signs up against a record access method
client.signin(params)Signs in with credentials
client.authenticate(token)Authenticates with an existing token
client.auth()Returns the current authentication record
client.invalidate()Invalidates the current session authentication
client.reset()Resets the session to an unauthenticated state

Use .signin() with the credentials appropriate to the level of access you need. It returns the authentication token as a JsonElement.

import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

// Root user
client.signin(buildJsonObject {
put("user", "root")
put("pass", "root")
})

// Database user
client.signin(buildJsonObject {
put("namespace", "surrealdb")
put("database", "docs")
put("user", "admin")
put("pass", "secret")
})

Use .signup() to register against a record access method.

val token = client.signup(buildJsonObject {
put("namespace", "surrealdb")
put("database", "docs")
put("access", "user")
put("email", "ada@example.com")
put("password", "hunter2")
})

If you already hold a token (for example from a previous session), authenticate the connection with .authenticate().

client.authenticate("eyJ0eXAiOiJKV1Qi...")

Retrieve the currently authenticated record with .auth(), drop the authentication while keeping the connection open with .invalidate(), or fully reset the session state with .reset().

val me = client.auth()
client.invalidate()
client.reset()

The client can authenticate automatically on connect and after reconnects, and renew tokens shortly before they expire. Provide a credentialProvider and enable autoAuthenticate on your SurrealClientConfig. The provider returns a SurrealAuthInput — either a SignIn with credentials or an existing Token.

import com.surrealdb.kotlin.SurrealAuthInput
import com.surrealdb.kotlin.SurrealClientConfig
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val client = SurrealClient(
SurrealClientConfig(
url = "wss://example.com",
autoAuthenticate = true,
tokenRenewalLeadMillis = 60_000, // renew 60s before expiry
credentialProvider = {
SurrealAuthInput.SignIn(buildJsonObject {
put("user", "root")
put("pass", "root")
})
},
),
)

Was this page helpful?