0
0
Ruby on Railsframework~30 mins

Token-based authentication in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Token-based authentication
📖 Scenario: You are building a simple Rails API that uses token-based authentication to secure user access. Users will have unique tokens that the server checks to allow or deny access to protected resources.
🎯 Goal: Create a Rails controller that authenticates users by checking a token sent in the request headers. You will set up a user data structure, configure a token variable, implement the authentication logic, and complete the controller to respond based on token validity.
📋 What You'll Learn
Create a hash called USERS with usernames as keys and tokens as values
Add a variable valid_token to hold the token from request headers
Write a method authenticate_user that checks if valid_token matches any token in USERS
Complete the controller action to render json: { message: 'Access granted' } if authenticated, else json: { message: 'Access denied' }
💡 Why This Matters
🌍 Real World
Token-based authentication is commonly used in APIs to secure access without sessions or cookies. It allows stateless, scalable authentication.
💼 Career
Understanding token-based authentication is essential for backend developers building secure APIs and services.
Progress0 / 4 steps
1
Set up user tokens
Create a constant hash called USERS with these exact entries: 'alice' => 'token123', 'bob' => 'token456', and 'carol' => 'token789'.
Ruby on Rails
Need a hint?

Use a Ruby hash with string keys and string values for tokens.

2
Get token from request headers
Add a variable called valid_token that gets the token from request.headers['Authorization'] inside the controller action.
Ruby on Rails
Need a hint?

Use request.headers['Authorization'] to get the token string.

3
Check token validity
Inside the authenticate method, write a condition that sets authenticated to true if valid_token is included in the values of USERS, otherwise false.
Ruby on Rails
Need a hint?

Use USERS.value?(valid_token) to check if the token exists.

4
Respond based on authentication
Complete the authenticate method to render json: { message: 'Access granted' } if authenticated is true, else render json: { message: 'Access denied' }.
Ruby on Rails
Need a hint?

Use an if statement to render different JSON messages based on authenticated.