Authentication - kollektivesplagiieren/innovative-commercial-market GitHub Wiki
Theory
Token-based vs. session-based authentication
Token-based authentication
Token authentication involves issuing a unique token (usually a long string of characters) to a client after they successfully authenticate. The token is typically generated by the server and sent to the client after a login request. The client stores the token, usually in local storage or a cookie, and includes it in subsequent requests to the server. The server validates the token on each request by checking if it matches a stored token and whether it's still valid. Tokens can be used for stateless authentication, meaning the server doesn't need to store session data, making it suitable for scaling and microservices architectures. Tokens often have an expiration time (e.g., JWTs) and can carry additional data (claims) beyond authentication.
Session-based Authentication
Session authentication involves creating and managing a session for each authenticated user on the server. When a user logs in, the server creates a session and typically generates a unique session identifier (a session ID). The server stores session data on the server-side, associating it with the session ID. The client receives a session ID (usually in a cookie) and includes it in subsequent requests. The server uses the session ID to look up session data and authenticate the user on each request. Sessions are typically stateful, meaning the server must manage session data and may require sticky sessions in load-balanced environments. Sessions can be more secure if implemented correctly but can introduce server-side storage and scalability challenges.
Strategies
PassportJS with JWT
Now here is how everything is going to work:
- When the user logs in, the backend creates a signed token and returns it in response
- The client saves the token locally (typically in localStorage) and sends it back in every subsequent request that needs authentication
- All requests needing authentication pass through a middleware that checks the provided token and allows the request only if the token is verified
References
- Token-based and session-based authentication: https://www.geeksforgeeks.org/session-vs-token-based-authentication/, https://stackoverflow.com/questions/40200413/sessions-vs-token-based-authentication
- PassportJS with JWT: https://medium.com/front-end-weekly/learn-using-jwt-with-passport-authentication-9761539c4314