JavaScript · API · Intermediate

Token Authentication

5 tasks

Register a user, obtain an auth token, and make authenticated API requests.

Token authentication flow

#
**A shorter way to write fetch calls** In the Beginner section, every fetch request used two separate `await` lines: ```javascript const response = await fetch(url); const data = await response.json(); ``` From here you will also see a one-line shorthand using `.then()`: ```javascript const data = await fetch(url).then(r => r.json()); ``` These two forms are equivalent. `.then(r => r.json())` is a callback attached directly to the Promise returned by `fetch()`. When the server responds, `.then()` immediately calls `r.json()` and returns a new Promise. The outer `await` waits for that JSON Promise to resolve. The shorter form is useful when you do not need to inspect `response.status` or `response.ok` before reading the body. When you do need error checking, use the two-step form -- it gives you access to `response` before consuming the body: ```javascript const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); ``` --- Token authentication works in two steps: obtain a token once, then include it in every subsequent request. **Step 1 — Register a new user:** ```javascript const response = await fetch('https://apilearn.tukas.dev/api/auth/register/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'alice42', email: '[email protected]', password: 'SecurePass123!', }), }); const data = await response.json(); console.log(data.token); // token is returned immediately on registration ``` **Step 2 — Or log in to get a token for an existing account:** ```javascript const response = await fetch('https://apilearn.tukas.dev/api/auth/token/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'alice42', password: 'SecurePass123!' }), }); const { token } = await response.json(); ``` **Step 3 — Use the token in the `Authorization` header:** ```javascript const headers = { 'Authorization': `Token ${token}`, 'Content-Type': 'application/json', }; const profile = await fetch('https://apilearn.tukas.dev/api/users/profile/', { headers, }).then(r => r.json()); console.log(profile.username); ``` The token does not expire — store it and reuse it across requests. The `Authorization` header format is exactly `Token <token>` (with a capital T, space, then the token value).

Registration, token, and authenticated requests

#
Complete flow — register, get token, make authenticated requests: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function register(username, email, password) { const response = await fetch(`${BASE_URL}/api/auth/register/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, email, password }), }); if (!response.ok) { const err = await response.json(); throw new Error(JSON.stringify(err)); } return response.json(); // { token, user: { id, username, email } } } async function getToken(username, password) { const response = await fetch(`${BASE_URL}/api/auth/token/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }); const data = await response.json(); return data.token; } async function main() { // Get a token for an existing account const token = await getToken('YOUR_USERNAME', 'YOUR_PASSWORD'); console.log('Token:', token); // Build auth headers const headers = { 'Authorization': `Token ${token}`, 'Content-Type': 'application/json', }; // Fetch the profile const profile = await fetch(`${BASE_URL}/api/users/profile/`, { headers }) .then(r => r.json()); console.log('Logged in as:', profile.username); console.log('Email:', profile.email); } main(); ``` A reusable helper for authenticated requests: ```javascript function makeAuthHeaders(token) { return { 'Authorization': `Token ${token}`, 'Content-Type': 'application/json', }; } const token = await getToken('YOUR_USERNAME', 'YOUR_PASSWORD'); const headers = makeAuthHeaders(token); const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json()); console.log('Cart items:', cart.items.length); ```

Token auth reference

#
**Endpoints** ``` POST /api/auth/register/ Register + get token body: { username, email, password } returns: { token, user: { id, username, email } } POST /api/auth/token/ Get token for existing user body: { username, password } returns: { token } ``` **Using the token** ```javascript headers: { 'Authorization': `Token ${token}` } // Format: "Token " + token value (capital T, one space) ``` **Password requirements** ``` Min 8 characters At least one uppercase letter At least one digit At least one special character (!, @, #, ...) ``` **401 Unauthorized** ```javascript const response = await fetch(url, { headers }); if (response.status === 401) { console.log('Invalid or missing token'); } ``` **Endpoints requiring auth** ``` GET/PATCH/PUT /api/users/profile/ GET/POST /api/cart/items/ PATCH/DELETE /api/cart/items/{id}/ POST/GET /api/orders/ ```
01

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();
02

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();
03

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();
04

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();
05

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();