0
0
Rest APIprogramming~30 mins

Basic authentication in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Basic Authentication in a REST API
📖 Scenario: You are building a simple REST API that requires users to log in with a username and password. To keep things safe, the API uses basic authentication, which means the client sends a username and password encoded in a special way with each request.This project will guide you step-by-step to create a basic authentication check in your API.
🎯 Goal: Build a REST API endpoint that checks the username and password sent by the client using basic authentication. If the credentials are correct, the API will respond with a welcome message. If not, it will respond with an error message.
📋 What You'll Learn
Create a dictionary called users with exact username-password pairs
Create a variable called auth_header to hold the incoming authorization header string
Decode the base64 encoded credentials from auth_header and split into username and password
Check if the username and password match the users dictionary and print the correct response
💡 Why This Matters
🌍 Real World
Basic authentication is a simple way to protect API endpoints by requiring users to send their username and password encoded in each request.
💼 Career
Understanding basic authentication helps you build secure APIs and is a foundation for learning more advanced authentication methods used in web development jobs.
Progress0 / 4 steps
1
Create the user credentials dictionary
Create a dictionary called users with these exact entries: 'alice': 'wonderland', 'bob': 'builder', and 'charlie': 'chocolate'.
Rest API
Need a hint?

Use curly braces {} to create a dictionary and separate each username and password with a colon.

2
Set the authorization header string
Create a variable called auth_header and set it to the exact string 'Basic YWxpY2U6d29uZGVybGFuZA=='. This string represents the username and password encoded in base64.
Rest API
Need a hint?

Assign the exact string to auth_header including the word Basic and the encoded part.

3
Decode and extract username and password
Import the base64 module. Then decode the base64 part of auth_header (after the space) to get a string like username:password. Split this string by ':' into variables username and password.
Rest API
Need a hint?

Use auth_header.split(' ')[1] to get the encoded part. Then use base64.b64decode() and decode to UTF-8 string. Finally, split by ':'.

4
Check credentials and print response
Use an if statement to check if username is in users and if password matches users[username]. If both are true, print f"Welcome, {username}!". Otherwise, print "Authentication failed.".
Rest API
Need a hint?

Use if username in users and users[username] == password: to check credentials.