Session-based authentication is a method where the server creates a session for a user after they log in. This session is stored on the server and linked to a client-specific identifier, often a cookie. This approach is commonly used in web applications to maintain user state and ensure secure access to resources. Below are three practical examples that illustrate how session-based authentication can be implemented in APIs.
In this example, we will demonstrate a simple login system for an online bookstore API that uses session-based authentication to manage user sessions.
To begin, the user submits their login credentials (username and password) to the API. If the credentials are valid, the API creates a session and returns a session ID, which the client stores in a cookie.
After the session is established, the user can make authorized requests by including the session ID in the header.
// User login request
const login = async (username, password) => {
const response = await fetch('https://api.bookstore.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (response.ok) {
const data = await response.json();
document.cookie = `sessionId=${data.sessionId}; path=/`; // Store session ID in a cookie
} else {
console.error('Login failed');
}
};
// Example of making an authenticated request
const getBooks = async () => {
const response = await fetch('https://api.bookstore.com/books', {
method: 'GET',
headers: { 'Authorization': `Bearer ${getCookie('sessionId')}` }
});
if (response.ok) {
const books = await response.json();
console.log(books);
} else {
console.error('Failed to retrieve books');
}
};
This example demonstrates how a user can log out and terminate their session in a social media API. When a user logs out, the session ID should be invalidated on the server, ensuring that the user cannot access protected resources afterward.
// User logout request
const logout = async () => {
const response = await fetch('https://api.socialmedia.com/logout', {
method: 'POST',
headers: { 'Authorization': `Bearer ${getCookie('sessionId')}` }
});
if (response.ok) {
document.cookie = 'sessionId=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'; // Clear cookie
console.log('Successfully logged out');
} else {
console.error('Logout failed');
}
};
In this example, we will illustrate how a mobile application can use session-based authentication. Users log in using their credentials, and the app stores the session token securely. This approach helps maintain the user’s authenticated state throughout the application.
// User login in mobile app
const login = async (username, password) => {
const response = await fetch('https://api.mobileapp.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (response.ok) {
const data = await response.json();
await SecureStore.setItemAsync('sessionId', data.sessionId); // Store session ID securely
} else {
console.error('Login failed');
}
};
// Example of making an authenticated request
const fetchUserProfile = async () => {
const sessionId = await SecureStore.getItemAsync('sessionId');
const response = await fetch('https://api.mobileapp.com/profile', {
method: 'GET',
headers: { 'Authorization': `Bearer ${sessionId}` }
});
if (response.ok) {
const profile = await response.json();
console.log(profile);
} else {
console.error('Failed to retrieve profile');
}
};
These examples illustrate the versatility of session-based authentication across different platforms and use cases, highlighting its importance in securing user sessions in API interactions.