0

I have a little bit of a problem understanding cookies,session and authentication in a java web app.

Basically I have an authentication class, to an object of which my servlet gives the request object, and it is responsible to return true or false depending on whether the user has logged in or not.

So, every time a user logs in, I will create a big random string, and i will give it as a value to the response.cookie and also to the session object as an attribute, is that right? An when that user makes an other request, i will compare the cookie he just sent me to the cookie of his session to see if it is the same, and then he will be authenticated, right?

Maybe I say wrong things here, that's why I want someone to explain me if the authentication of a user is the above process or where i am mistaken.

thank you

2 Answers2

0

A simple way is to set a flag in the session (or the user object itself) when the user is authenticated. You don't have to do anything with cookies - let the container manage maintaining your session using the cookie. You just concern yourself with the session itself.

To be more efficient, you code optimize your code to not create a session until the user is logged in. But then you may not be able to store other information (such as shopping-cart contents) of a user that has not been logged in. The small memory savings is not worth the extra hassle.

I would suggest using a framework - JAAS is too abstract/complicated. Use something like Shiro

Καrτhικ
  • 3,833
  • 2
  • 29
  • 42
  • that's it? just a flag? not cookies? is that safe? so this method is optimum for keeping a user logged? –  Feb 06 '13 at 02:37
  • 1
    Yes. The app server will write a session-id to the cookie and use that to associate the correct session instance to the thread that is processing the user's http request. The session data cannot be tampered with by the end-user but the cookie sure can. The session only stays on the server. It is never sent to the client. – Καrτhικ Feb 06 '13 at 02:40
0

Either have a security framework (like JAAS) handle it, or store the data in the session. Storing it in the cookie is horribly insecure and vulnerable to a whole range of attacks. See this similar question

Cookies are stored client side, and session are managed in the server and are therefore, more secure. Using JAAS or other frameworks will give you more sophisticated authentication/authorisation options.

Community
  • 1
  • 1
Romski
  • 1,912
  • 1
  • 12
  • 27
  • i am not allowed to use frameworks. So can i just have a boolean variable in the session object, which will tell me in every request if the user is logged in? is that good technique? –  Feb 06 '13 at 02:41