Middle+
Have you implemented authorization? How did you work with tokens?
sobes.tech AI
Answer from AI
Yes, I implemented authentication, most often using JWT (JSON Web Token) for session management.
The main scheme for working with tokens:
- The user enters login and password.
- The server verifies the data and, if correct, generates a JWT with the necessary permissions and expiration time.
- The token is sent to the client, which stores it (for example, in localStorage or a cookie).
- In subsequent requests, the client adds the token to the Authorization header: Bearer <token>.
- The server checks the validity of the token and, if everything is in order, grants access to protected resources.
Example of token validation on the frontend (React):
const token = localStorage.getItem('token');
fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => {
if (response.status === 401) {
// redirect to login page
}
return response.json();
})
.then(data => console.log(data));
It is also important to implement token refresh mechanisms to maintain the session without re-login and to protect against XSS/CSRF attacks.