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.
API references
Method | Description |
|---|---|
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 |
Signing in
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")
})Signing up
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")
})Authenticating with a token
If you already hold a token (for example from a previous session), authenticate the connection with .authenticate().
client.authenticate("eyJ0eXAiOiJKV1Qi...")Inspecting and clearing authentication
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()Automatic authentication and token renewal
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")
})
},
),
)Learn more
SurrealClient API reference for complete method signatures
Client configuration for
credentialProviderand renewal optionsMultiple sessions for per-session authentication
SurrealDB authentication for an overview of authentication concepts