0
0
Expressframework~30 mins

Why authorization differs from authentication in Express - See It in Action

Choose your learning style9 modes available
Why Authorization Differs from Authentication in Express
📖 Scenario: You are building a simple Express server that handles user login and access control. You want to understand the difference between authentication (checking who the user is) and authorization (checking what the user can do).
🎯 Goal: Create a basic Express app that authenticates a user by checking a username and password, then authorizes access to a protected route based on the user's role.
📋 What You'll Learn
Create an object called users with usernames as keys and objects containing password and role as values
Create a variable called loggedInUser initialized to null
Write a function called authenticate that takes username and password and sets loggedInUser if credentials match
Write a function called authorize that takes a role and returns true if loggedInUser has that role
Add an Express route /dashboard that uses authorize to allow access only if the user is an admin
💡 Why This Matters
🌍 Real World
Web apps need to know who users are (authentication) and what they can do (authorization) to protect sensitive data and actions.
💼 Career
Understanding authentication and authorization is essential for backend developers building secure web services with Express.
Progress0 / 4 steps
1
Set up user data
Create an object called users with these exact entries: 'alice' with password 'wonderland' and role 'admin', and 'bob' with password 'builder' and role 'user'.
Express
Need a hint?

Use an object with usernames as keys and objects with password and role as values.

2
Add login state variable
Create a variable called loggedInUser and set it to null to represent no user logged in yet.
Express
Need a hint?

Use let to allow changing the logged in user later.

3
Write authentication function
Write a function called authenticate that takes username and password. If the username exists in users and the password matches, set loggedInUser to the user object; otherwise, set it to null.
Express
Need a hint?

Check if the username exists and password matches, then update loggedInUser.

4
Add authorization and protected route
Write a function called authorize that takes a role and returns true if loggedInUser has that role. Then create an Express app with a route /dashboard that sends 'Welcome admin' if authorized as admin, otherwise sends 'Access denied'.
Express
Need a hint?

Use loggedInUser.role to check authorization. Create an Express route that sends different responses based on authorization.