-1

I'm learning about authentication in Java and Spring and about difference between session and token based authentication.

I know that in session based authentication the user sends the username/password to server. It could send the credentials using a html form or basic authentication. After that the server create a session and send the session id in a cookie header like this set-cookie: sessionid, and when the user make another request it will use the session id in a cookie header like this cookie: sessionid. And the server compare the session id stored on the cookie against the session information stored in the memory to verify user’s identity and sends response with the corresponding state.

I'm not sure what's happen in the token based authentication. The user will send the username/password to server in the same way like in the first case: html form, basic authentication, etc. The server creates JWT and send the JWT to the user browser usually in the localstorage. But what I don't understand is how the server sends the JWT to client? Does it send the JWT in a Header like this set-authorization: jwt? What is the name of the header where the jwt is put? And after that when the client does a new request the JWT will be in an authorization header like this Authorization: Bearer jwt. So I don't understand how the JWT is sent from the server to the browser. Any feedback will be apreciated! Thank you!

elvis
  • 956
  • 9
  • 33
  • 56

1 Answers1

1

What you said about Basic Authentication is somehow correct but not completely. In basic Authentication client almost always send the username and password to the server and server authenticate user by those information(it means client send those information in each request). something you said about coockie is not mandatory in basic authentication. client can store information like username and password in storage and send them on each request to server.

What about JWT and why is this much more reliable?

In JWT client use an authentication path to get the token from the server, so server provides client with an API like /user/authenticate and this path is usually secured by some other security mechanism(it can be Basic Authentication too) so client send username and password of the user to this path in header and it will get JWT token in Response Body, Then after for sending request to other resources(for instance /products) client send that token in the header of those request like this:

authorization: Bearer jwt

In JWT and other token based authentication mechanisms client should not save the username and password of the user somewhere in their storage. Something they could (or rather should) save in their storage is the token that they have received from the server, therefore something that is send in each request is the token and not username and password of the user as a result this mechanism is more secure.

Tashkhisi
  • 2,070
  • 1
  • 7
  • 20