JavaScript · API · Середній
JWT-автентифікація
Використовуйте JSON Web Tokens для автентифікації та обробляйте оновлення токенів.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Отримання та оновлення JWT-токенів
#Довідник JWT
#Вправи:
Отримати JWT-токени
#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 для запиту
#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
#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
#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-потік
#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();