authentication safely - php

So I currently store a token and user ID whenever a user logs in. The token is stored in the user table and in a COOKIE.
So user 1 logs in and the following details is stored in a COOKIE and database on his
computer:
id
randomly generated token
whenever he logs in a different token is generated.
To authenticate the user, everytime he accesses my site, I check to see if the token matches with that stored in the database for the specific cookie.
But the problem is that constantly checking the database is a waste of resources but how do we make sure that user is who they say they are? I can't just store his ID in a cookie because he could easily change the ID and get access to another user's information.
thanks!

Could you use a $_SESSION variable such as: $_SESSION['id'] = $randomstring;
Then at the top of each page check if the variable is set:
<?php if(isset($_SESSION['id'])) $loggedin;
else $logout;
?>

Use session_start() which handles the logistics of checking the cookie and validating that the data is actually for that user's session.
You have to start the session before you can use $_SESSION but that's one way to store session data.
http://php.net/manual/en/function.session-start.php

Related

PHP: Allow only one login per user

Currently, I try to implement that only one user can be online simultaneously on the same account. There are solutions which prefer to store the session id and compare it to the current session id. But I have problems to understand how it should work.
So I store the session id after the user's login was successful. Now I am trying on another client to log in on the same account. It is not possible because the current session id is not equal to the stored id. So what happens if ...
1) Using logout button
The user uses the logout button. The session is destroyed. I reset the stored session id to "" or something. If the stored session id is "" a client can log in on this account. Is it right?
2) The browser is closed
Closing the browser without using the logout function. There is still a session id stored. I can not log in with this account because my current session id is not equal to the stored session id. So how can I realize a re-login?
i believe you can solve that problem simply by storing a variable in a user field database to indicate it's been logged in.

Perform queries/tasks on specific users

I got a user system, with session for both their username and ID. I also got a field in my users table named user_locked which determines if the user's account is locked or not (if it's locked; they can't log in).
Recently I added a feature on my site where it allows me to lock users easily by one click, and I then got the idea: is it possible to force that specific user to get logged out (make his/her session/cookies get destroyed) while leaving everyone elses unharmed?
Is it possible? If it is, how would I do?
Thanks.
My approach would be:
User logs in
You start a session for him and store whatever session variables you want
You store this session's ID in a table at your database with user id/username info
Whenever you want to destroy his session and log him out you follow this routine:
// old_session_id will be retrieved from your database table for
// this current user that you want to force log off
session_id($old_session_id);
session_start();
session_destroy();
Destroy php session remotely

PHP login session and cookie

On my PHP website, users can login and have the possibility to check "Remember me" to set a cookie.
What should I be storing as a SESSION variable? The username, hashed password and user ID, or only the user ID? If I only store the user ID, wouldn't it be possible for someone to edit the SESSION and change the ID?
What about the COOKIE? Should I store only the user ID? As far as I know, cookies can be modified by the end user...
It seems that you don't have a clear vision of sessions and cookies!
No body can change the session contents except your code (beside attacks). So you can store everything (reasonable) like user id or username that you need to access frequently. in cookies you must store some obfuscated information that you can recognize user later when he/she tries to access your page. so based on cookie content you can regenerate users session (ie. re-login user automatically). Just to note that user CAN change cookies content so it must not be something simple like user id for security reason.
I just give you a simple example, it's far from perfect but not so bad! you may need to tailor it to fit your scenario:
here you can create cookie content like this:
$salt = substr (md5($password), 0, 2);
$cookie = base64_encode ("$username:" . md5 ($password, $salt));
setcookie ('my-secret-cookie', $cookie);
and later to re-login user you do:
$cookie = $_COOKIE['my-secret-cookie'];
$content = base64_decode ($cookie);
list($username, $hashed_password) = explode (':', $hash);
// here you need to fetch real password from database based on username. ($password)
if (md5($password, substr(md5($password), 0, 2)) == $hashed_password) {
// you can consider use as logged in
// do whatever you want :)
}
UPDATE:
I wrote this article that covers this concept. Hope it helps.
You should be storing the random session value in the cookie. You definitely should not be storing any information about the user in the cookie itself. You can then check the session id in the cookie on each page load to ensure that (a) the user should have access to that content and (b) that the session ID is valid.
In PHP you can use session_set_cookie_params and session_name to set the parameters of the cookie.
For who may prefer using cookies (So you can access it long time later even if the browser was closed) this is a safe way to store even rough ID in cookies:
Create a new field in users database name it X.
Generate a cookie to keep the user ID.
Generate a safe (say long) RandomString and keep it in another cookie.
Also save that random string in the filed of X.
In members area check if cookies of ID and RandomString match the database information.
Clear column X when user signs out and generate data for X on next login.
To prevent library attack to match that random string, you may also force logout as soon as the check fails or blocking that IP for a certain time.
User cannot edit session variable, these are managed on server.
Session Variable Advantage
1.)Secure
2.)Robust
Session Disadvantage
1.) Short life time, untill session exist ,
session get destroyed
when user close his browser
server restart
session destroyed using session_destroy();
So session is more secure
Cookie on the other hand let you remember user prefrences
If you use combination of both , then its advantage to your code
You can store userid and username in cookie, then verify user identity using its combination.
If its not exits then you can login user and keep info in session as well as update cookie.

