# Handle authentication

In this section, we will walk you through the process of authenticating users and securing your SurrealDB database.

Since SurrealDB is a database that is designed to be used in a distributed environment, it is important to secure the database and the data that is stored in it.
SurrealDB provides a number of methods for authenticating users and securing the database.

In your SurrealDB database, you can create authentication login using the [`DEFINE ACCESS`](/docs/reference/query-language/statements/define/access.md) statement which supports [JWT](/docs/reference/query-language/statements/define/access/jwt.md) and [Record](/docs/reference/query-language/statements/define/access/record.md) Access methods.

The access method used will inform the input for `Access` in the `.SignUp()` and `.SignIn()` methods.

> [!IMPORTANT]
> If you are not on Version `v3.2.4` of SurrealDB, you will use the `Scope` property instead of `Access`.

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="#signup"> <code> db.SignUp() </code></a></td>
			<td scope="row" data-label="Description">Connects to a local or remote database endpoint</td>
		</tr>
        <tr>
            <td scope="row" data-label="Method"><a href="#signin"> <code> db.SignIn() </code></a></td>
            <td scope="row" data-label="Description">Signs in to a root, namespace, database or scope user</td>
		</tr>
        <tr>
            <td scope="row" data-label="Method"><a href="#invalidate"> <code> db.Invalidate() </code></a></td>
            <td scope="row" data-label="Description">Invalidates the current session</td>
        </tr>
        <tr>
            <td scope="row" data-label="Method"><a href="#authenticate"> <code> db.Authenticate() </code></a></td>
            <td scope="row" data-label="Description">Authenticates a user with a token</td>
        </tr>
	</tbody>
</table>

## Defining access in your application

The .NET SDK has a [`.Query()` method](/docs/reference/dotnet/core/writing-surrealql.md) which allows you to write secure SurrealQL statements from within your application. Using this method, you can define access for your users and securely manage authentication. See the code example below:

```csharp
await db.Query(
    $"""
    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;
    """
);
```

> [!NOTE]
> Depending on the connection protocol you choose, authentication tokens and sessions lifetime work differently. Refer to the [connection options](/docs/reference/dotnet/core/create-a-new-connection.md#connection-options) documentation for more information.

## User authentication

After you have defined your authentication login, you can use the following methods to authenticate users:

## `.SignUp()` {#signup}

Signs up to a specific authentication scope / access method.

```csharp title="Method Syntax"
await db.SignUp(credentials)
```

### Arguments

<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Arguments</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>credentials</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Credentials to sign up as a scoped user.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>cancellationToken</code>
                <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The cancellationToken enables graceful cancellation of asynchronous operations.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```csharp
// With Record Access
var authParams = new AuthParams
{
    Namespace = "main",
    Database = "main",
    Access = "user",
	// Also pass any properties required by the access definition
    Email = "info@surrealdb.com",
    Password = "123456"
};

Jwt jwt = await db.SignUp(authParams);

public class AuthParams : ScopeAuth
{
	public string? Username { get; set; }
	public string? Email { get; set; }
	public string? Password { get; set; }
}
```

<br />

## `.SignIn()` {#signin}

Signs in to a root, namespace, database or scope user.

```csharp title="Method Syntax"
await db.SignIn(credentials)
```

### Arguments

<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Arguments</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="col" scope="row" data-label="Arguments">
                <code>credentials</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="col" scope="row" data-label="Description">
                Variables used in a signin query.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="col" scope="row" data-label="Arguments">
                <code>cancellationToken</code>
                <label label="optional" />
            </td>
            <td colspan="2" scope="col" scope="row" data-label="Description">
                The cancellationToken enables graceful cancellation of asynchronous operations.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

**Root user**

```csharp
// Sign in as root user
await db.SignIn(new RootAuth { Username = "root",
    Password = "secret" });
```

**Namespace user**

```csharp
// Sign in using namespace auth
await db.SignIn(
    new NamespaceAuth
    {
        Namespace = "main", 
        Username = "johndoe", 
        Password = "password123" 
    }
);
```

**Database user**

```csharp
// Sign in using database auth
await db.SignIn(
    new DatabaseAuth
    {
        Namespace = "main", 
        Database = "main", 
        Username = "johndoe", 
        Password = "password123" 
    }
);
```

**Record Access**

```csharp
// Sign in with Record Access
var authParams = new AuthParams
{
    Namespace = "main",
    Database = "main",
    Access = "user",
    Email = "info@surrealdb.com",
    Password = "123456"
};

Jwt jwt = await db.SignIn(authParams);

public class AuthParams : ScopeAuth
{
	public string? Username { get; set; }
	public string? Email { get; set; }
	public string? Password { get; set; }
}
```

**Scopes**

```csharp
// Sign in as a scoped user
var authParams = new AuthParams
{
    Namespace = "main",
    Database = "main",
    Scope = "user",
    Email = "info@surrealdb.com",
    Password = "123456"
};

Jwt jwt = await db.SignIn(authParams);

public class AuthParams : ScopeAuth
{
	public string? Username { get; set; }
	public string? Email { get; set; }
	public string? Password { get; set; }
}
```

<br />

## `.Authenticate()` {#authenticate}

Authenticates the current connection with a JWT token.

```csharp title="Method Syntax"
await db.Authenticate(jwt)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Arguments</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="col" scope="row" data-label="Arguments">
                <code>jwt</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="col" scope="row" data-label="Description">
                The JWT object holder of the authentication token.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="col" scope="row" data-label="Arguments">
                <code>cancellationToken</code>
                <label label="optional" />
            </td>
            <td colspan="2" scope="col" scope="row" data-label="Description">
                The cancellationToken enables graceful cancellation of asynchronous operations.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```csharp
var jwt = new Jwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA");
await db.Authenticate(jwt);
```

<br />

## `.Invalidate()` {#invalidate}

Invalidates the authentication for the current connection.

```csharp title="Method Syntax"
await db.Invalidate()
```

### Arguments

<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Properties</th>
            <th colspan="2" scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="col" scope="row" data-label="Properties">
                <code>cancellationToken</code>
                <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The cancellationToken enables graceful cancellation of asynchronous operations.
            </td>
        </tr>
    </tbody>
</table>

### Example usage

```csharp
await db.Invalidate();
```
