Skip to content

Concepts

Authentication

The Go SDK signs in system users and record users, signs up record users, and manages the tokens that the server returns. The credentials that you pass decide which user the connection signs in as, and so which data it can read and change. This page covers each way to sign in, refresh tokens and their automatic renewal, and how to sign out.

Method

Description

db.SignIn(ctx, authData)

Signs in an existing user and returns a JWT

db.SignUp(ctx, authData)

Signs up a new record user and returns a JWT

db.SignInWithRefresh(ctx, authData)

Signs in and returns an access token and a refresh token

db.SignUpWithRefresh(ctx, authData)

Signs up and returns an access token and a refresh token

db.Refresh(ctx, tokens)

Exchanges a token pair for a new one

db.Revoke(ctx, tokens)

Revokes the refresh token of a token pair

db.Tokens()

Returns the token pair the session holds

db.Authenticate(ctx, token)

Authenticates the connection with a JWT

db.Info(ctx)

Returns the record of the signed-in record user

db.Invalidate(ctx)

Signs the session out

db.Reset(ctx)

Signs the session out and clears its namespace, database and variables

SurrealDB has four levels of user. The fields you set in the authentication data decide which level a sign-in uses:

LevelRequired fieldsAccess to
RootUsername, PasswordAll namespaces and databases
NamespaceNamespace, Username, PasswordAll databases in the namespace
DatabaseNamespace, Database, Username, PasswordA single database
RecordNamespace, Database, Access, and the fields the access method readsRecords that the access method and table permissions allow

Pass the credentials as an Auth struct or as a map[string]any. A map uses the keys NS, DB, AC, user and pass. It can also hold any other field that an access method reads, such as email.

To sign in as a root, namespace or database user, set the fields for that level:

token, err := db.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
})
token, err := db.SignIn(ctx, surrealdb.Auth{
	Namespace: "surrealdb",
	Database:  "docs",
	Username:  "db_user",
	Password:  "hunter123",
})

.SignIn() returns the JWT that the server issued. On a WebSocket connection, the session stays signed in after the token expires, until the session itself expires. Over HTTP, the client sends the token with each request, so requests fail after the token expires.

A record user signs in through an access method that a DEFINE ACCESS ... TYPE RECORD statement defines. The access method decides which fields it reads:

DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP (CREATE user SET email = $email, pass = crypto::argon2::generate($pass))
	SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass))
	DURATION FOR TOKEN 15m, FOR SESSION 12h;

Pass the namespace, database and access method, and the fields that the SIGNIN clause reads, in a map:

token, err := db.SignIn(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})

When the access method reads $user and $pass, the Access, Username and Password fields of an Auth struct also work.

.SignUp() runs the SIGNUP clause of an access method. This clause usually creates the user record. .SignUp() then signs the new user in:

token, err := db.SignUp(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "jaime@example.com",
	"pass":  "hunter123",
})

For an access method defined WITH REFRESH, the server returns a refresh token with each access token. Add WITH REFRESH to the definition:

DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP (CREATE user SET email = $email, pass = crypto::argon2::generate($pass))
	SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass))
	WITH REFRESH
	DURATION FOR TOKEN 15m, FOR SESSION 12h;

Then sign in or sign up with .SignInWithRefresh() or .SignUpWithRefresh(). Both return Tokens, which hold the Access token and the Refresh token:

tokens, err := db.SignInWithRefresh(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
Warning

On an access method defined WITH REFRESH, .SignIn() and .SignUp() sign the session in, but return the error cannot decode map into string. This happens because the server answers with two tokens instead of one. Use the WithRefresh methods for these access methods.

.Refresh() exchanges a pair for a new pair, without the user's credentials. It then authenticates the session with the new access token:

tokens, err = db.Refresh(ctx, *tokens)
if err != nil {
	log.Fatal(err)
}

The server revokes a refresh token after its first use, so keep the pair that .Refresh() returns. A second refresh with the same refresh token fails with There was a problem with authentication.

.Revoke() revokes the refresh token of a pair. After that, a refresh with that pair fails. Use it, for example, when a user signs out, so that a stored copy of the pair cannot be refreshed. .Revoke() leaves the session signed in:

if err := db.Revoke(ctx, *tokens); err != nil {
	log.Fatal(err)
}

.SignInWithRefresh() can also exchange a refresh token for a new pair. Pass the refresh token in the refresh key, in place of the credentials:

tokens, err = db.SignInWithRefresh(ctx, map[string]any{
	"NS":      "surrealdb",
	"DB":      "docs",
	"AC":      "account",
	"refresh": tokens.Refresh,
})

With WithTokenRenewal(true), the client renews a token pair by itself. A session gets a pair from .SignInWithRefresh(), .SignUpWithRefresh() or .Refresh(). After that, the client exchanges the pair for a new pair shortly before the access token expires. The client then does the same for each new pair:

db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "ws://localhost:8000",
	surrealdb.WithTokenRenewal(true),
)
if err != nil {
	log.Fatal(err)
}

_, err = db.SignInWithRefresh(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})

By default, the client renews an access token one minute before it expires. WithTokenExpiryMargin changes the margin. If an access token lives for less than twice the margin, the client renews it halfway through its life.

Each renewal uses up the refresh token of the pair it replaces. A program can store a pair to sign in again on its next run. Such a program must store the pair that .Tokens() returns, because that pair changes at each renewal:

if pair := db.Tokens(); pair != nil {
	saveTokens(pair.Access, pair.Refresh)
}

.Tokens() returns nil when renewal is off or the session holds no pair. Renewal is off by default.

A TYPE BEARER access method signs in with a key that an ACCESS ... GRANT statement issued. Pass the key in the key field, with no username or password:

token, err := db.SignIn(ctx, map[string]any{
	"NS":  "surrealdb",
	"DB":  "docs",
	"AC":  "api",
	"key": bearerKey,
})

A bearer key has the form surreal-bearer-.... The key field is for bearer access methods only. A refresh token goes in the refresh field.

.Authenticate() signs the connection in with a JWT that you already have. The JWT can be a token from an earlier sign-in. It can also be a token that your own identity provider issued for a TYPE JWT access method:

if err := db.Authenticate(ctx, token); err != nil {
	log.Fatal(err)
}

On a WebSocket connection, a session that authenticated with a token ends when the token expires.

.Info() returns the record of the signed-in record user, as SELECT * FROM $auth would:

info, err := db.Info(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(info["email"])

The table permissions apply. If the permissions do not let the user select its own record, the map is empty.

.Invalidate() signs the session out. The namespace, database and variables stay as they are:

if err := db.Invalidate(ctx); err != nil {
	log.Fatal(err)
}

.Reset() returns the session to the state that it had when the connection opened. The session is then signed out and has no namespace, database or variables. .Reset() also kills the live queries of the session. Over HTTP, the client keeps this state itself, so .Reset() clears it without calling the server:

if err := db.Reset(ctx); err != nil {
	log.Fatal(err)
}

Over WebSocket, the server keeps the authentication in the session. A connection to another server must sign in again. When the client reconnects, it authenticates the new connection with the last token it received. If token renewal is on and the access token has expired, the client first exchanges the pair for a new pair. Without renewal, a session that signed in with a username and password can last longer than its token. The reconnect then cannot restore the sign-in. The status event reports the error, and the session needs to sign in again.

Over HTTP, the client keeps the token and sends it in the Authorization header of each request. DB.Import and DB.Export use the token on WebSocket connections too. After the token expires, they fail with 401 Unauthorized, even while queries still work. Sign in again to get a new token.

Was this page helpful?

Last updated