restrict access to single user on php website [duplicate]

I would like to make my website to allow only one session at a time. For example, let say user has login to my website on firefox, if the user login again to another browser like opera on the same computer or different computer, the session on firefox will be destroyed. However, the session on firefox remained if it remains as one session. May I know how can I do that? I am using php and apache. Thank you.
Regards.
Benjamin
I'll suggest you to do something like this:
Suppose when user "A" loges in to the "Com_1", for the first time. Save a unique code in the database against that session, and same with the user session.
At the mean time if he (user "A") loges in again on "com_2", then check his status in the database and update the unique code in the database.
again back if same user (user "A") refreshes the page on "com_1", we all you need to do is check the unique code from the session and match it to the database, It is for sure it will not match, then log it out and destroy the session.
For keeping the user loggedin, even if browser is closed, you can store the cookie on the browser, and re-generate the session accoordingly.
Hope this helps. Thank you.
You can use the following algorithm
create an integer field in the databse userLoggedInCount
On each login increment that flag and store the result in the session.
On each request check the value in the database and the one in the session, and if the one in the session is less than the one in the DB, invalidate() the session and decrement the value in the database
whenever a session is destroyed decrement the value as well
Credits to Bozho because he posted this, answering to a question
here
Keep a central database table or text file of who is logged in at the moment. If a user is already logged in in another session, invalidate that session by setting the "logged in" flag to false.
I think you'd have to do something like that :
add a "last_session_id" column to your user table
when a user logs in, update its last_session_id field with its current session id
on each page, if the user has an authenticated session, check if the session id is equal to the one recorded in your database. If not, destroy this session.
Store session id in the database. retrieve last login session id from db, set session id using session_id(oldid) and change session variables related to authentication like $_SESSION['LOGIN']
and destroy the session and create new session with new session id. follow example for logic https://www.php.net/manual/en/function.session-create-id.php.
this will make the last login allowed. validate on each page session variables related authentication. this makes it session invalid because of this session_id reset by a new login.
Save users' IP=>SESSION_ID pairs in a database. When user try to load your page you must compare the actual IP=>SESSION_ID pair then allow/deny if the pair is ok/different.

$_SESSION['loggedin'], identification of particular user and security questions

Please, advice if my thoughts are correct. I have searched for information but have not found exact answer.
User enters username and password and the entered username/password are the same as in mysql.
I create $_SESSION['loggedin'] = 1; This means that somewhere on server is created file with random name like r21bj2a3.... and in user browser is created cookie with value like r21bj2a3....
On next page I check if( $_SESSION['loggedin'] == 1 ). User browser connect to server, send to server information like: I have cookie with value r21bj2a3...., please send me content of ? session? Server sends information that for the particular cookie session loggedin is 1.
As I understand if malicious user gets cookie value r21bj2a3...., sends to server and gets the same answer as normal user?
Depending on $_SESSION['loggedin'] I can not identify particular user? To identify particular user after successful login I can create unique token, record in mysql and pass with session? And on password protected page from the passed session I get token value and check (select) if such value exists in mysql. Is this way ok? May be post some link with good method?
Regarding token. I pass the token value with sessions. That means if malicious user get cookie value, send to server and get answer, containing token value (so malicious user gets rights of normal user)?
I suggest to save all active sessions in the database, you can create a table for doing that, to prevent session hijacking, you can check each particular session (login) and see if user already authenticated, then, do not allow second authentication.
The problem here, how to recognize user?
You can bind some Information like USER_AGENT, and IP Address, however, these information can also be spoofed by hacker, but, the probability is less.
Also, once user signed out, you can delete the session record in the database.
HTTP is stateless protocol.It does not keep track of data across several pages.So we require session which can be globally accessible across all pages in website
For identifying the user who is currently logged into website we need to store value of user_id field in user table into session after he is authenticated successfully.
e.g.
$_SESSION['user_id']=$result['user_id']
And to determine whether user is logged in or not we can check the value of $_SESSION['user_id'] variable .If it is empty then user is not logged in else user is logged in
To identify which user the session belongs to, just set a viable in the session
$_SESSION['user'] = user
You are correct about the cookie giving access to the session. If security is important, use SsL.

Categories