JavaScript · API · Средний
JWT-аутентификация
Используйте JSON Web Tokens для аутентификации и обрабатывайте обновление токенов.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Получение и обновление JWT-токенов
#Справочник JWT
#Упражнения:
Получить JWT-токены
#POST к `/api/auth/jwt/` с вашими учётными данными. Выведите оба токена — `access` и `refresh` (первых 30 символов достаточно).
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// POST /api/auth/jwt/ и вывести access + refresh (первые 30 символов)
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/auth/jwt/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
});
const { access, refresh } = await response.json();
console.log('access:', access.slice(0, 30) + '...');
console.log('refresh:', refresh.slice(0, 30) + '...');
}
main();
Использовать access token для запроса
#Получите JWT-токены, затем используйте `access` токен с префиксом `Bearer` для запроса к `/api/users/profile/`. Выведите `username` и `email`.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// получить JWT, использовать access token с префиксом Bearer для запроса профиля
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { access } = await fetch(`${BASE_URL}/api/auth/jwt/`, {
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': `Bearer ${access}` },
}).then(r => r.json());
console.log(profile.username);
console.log(profile.email);
}
main();
Обновить access token
#Получите начальные JWT-токены, затем сразу вызовите `/api/auth/jwt/refresh/` с токеном `refresh`. Выведите новый `access` токен (первых 30 символов) и убедитесь, что он отличается от старого.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// получить токены, затем обновить, сравнить старый и новый access
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { access: oldAccess, refresh } = await fetch(`${BASE_URL}/api/auth/jwt/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const { access: newAccess } = await fetch(`${BASE_URL}/api/auth/jwt/refresh/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh }),
}).then(r => r.json());
console.log('Old:', oldAccess.slice(0, 30));
console.log('New:', newAccess.slice(0, 30));
console.log('Different:', oldAccess !== newAccess);
}
main();
Декодировать payload JWT
#Получите access token. Payload JWT — это средняя часть (между двумя точками), закодированная в base64. Декодируйте её через `atob()` и `JSON.parse()`. Выведите `user_id` и `exp` из payload.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// получить access token
// разбить по '.', взять индекс 1, декодировать через atob, распарсить JSON
// вывести user_id и exp
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { access } = await fetch(`${BASE_URL}/api/auth/jwt/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const payload = JSON.parse(atob(access.split('.')[1]));
console.log('user_id:', payload.user_id);
console.log('exp:', payload.exp);
console.log('expires:', new Date(payload.exp * 1000).toISOString());
}
main();
Полный JWT-поток
#Напишите полный скрипт: получите токены, запросите профиль через `access`, обновите токены, затем запросите корзину с новым `access`. Выведите username из профиля и количество товаров в корзине.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. получить JWT-токены
// 2. запросить профиль через access
// 3. обновить токены
// 4. запросить корзину с новым access
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. Initial tokens
let { access, refresh } = await fetch(`${BASE_URL}/api/auth/jwt/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
// 2. Fetch profile
const profile = await fetch(`${BASE_URL}/api/users/profile/`, {
headers: { 'Authorization': `Bearer ${access}` },
}).then(r => r.json());
console.log('Username:', profile.username);
// 3. Refresh
({ access, refresh } = await fetch(`${BASE_URL}/api/auth/jwt/refresh/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh }),
}).then(r => r.json()));
// 4. Fetch cart with new token
const cart = await fetch(`${BASE_URL}/api/cart/`, {
headers: { 'Authorization': `Bearer ${access}` },
}).then(r => r.json());
console.log('Cart items:', cart.items.length);
}
main();