JavaScript · API · Intermediate
Token Authentication
Register a user, obtain an auth token, and make authenticated API requests.
Quick topic start and explanations before exercises (exercises below):
Registration, token, and authenticated requests
#Token auth reference
#Exercises:
Get an auth token
#POST to `/api/auth/token/` with your credentials. Print the token you receive.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// POST /api/auth/token/ with username and password
// print the token
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
});
const data = await response.json();
console.log(data.token);
}
main();
Fetch your profile
#Get a token, then use it to fetch `/api/users/profile/`. Print `username` and `email`.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. get token
// 2. GET /api/users/profile/ with Authorization header
// 3. print username and email
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const profile = await fetch(`${BASE_URL}/api/users/profile/`, {
headers: { 'Authorization': `Token ${token}` },
}).then(r => r.json());
console.log(profile.username);
console.log(profile.email);
}
main();
Check what happens without a token
#Try to fetch `/api/users/profile/` without any Authorization header. Print `response.status` and `response.ok`. Then repeat with a valid token and compare.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. fetch profile without auth — print status and ok
// 2. fetch profile with valid token — print status and ok
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// Without token
const r1 = await fetch(`${BASE_URL}/api/users/profile/`);
console.log('No token:', r1.status, r1.ok); // 401 false
// With token
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const r2 = await fetch(`${BASE_URL}/api/users/profile/`, {
headers: { 'Authorization': `Token ${token}` },
});
console.log('With token:', r2.status, r2.ok); // 200 true
}
main();
Register a new user
#Register a new user by POSTing to `/api/auth/register/`. Use a unique username. Print the token and username from the response.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// POST /api/auth/register/ with username, email, password
// print token and username
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/auth/register/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: 'newuser_' + Date.now(),
email: '[email protected]',
password: 'SecurePass123!',
}),
});
const data = await response.json();
console.log(data.token);
console.log(data.user.username);
}
main();
Reusable auth helper
#Write a `getAuthHeaders(username, password)` async function that fetches a token and returns the headers object `{ Authorization: "Token ..." }`. Use it to fetch the profile and the cart.
const BASE_URL = 'https://apilearn.tukas.dev';
async function getAuthHeaders(username, password) {
// fetch token, return headers object
}
async function main() {
const headers = await getAuthHeaders('YOUR_USERNAME', 'YOUR_PASSWORD');
// use headers to fetch profile and cart
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function getAuthHeaders(username, password) {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
}).then(r => r.json());
return { 'Authorization': `Token ${token}` };
}
async function main() {
const headers = await getAuthHeaders('YOUR_USERNAME', 'YOUR_PASSWORD');
const profile = await fetch(`${BASE_URL}/api/users/profile/`, { headers }).then(r => r.json());
console.log('Profile:', profile.username);
const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json());
console.log('Cart items:', cart.items.length);
}
main();