authentication and authorization flow for web applications
Token-Based Authentication using Bearer Tokens
API 1: LOGIN:
Purpose: Authenticate the user using their credentials (username and password).
Process:
The user sends their username and password to the login endpoint.
The server verifies these credentials.
If valid, the server generates a JWT (JSON Web Token) and sends it back to the client as the response.
API 2: Data Access:
Purpose: Access protected data using the previously generated JWT as a Bearer Token.
Process:
The client includes the JWT in the
Authorization
header of their request.The server verifies the token to ensure it is valid and not expired.
If valid, the server processes the request and sends back the protected data.
Method Used:
This approach is known as Bearer Token Authentication using JWTs (JSON Web Tokens). The method ensures that each request to a protected endpoint carries an authentication token (JWT) which verifies the identity of the user.
Why Use This Method:
Stateless Authentication: The server does not need to store user session data, reducing server-side memory usage.
Scalability: Easy to scale since authentication is handled via tokens that can be verified without server-side session storage.
Security: JWTs can be securely signed and verified, and you can encode any user information or claims within them.
By employing this method, you ensure that all subsequent API calls are authenticated by passing the JWT in the Authorization
header as a Bearer Token.
API: 1: // Login API endpoint (Node.js
example)
app.post('/login', (req, res)
=> {
const { username, password } = req.body;
// Validate credentials...
const token = jwt.sign({ userId: user.id }, 'your_secret_key', {
expiresIn: '1h' });
res.json({ token });
});
API2:// Protected API endpoint (Node.js
example)
app.get('/data', (req, res) =>
{
const token = req.headers['authorization'].split(' ')[1];
jwt.verify(token, 'your_secret_key', (err, decoded) => {
if (err) return res.status(401).send('Unauthorized access');
// Fetch and send protected data...
res.json({ data: 'protected data' });
});
});
No comments:
Post a Comment