|
| 1 | +# Custom overrides |
| 2 | + |
| 3 | +Serverpod is designed to make it as simple as possible to implement custom authentication overrides. The framework comes with an integrated auth token creation, validation, and communication system. With a simple setup, it is easy to generate custom tokens and include them in authenticated communication with the server. |
| 4 | + |
| 5 | +## Server setup |
| 6 | + |
| 7 | +After successfully authenticating a user, for example, through a username and password, an auth token can be created to preserve the authenticated user's permissions. This token is used to identify the user and facilitate endpoint authorization validation. When the user signs out, the token can be removed to prevent further access. |
| 8 | + |
| 9 | +### Create auth token |
| 10 | + |
| 11 | +To create an auth token, call the `signInUser` method in the `UserAuthentication` class, accessible through the `session.auth` field on the `session` object. |
| 12 | + |
| 13 | +The `signInUser` method takes three arguments: the first is a unique `integer` identifier for the user, the second is information about the method used to authenticate the user, and the third is a set of scopes granted to the auth token. |
| 14 | + |
| 15 | +```dart |
| 16 | +var authToken = await session.auth.signInUser(myUserObject.id, 'myAuthMethod', scopes: { |
| 17 | + Scope('delete'), |
| 18 | + Scope('create'), |
| 19 | +}); |
| 20 | +``` |
| 21 | + |
| 22 | +The example above creates an auth token for a user with the unique identifier taken from `myUserObject`. The auth token preserves that it was created using the method `myAuthMethod` and has the scopes `delete` and `create`. |
| 23 | + |
| 24 | + |
| 25 | +:::info |
| 26 | +The unique identifier for the user should uniquely identify the user regardless of authentication method. The information allows authentication tokens associated with the same user to be grouped. |
| 27 | +::: |
| 28 | + |
| 29 | +#### Custom auth tokens |
| 30 | + |
| 31 | +The `UserAuthentication` class simplifies the token management but makes assumptions about what information should be stored in the auth token. If your project has different requirements, managing auth tokens manually with your defined model is possible. Custom auth tokens require that the token validation is overridden and adjusted to the new auth token format, explained in [override token validation](#override-token-validation). |
| 32 | + |
| 33 | +### Token validation format |
| 34 | + |
| 35 | +The framework requires tokens to be of `String` type, and the default token validation expects the token to be in the format `userId:key`. The `userId` is the unique identifier for the user, and the `key` is a generated auth token key. The `userId` and `key` are then retrieved from the token and validated towards the auth token stored as a result of the call to `session.auth.signInUser(...)`. |
| 36 | + |
| 37 | +```dart |
| 38 | +var authToken = await session.auth.signInUser(....); |
| 39 | +var verifiableToken = '${authToken.userId}:${authToken.key}'; |
| 40 | +``` |
| 41 | + |
| 42 | +In the above example, the `verifiableToken` is created by concatenating the `userId` and `key` from the `authToken`. This token is then verifiable by the default token validation. |
| 43 | + |
| 44 | +#### Override token validation |
| 45 | + |
| 46 | +The token validation method can be overridden by providing a custom `authenticationHandler` callback when initializing Serverpod. The callback should return an `AuthenticationInfo` object if the token is valid, otherwise `null`. |
| 47 | + |
| 48 | +```dart |
| 49 | +// Initialize Serverpod and connect it with your generated code. |
| 50 | +final pod = Serverpod( |
| 51 | + args, |
| 52 | + Protocol(), |
| 53 | + Endpoints(), |
| 54 | + authenticationHandler: (Session session, String token) async { |
| 55 | + /// Custom validation handler |
| 56 | + if (token != 'valid') return null; |
| 57 | +
|
| 58 | + return AuthenticationInfo(1, <Scope>{}); |
| 59 | + }, |
| 60 | +); |
| 61 | +``` |
| 62 | + |
| 63 | +In the above example, the `authenticationHandler` callback is overridden with a custom validation method. The method returns an `AuthenticationInfo` object with user id `1` and no scopes if the token is valid, otherwise `null`. |
| 64 | + |
| 65 | +### Send token to client |
| 66 | + |
| 67 | +After creating the token, it should be sent to the client. The client is then responsible for storing the token and including it in communication with the server. The token is usually sent in response to a successful sign-in request. |
| 68 | + |
| 69 | +```dart |
| 70 | +class UserEndpoint extends Endpoint { |
| 71 | + Future<String?> login( |
| 72 | + Session session, |
| 73 | + String username, |
| 74 | + String password, |
| 75 | + ) async { |
| 76 | + var identifier = authenticateUser(session, username, password); |
| 77 | + if (identifier == null) return null; |
| 78 | +
|
| 79 | + var authToken = await session.auth.signInUser( |
| 80 | + identifier, |
| 81 | + 'username', |
| 82 | + scopes: {}, |
| 83 | + ); |
| 84 | +
|
| 85 | + return '${authToken.id}:${authToken.key}'; |
| 86 | + } |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +In the above example, the `login` method authenticates the user and creates an auth token. The token is then returned to the client in the format expected by the default token validation. |
| 91 | + |
| 92 | +### Remove auth token |
| 93 | +When the default token validation is used, signing out a user on all devices is made simple with the `signOutUser` method in the `UserAuthentication` class. The method removes all auth tokens associated with the user. |
| 94 | + |
| 95 | +```dart |
| 96 | +class AuthenticatedEndpoint extends Endpoint { |
| 97 | + @override |
| 98 | + bool get requireLogin => true; |
| 99 | + Future<void> logout(Session session) async { |
| 100 | + await session.auth.signOutUser(); |
| 101 | + } |
| 102 | +} |
| 103 | +``` |
| 104 | + |
| 105 | +In the above example, the `logout` endpoint removes all auth tokens associated with the user. The user is then signed out and loses access to any protected endpoints. |
| 106 | + |
| 107 | +#### Remove specific tokens |
| 108 | +The `AuthKey` table stores all auth tokens and can be interacted with in the same way as any other model with a database in Serverpod. To remove specific tokens, the `AuthKey` table can be interacted with directly. |
| 109 | + |
| 110 | +```dart |
| 111 | +await AuthKey.db.deleteWhere( |
| 112 | + session, |
| 113 | + where: (t) => t.userId.equals(userId) & t.method.equals('username'), |
| 114 | +); |
| 115 | +``` |
| 116 | + |
| 117 | +In the above example, all auth tokens associated with the user `userId` and created with the method `username` are removed from the `AuthKey` table. |
| 118 | + |
| 119 | + |
| 120 | +#### Custom token solution |
| 121 | +If a [custom auth token](#custom-tokens) solution has been implemented, auth token removal must be handled manually. The `signOutUser` method does not provide an interface to interact with other database tables. |
| 122 | + |
| 123 | +## Client setup |
| 124 | +Enabling authentication in the client is as simple as configuring a key manager and placing any token in it. If a key manager is configured, the client will automatically query the manager for a token and include it in communication with the server. |
| 125 | + |
| 126 | +### Configure key manager |
| 127 | +Key managers need to implement the `AuthenticationKeyManager` interface. The key manager is configured when creating the client by passing it as the named parameter `authenticationKeyManager`. If no key manager is configured, the client will not include tokens in requests to the server. |
| 128 | + |
| 129 | +```dart |
| 130 | +class SimpleAuthKeyManager extends AuthenticationKeyManager { |
| 131 | + String? _key; |
| 132 | +
|
| 133 | + @override |
| 134 | + Future<String?> get() async { |
| 135 | + return _key; |
| 136 | + } |
| 137 | +
|
| 138 | + @override |
| 139 | + Future<void> put(String key) async { |
| 140 | + _key = key; |
| 141 | + } |
| 142 | +
|
| 143 | + @override |
| 144 | + Future<void> remove() async { |
| 145 | + _key = null; |
| 146 | + } |
| 147 | +} |
| 148 | +
|
| 149 | +
|
| 150 | +var client = Client('http://$localhost:8080/', |
| 151 | + authenticationKeyManager: SimpleAuthKeyManager()) |
| 152 | + ..connectivityMonitor = FlutterConnectivityMonitor(); |
| 153 | +``` |
| 154 | + |
| 155 | +In the above example, the `SimpleAuthKeyManager` is configured as the client's authentication key manager. The `SimpleAuthKeyManager` stores the token in memory. |
| 156 | + |
| 157 | +:::info |
| 158 | + |
| 159 | +The `SimpleAuthKeyManager` is not practical and should only be used for testing. A secure implementation of the key manager is available in the `serverpod_auth_shared_flutter` package named `FlutterAuthenticationKeyManager`. It provides safe, persistent storage for the auth token. |
| 160 | + |
| 161 | +::: |
| 162 | + |
| 163 | +The key manager is then available through the client's `authenticationKeyManager` field. |
| 164 | + |
| 165 | +```dart |
| 166 | +var keyManager = client.authenticationKeyManager; |
| 167 | +``` |
| 168 | + |
| 169 | +### Store token |
| 170 | +When the client receives a token from the server, it is responsible for storing it in the key manager using the `put` method. The key manager will then include the token in all requests to the server. |
| 171 | + |
| 172 | +```dart |
| 173 | +await client.authenticationKeyManager?.put(token); |
| 174 | +``` |
| 175 | + |
| 176 | +In the above example, the `token` is placed in the key manager. It will now be included in communication with the server. |
| 177 | + |
| 178 | +### Remove token |
| 179 | +To remove the token from the key manager, call the `remove` method. |
| 180 | + |
| 181 | +```dart |
| 182 | +await client.authenticationKeyManager?.remove(); |
| 183 | +``` |
| 184 | + |
| 185 | +The above example removes any token from the key manager. |
| 186 | + |
| 187 | +### Retrieve token |
| 188 | +To retrieve the token from the key manager, call the `get` method. |
| 189 | + |
| 190 | +```dart |
| 191 | +var token = await client.authenticationKeyManager?.get(); |
| 192 | +``` |
| 193 | + |
| 194 | +The above example retrieves the token from the key manager and stores it in the `token` variable. |
0 commit comments