Authentication
The Java SDK supports signing in as a root, namespace, database, or record-level user. After signing in, the connection is authenticated for all subsequent operations until the session is invalidated or the connection is closed.
You can configure authentication in your SurrealDB database using the DEFINE USER or DEFINE ACCESS statements.
API References
Signing in as a system user
System users are defined with the DEFINE USER statement and have access at the root, namespace, or database level. Use the corresponding credential class to sign in.
import com.surrealdb.signin.RootCredential;
import com.surrealdb.signin.NamespaceCredential;
import com.surrealdb.signin.DatabaseCredential;
try (Surreal db = new Surreal()) {
db.connect("ws://localhost:8000");
db.useNs("surrealdb").useDb("docs");
db.signin(new RootCredential("root", "root"));
db.signin(new NamespaceCredential("tobie", "123456", "surrealdb"));
db.signin(new DatabaseCredential("tobie", "123456", "surrealdb", "docs"));
}
Signing in as a record user
Record users authenticate against a DEFINE ACCESS method defined on a database. Use RecordCredential with the access method name and any parameters required by the access definition.
import com.surrealdb.signin.RecordCredential;
Map<String, Object> params = Map.of(
"email", "info@surrealdb.com",
"password", "123456"
);
Token token = db.signin(new RecordCredential(
"surrealdb", "docs", "account", params
));
Signing up a record user
The .signup() method registers a new record user through a record access method and returns a Token. Signup is only available for record-level access.
import com.surrealdb.signin.RecordCredential;
Map<String, Object> params = Map.of(
"email", "newuser@surrealdb.com",
"password", "s3cureP@ss"
);
Token token = db.signup(new RecordCredential(
"surrealdb", "docs", "account", params
));
Using authentication tokens
The .signin() and .signup() methods return a Token object. Use .getAccess() to retrieve the JWT access token and .getRefresh() to retrieve the optional refresh token. You can store these tokens and use them later to re-authenticate without credentials.
Token token = db.signin(new RootCredential("root", "root"));
String accessToken = token.getAccess();
String refreshToken = token.getRefresh();
db.authenticate(accessToken);
Authenticating with a bearer token
If you have a bearer key — for example, one defined with a bearer access method — use BearerCredential to authenticate.
import com.surrealdb.signin.BearerCredential;
db.signin(new BearerCredential("eyJhbGciOiJIUzI1NiIs..."));
Invalidating authentication
The .invalidate() method clears the authentication state for the current connection. After invalidation, subsequent operations execute as an unauthenticated user.
db.invalidate();
Learn more