DEFINE ACCESS
statement
Defining an access method allows SurrealDB to grant access to resources using different kinds of credentials.
Requirements
- You must be authenticated as a system user at the same level or higher than the level on which access is defined.
Statement syntax
SurrealQL SyntaxDEFINE ACCESS [ IF NOT EXISTS ] @name
ON [ NAMESPACE | DATABASE ]
TYPE [
JWT [ ALGORITHM @algorithm KEY @key | URL @url ]
| RECORD
[ SIGNUP @expression ]
[ SIGNIN @expression ]
[ AUTHENTICATE @expression ]
[ WITH JWT
[ ALGORITHM @algorithm KEY @key | URL @url ]
[ WITH ISSUER KEY @key ]
]
[ DURATION
[ FOR TOKEN @duration ]
[ FOR SESSION @duration ]
]
[ COMMENT @string ]
JSON Web Token (JWT) Access
A JWT access method allows accessing SurrealDB with a token signed by a trusted issuer. The contents of the token will be trusted by SurrealDB as long as it has been signed with a trusted credential.
Learn more about JWT access method in the documentation.
Record Access
A record access method allows accessing SurrealDB as a record user. Record users allow SurrealDB to operate as a web database by offering mechanisms to define custom signin and signup logic as well as custom table and field permissions.
Learn more about record access method in the documentation.
Duration
The duration clause specifies the duration of the token returned after successful authentication with the access method as well as the duration of the session established both using the access method and the aforementioned token. The difference between these concepts is explained in the expiration documentation.
-- Create a RECORD access method for accounts
-- On successful authentication, a token expiring after 15 minutes will be returned
-- This token can be used to establish a session that will expire after 6 hours
-- The token will be automatically used to authenticate the session
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
;
Using IF NOT EXISTS
clause
The IF NOT EXISTS
clause can be used to define an access method only if it does not already exist. If the access method already exists, the DEFINE ACCESS
statement will return an error.
-- Create an ACCESS if it does not already exist
DEFINE ACCESS IF NOT EXISTS example ON NAMESPACE;