I'm trying to avoid DB access upon authentication to improve performance
a valid solution after lots of searching seems to be storing an encrypted string in cookie and try to decrypt it upon authentication.
Thus, I am wondering if the following is a good idea:
- transmit everything via SSL (I'm lazy..)
- set a global constant secret key in my program
- generate a new random verification string upon registration and password change, store it in the User object
- generate an encrypted verification string with verification string and secret key
- store the unencrypted and encrypted verification strings in the cookie
- when user tries to login, decrypt the verification string and check against the original verification string
if it is an "OK" idea, how do I actually make it work, like:
what encryption method should I use, AES-256?
how do I do this kind of encryption/decryption in Java, using Bouncycastle?
if it is not a good idea, what should I do to avoid querying DB on authentication?
thans in advance!
The problem you describe above is called “RememberMe”. Two approaches to solve your problem:
1) Create your own authentication framework.
Upon the successful authentication put in a cookie an encrypted value of a username (I strongly not recommend to use hashing; also please do not put the user password value).
The cookie should be persistent at most for 2 weeks.
For encryption please use AES-256 encryption with BouncyCastle: How to use Bouncy Castle lightweight API with AES and PBE Please do not put any plain values in cookies. If your framework success to decrypt the cookie – the user is authenticated. If your framework cannot decrypt the cookie or the cookie does not exist - the user is not authenticated. Upon the logout please clean the cookie.
2) Please consider to use the Spring Security framework: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
It is the great framework and solves a lot of authentication / authorization problems.
Your problem is solved by the “RememberMe” feature: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-remember-me
Please tell me if you need any additional clarifications.
Best regards,
Michael