Role-based Authorization
In most applications, different users have different levels of access. Let’s define an admin
role for our todo app and enforce the following authorization rules:
- All signed-in users can see the list of tasks.
- All signed-in users can mark specific tasks as
completed
. - Only users with the
admin
role can create or delete tasks.
Step 1: Modify the Task Entity Class
- Modify the highlighted lines in the
Task
entity class to reflect the top three authorization rules.
Code Explanation
allowApiCrud: remult.authenticated
: Ensures that only authenticated users can perform basic CRUD operations.allowApiInsert: 'admin'
: Restricts the creation of tasks to users with theadmin
role.allowApiDelete: 'admin'
: Restricts the deletion of tasks to users with theadmin
role.
Step 2: Assign Roles in the AuthController
- Let’s make “Jane” an admin and use it to determine her roles in the
signIn
method.
Code Explanation
- We added an
admin
property to theJane
user object in thevalidUsers
array. - In the
signIn
method, we assign theadmin
role toremult.user.roles
if the user is an admin. If the user is not an admin,roles
is set to an empty array. - The user’s role is stored in the session, allowing Remult to enforce authorization rules based on the user’s role in subsequent requests.
Try It Out
Sign in to the app as “Alex” to test that actions restricted to admin
users, such as creating or deleting tasks, are not allowed.
Then, sign in as “Jane” to confirm that these actions are permitted for admin users.
Files
Preparing Environment
- Installing dependencies
- Starting http server