The basics
Serverpod automatically checks if the user is logged in and if the user has the right privileges to access the endpoint. When using the serverpod_auth
module you will not have to worry about keeping track of tokens, refreshing them or, even including them in requests as this all happens automatically under the hood.
The Session
object provides information about the current user. A unique userId
identifies a user. You should use this id whenever you a referring to a user. Access the id of a signed-in user through the auth
field of the Session
object.
Future<void> myMethod(Session session) async {
var userId = await session.auth.authenticatedUserId;
...
}
The Session
object provides information about the current user. A unique userId
identifies a user. You should use this id whenever you a referring to a user. Access the id of a signed-in user through the authenticated
field of the Session
object.
Future<void> myMethod(Session session) async {
var userId = (await session.authenticated)?.userId;
...
}
You can also use the Session object to check if a user is authenticated:
Future<void> myMethod(Session session) async {
var isSignedIn = await session.isUserSignedIn;
...
}
Requiring authentication on endpoints
@@ -28,6 +28,18 @@Custom scopes<
class CustomScope extends Scope {
const CustomScope(String name) : super(name);
static const userRead = CustomScope('userRead');
static const userWrite = CustomScope('userWrite');
}
class CustomScope extends Scope {
const CustomScope(String name) : super(name);
static const userRead = CustomScope('userRead');
static const userWrite = CustomScope('userWrite');
}
Then use the custom scopes like this:
class MyEndpoint extends Endpoint {
bool get requireLogin => true;
Set<Scope> get requiredScopes => {CustomScope.userRead, CustomScope.userWrite};
Future<void> myMethod(Session session) async {
...
}
...
}
Keep in mind that a scope is merely an arbitrary string and can be written in any format you prefer. However, it's crucial to use unique strings for each scope, as duplicated scope strings may lead to unintentional data exposure.