Sobes.tech
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:

  1. The user enters login and password.
  2. The server verifies the data and, if correct, generates a JWT with the necessary permissions and expiration time.
  3. The token is sent to the client, which stores it (for example, in localStorage or a cookie).
  4. In subsequent requests, the client adds the token to the Authorization header: Bearer <token>.
  5. 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.