Handling user authentication and authorization in a RESTful API using JSON Web Tokens (JWT) involves verifying the identity of users and granting them access to specific resources based on their roles or permissions. JWTs provide a secure and stateless way to manage user sessions and protect API endpoints. Here’s a detailed explanation of the process:
I. Authentication (Login):
1. User Submits Credentials:
- The user sends their credentials (e.g., username and password) to the API's authentication endpoint (e.g., `/login`).
2. Server Validates Credentials:
- The server receives the credentials and verifies them against a database or authentication provider. This typically involves hashing the provided password and comparing it to the stored hash.
3. Generate JWT:
- If the credentials are valid, the server generates a JWT. A JWT is a compact, URL-safe JSON object that contains information about the user, called "claims."
- The JWT consists of three parts:
- Header: Specifies the algorithm and token type.
- Payload: Contains the claims, such as user ID, username, roles, and expiration time.
- Signature: Verifies that the token hasn't been tampered with. It's created by signing the header and payload with a secret key using the algorithm specified in the header.
Example JWT generation (Node.js with jsonwebtoken library):
```javascript
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key'; // Replace with a strong, randomly generated key
function generateToken(user) {
const payload = {
userId: user.id,
username: user.username,
role: user.role // e.g., 'admin', 'user'
};
const options = {
expiresIn: '1h' // Token expires in 1 hour
};
return jwt.sign(payload, secretKey, options);
}
// Example usage
const user = { id: 123, username: 'john.doe', role: 'user' };
const token = generateToken(user);
console.log(token);
```
4. Return JWT to Client:
- The server sends the generated JWT back to the client in the response body or as a cookie.
Example response:
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywidXNlcm5hbWUiOiJqb2....
Log in to view the answer