How to add session id to swift php mysql application backend - php

I am currently developing a back-end for an iOS application with Apache, PHP and MySQL. However, I am a bit lost now that I have to implement an authentication method into the application.
Whenever a user signs up to the application, a unique user id is issued and saved in the database.
Then, when the user logs in I add the unique user id to the $_SESSIONS["Id"].
In addition, when the user logs out, the session is destroyed.
However, I find it unclear on how this can help me implement an authentication method without having to log in the user again and again.
So, after logging in and the app needs other information from the database, should I pass the unique userId to the PHP script to check if it's the same as the $_SESSION["Id"]?

I'm sorry, but I don't understand what you are asking.
If you set $_SESSION["Id"] on login and destroy it on logout, then that should be sufficient.
The first line of your db script should just read
if (isset($_SESSION["Id"]) {
// do stuff knowing the user is authenticated
}

Related

How to get mysql database updates to trigger re-authentication in PHP sessions

When starting a session, an authentication is made to the database through a query. If this authentication is granted, one or more session variables are filled with data. This allows the user to transfer through multiple pages without having to re-authenticate - which is great. However, if a session variable that is being used is changed within the database, i.e. username change, access privileges change, the changes are not rippled through to the session (obviously).
How is it possible to get the database changes to trigger, or ripple to, the PHP session variables.
An example is being logged into a website where you have access privileges x that allows you to access pages 1,2,3. Your privileges are now taken away for some reason and you now have access privileges y which allows you to only access page 1. If the user is already authenticated within the site, these changes will not affect the users current session, and will still be able to access pages 2 and 3. This could be an issue in many situations.
Currently my solution to the problem is to re-authenticate the user every page, and update the session variables accordingly. This definitively seems the wrong way to accomplish this task from my limited understanding of how sessions (should) work.
Essentially, I would like a way for database updates to trigger a re-authenticate of the current logged in user. i.e. if user john12 has his database row altered, then his session should require re-authentication.
At the moment I can't think of any way to accomplish this without querying the database every time a page is loaded.
Any tips or solutions would be greatly appreciated.
How I usually do it is by having 4 fields for authentication is my database.
Username
Password (usually hashed)
Token
Logged IP
I remember the user's auth data in cookies. When user has entered the right username and password the website generates a new token and sets two cookies - username and token. On every page load you check if the username, token and logged IP match (to prevent token steal).If one of them isn't right remove all of them and redirect to login page.
In your case if you want to relogin on password change just delete the token when it has been changed.
The only con here is that only one machine can be logged at a given time.
I don't see why you don't want to query the database for user permissions, SQL databases are incredibly fast even with lots of records especially if searching by primary key.

PHPSESSID VS sennding user/pass in android

I'm new to Android/Java programming and I came across an issue where I have to use PHP session to keep the user logged in (persistant login), this has a set of methods form using httpclient cookie or using SharedPreferences and it made think of this solution instead of using session,
1- Login the user with backend with HTTPs, this will happen only the first time the user login, the app I'm working on requires one time login and no logout mechanism. the user name and password will be sent by SMS after installing the app.
2- If user exist save the save the user/pass(could be token here) in SharedPreferences
3- Whenever the user needs something from the backend send the user/pass over HTTPs and the backend will reply if the user/pass(could be token here) is correct.
My question is, do you think the overhead of checking the user/pass or token with every request is a bad idea?
The reason I'm asking this is that PHP session ID use the same method by checking the file that has the session variables which looks like the same overhead caused by checking the user/pass or token against DB.
I don't think there's much diference, what I actually do is create a token which contains the user identifier encripted with a salt, that way you can just verify credentials at the login and then use that token during the session, you can then easily retrieve the user on the PHP and do whatever needs to be done. I woulnd't recommend passing the user/pass every time, more query complexity and risk of credentials steal. About the session... I've never messed with it for a REST based service called by a mobile device client just because I don't see the need, guess it depends on what does the service do.

How to recognize user before and after logging in Symfony 2?

I’m using Symfony2.1, a very simple login form based on documentation (http://symfony.com/doc/current/book/security.html#using-a-traditional-login-form) and a custom authentication success handler.
Anonymous user can do some action which are stored in database with the user's session ID. Now the user is logging into the system and I want to update saved actions with user's ID so that logged user can continue its work . Unfortunately in success handler I have already an updated session ID and I don’t know which records in action's table belongs to user (since they are stored with old session ID that I can’t access to [or can I?]).
What is the best practice to handle this kind of situations. Should actions be saved in database with token stored in cookie instead of session id or is there a build in mechanism and I’m trying reinvent the wheel or maybe I’m asking wrong question and therefore I can’t find answer.
The default mechanism of generating a new session id on an access level change is best practise. You could write your own authentication that does something with the new and old session ID. But unless you really know what you are doing security and authentication code is best left alone.
Best method would be as you suggest to save a token in the database and in a cookie and track your users with that. Don't forget to clean up the used tokens in the database and cookies if you no longer need them.

Session Tracking - If User Is Logged In

I'm trying to implement Facebook authentication into my web project. I've managed to get login working just fine, but I am unsure as to how to proceed further.
I need to continuosly make sure that the user is logged in and authenticated while using my application. In previous projects I've achieved this by storing userid and password in cookies and run a check against the mysql "users" table each time a php page was called.
I haven't found any tutorial which describes how to do this with Facebook, as all the tutorials ends after login is complete.
I'm thinking of storing the FB_UID in a php session variable, and then check it against the mysql "users" table to see if it's correct each time a php page is called. However I get a feeling that this is unneccessary, and that the FB session variables can be used for this purpose. Any thoughts or insights appreciated!
I will of course implement https when the site goes online due to php session security issues.
When the user login to his/her facebook account, authenticate that use against database (check username, password, ...). If they match, create session(s). From that point use session for the authentication.
With the above way, people can hijack session. Enabling cookie can prevent it.
I hope that helps.
You can use FB.Event.subscribe() call. From the website:-
Global Events to which you can subscribe:
auth.login - fired when the user logs in
auth.authResponseChange - fired when the authResponse changes
auth.statusChange - fired when the status changes...
While authenticating a facebook user, if the FB_UID matches your users table, have a php session variable store the FB_UID and check if the php session variable is set or not, every time the page loads. Finally when the user logs out, unset the php session variable.

How to Prevent Concurrent User Logins in PHP/MySQL Site?

I am developing the user management portion of a website that will host a webcast. The goal is to prrevent the same user nam (email address) from being used concurrently. That is, we don't want two individuals using one login to view the event.
I've already setup a table that holds the user registration data with regID as primary key. My thought is to create a login history table with username as primary key, foreign key to user name in registration table. The login history table would simply timestamp when the user logs into the site. However, this won't accomplsih my goal of preventing more than one individual from using the same login name.
Instead, would it be better to have a login status field either in the login history or user table that is set to 1 for logged in and 0 for logged out? It would need a stored procedure to update the value at login and at logout, and would need to be validated when a user logs in such that if login status = 1, user already logged in and cannot login a second time. Is this a feasible approach?
Please share other methods you've used to prevent the same login credential from being shared amongst multiple individuals.
Thanks,
Sid
If it is OK to logout an already logged in user if someone else logs in with the same credentials then you could do the following: when a user logs in generate a random ID in your database for that user and the same in a cookie session. The two must match to authenticate.
Without rolling your own session handler, you could do a little parallel tracking. When a user logs in, you can store the user's session ID and login time in the database (maybe inside the user information table). The login script could then check for the existence if this sessionID and allow/deny login based on the presence of the session ID. If the ID's null/blank, then the user logs in. If there's a session ID present, and it's more than X minutes old, allow the login. Otherwise deny them.
Of course, you'd probably want to roll your own session cleanup handler at that point, so that when stale session files get deleted, you can remove the associated IDs from the database at the same time.
The problem here is detecting the user is logged in (i.e. whether he didn't logout).
One possible way is to register in the database the time of his last activity and the time of his explicit logout. You could then deny a login if it this was attempted less than say 5 minutes ago relatively to his latest activity and if he didn't login in between.
You could force "activity" by having the website pages periodically poll the server with Javascript.
It's easy to determine when someone logs in. It's much harder to determine when someone logs out. If you have a mechanism of killing the webcast streaming to a particular user quickly, you might want to have something which pops up asking the user if they want to kill their other session if you think there might be one active.
How are you doing user sessions on the server? If you store them in the db, you could query the active sessions anytime someone attempts to log in and see if they're already in there. Of course you'd probably also have to check some kind of timestamp since you're not guaranteed that sessions will disappear at session.gc_maxlifetime.
You might want to consider making a global variable in php to store a hash array with login status. This has the benefit that if the application has to be restarted for some reason, the user isn't stuck in the wrong state in the database.
You can store a mapping from user ID to IP or session cookie and redirect requests that come with different information to the login page. If the user logs in, the other session would be invalidated and further requests in the last session forward to the login page.

Categories