Bearer Token Authentication
📖 Scenario: You are building a simple REST API that requires users to authenticate using a bearer token. This is a common way to secure APIs by sending a secret token with each request.
🎯 Goal: Create a REST API endpoint that checks for a bearer token in the request headers and returns a success message if the token is valid, or an error message if it is missing or invalid.
📋 What You'll Learn
Create a variable called
VALID_TOKEN with the exact value 'abc123token'.Create a function called
check_token that takes a headers dictionary as input.In
check_token, check if the Authorization header exists and starts with 'Bearer '.Extract the token from the
Authorization header and compare it to VALID_TOKEN.Return
True if the token matches, otherwise False.Create a function called
api_endpoint that takes a headers dictionary as input.Use
check_token inside api_endpoint to verify the token.Return the string
'Access granted' if the token is valid, or 'Access denied' if not.Print the result of calling
api_endpoint with the headers {'Authorization': 'Bearer abc123token'}.💡 Why This Matters
🌍 Real World
Bearer token authentication is widely used to secure APIs in web and mobile apps. It helps ensure that only authorized users can access protected resources.
💼 Career
Understanding bearer token authentication is essential for backend developers, API developers, and anyone working with secure web services.
Progress0 / 4 steps