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 valuesAdd a variable
valid_token to hold the token from request headersWrite a method
authenticate_user that checks if valid_token matches any token in USERSComplete 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