PHP user authentication tutorial without sessions - php

I need to build my own system for part of a computer security project without using php sessions (just cookies) and im just lost. All the tutorials ive found use sessions (for good reason) so I was wondering if anyone knew of a roll your own php user authentication tutorial.

You could basically implement something session like yourself.
This would include the following tasks:
generate a random session id for new users (or on login - based on the exact use...)
save it into a cookie
do save additional session inforamtion somewhere on the server together with the session id (e.g. in a database table)
on subsequent page accesses check the session id in the cookie versus the data on the webserver to identify users and grant access
However it should be mentioned that a cookie only based solution is never that good. If a client for example doesn't have cookies enabled it won't work at all. A possible solution for this is to send the session id as GET parameter with every internal link if cookies are not enabled.

Sessions would make it much easier. That being said, where are you getting stuck mate?
To get started using Cookies in PHP, check this out: http://www.w3schools.com/php/php_cookies.asp
You could either
implement your own Session handling as s1lence suggests (which might be exactly what the professor wants you to do) or
implement your own Session handling through appending the session id to the QueryString (making it work for non-cookie browsers) or
you could store the user/password pair in cookies (which would force you to reauthenticate the user for every request)
I wouldn't recommend the latter, but if it's all about avoiding the Session Mechanism it's an option I guess. And a last remark, if this doesn't have something to do with understanding why Session is important you should really question your teachers task.. ;)

You should not use cookie for such system in cause cookie are stored on the client side. And any one can change it. Sessions are stored on the server side and only you can change it (also other system users can change it if they have directory access or db access if you store sessions in db). If you strongly need to use cookie you can encrypt login/password can write to cookie, but the using of sessions is more safely.

Related

How to get started with session id's in PHP and MySQL?

So I recently made the decision to use Session ID's for authentication on my website instead of JWT's, so I'm still trying to play catch up a little bit here.
I guess my concern is pretty simple. If I'm going to have my database handle my sessions that are currently active for the users that are logged in (probably through a table that has a column with the UserID and the SessionID) how can I use PHP to generate a completely random Session ID? I will then pass that Session ID into a httpOnly cookie.
I assume this will work with my Angular front-end as I can use the withCredentials boolean option on every http request since I won't have direct access to the Session ID cookie.
So when a user wants to access a restricted area, their http request will contain the Session ID cookie and my PHP will determine what their User ID is by doing a lookup on the CurrentSession table. This will then allow PHP to determine the user's access level.
All this will be done over a HTTPS connection but I think I will still have to worry about CSRF attacks so I will probably use the Double Submit Cookie method as Angular already provides support for it.
So I guess my main question is, would simply finding out a way to generate a unique Session ID with PHP work for securing my app? Or would somehow encrypting the Session ID so only my PHP can decrypt it be a good idea, so in case somehow an attacker got access to the Session ID from the cookie, it would solely be an encrypted version of it, so it would be useless.
I would suggest using PHP's session_start() which will handle the session in its entirety including any cookies that need to be written to maintain the session depending on your particular connection at the time.
All you need to do is put this at the very top of your PHP scripts:
<?php
session_start();
A PHP constant "SID" should be available to get your session id which you could store in MySQL for other purposes if you wanted to - but it may not be necessary. You can also use session_id() as well.

Can a user manipulate cookies?

I have a question regarding usage of cookies for standard login purposes. Say my php script saves a cookie into a users computer each time he logs in. The cookie value is say "Mike" after his username at the website. Can that user somehow manipulate that cookie in his browser to change the value to say "Admin" so suddenly he has access to administration of the website?
If this could happen how to solve such security risk?
--
Additionally... What if someone was to copy cookies from my browser, either he would stare at my computer screen and copy cookies and values into his computer or such intruder could steal cookies from my browser via JavaScript.
How is that taken care of?
Yes, that is a security problem, which extends to any information provided by the client.
Cookies are stored on the user's machine. They can be modified in any way. In fact, the cookies can just be created on the fly and sent via several utilities for making HTTP requests. It isn't even a browser problem.
Never trust any data that comes from the client.
Yes, a user can manipulate cookies if they're stored on their computer.
Use a session.
A 'session' is the server-side storage of connection-relative information that is linked to the user through a variable which is passed back and forth, most often a cookie, however logically, anywhere will do if both your client and server can handle it.
This 'session' is often represented by an integer which the client and server both know.
The problem is, if another client has a session open on the server, we (as a client) could 'hi-jack' this session by replacing our given id with a random id until one is found. The server would now believe we are in fact the other use and could give us access to their private informatin.
For this reason, we have 'keys'. A key is a unique, often alphanumeric, code which is changed on each request-response pair with the server, ensuring that only those who have the latest key are able to gain access.
YES
They can manipulate, edit, modify, create and delete cookies.
You should only store a hash key that you use on the server to look up in a database anything that should be secure.
Yes, users can manipulate cookies. The best way to handle it is to not store user credentials in such a manner that they can gain admin access by changing their user name.
The specifics on how to do this are pretty deep, but a good start would be to just store the users's session identifier instead. That has its own issues, but won't let people break things quite so easily.
Cookies are clientside which means that they can be read, write and delete by the client. A cookie manager plugin makes it easier to change the cookie value.
http://www.ehow.com/how_7149468_edit-cookies-computer.html
Yes a user can easily manipulate the cookies by just going to cooking option which all popular browser provide

Is using one session secure enough?

Currently a friend of mine and myself are working on a site together. We have our login system down, but are using sessions. I, myself, have always used cookies for logins, though my friend prefers sessions.
I keep telling him we should have two or more sessions we can compare with the database to make sure it's the accurate user, and not someone who somehow scammed the ID.
For example:
$_SESSION['id'] = $YourId;
$_SESSION['salt'] = $SomethingElseTheDatabaseHas;
This making it more secure instead of just one session that the database can compare with.
Using multiple session variable to store information does nothing for security since the session data is stored server-side. The only thing that the client knows about the session is the session ID that it stores in a cookie. The server uses the session id to lookup data for the user. If you're using a hash stored in a cookie to identify users, you might as well use sessions since that basically does the same thing, but makes working with a user's data much easier.
I'm not sure exactly what you mean by using cookies to store the data, but if you mean that the client would have a cookie with their user id that the server uses for authentication, you should rewrite that immediately since it basically allows the user to be whomever they want.

Cookies/Sessions login system

When a user logins I get him/her's ID and save it in a session var. What I wonder is, is this the way to go? Or should I use cookies? so it automatically login and so on.
session_start();
ifcorrectlogin {
$_SESSION['id'] = mysql_result($loginQuery, 0, 'user_id');
}
how do you authenticate your users?
//Newbie
Yes, this is the way to go. The session itself is already backed by a cookie to remove you any programming efforts around that. The session (actually, the cookie) will live as long as the user has the browser instance open or until the session times out at the server side because the user didn't visit the site for a certain time (usually around 30 minutes).
On login, just put the obtained User in the $_SESSION. On every request on the restricted pages you just check if the logged-in User is available in the $_SESSION and handle the request accordingly, i.e. continue with it or redirect to a login or error page. On logout, just remove the User from the $_SESSION.
If you want to add a Remember me on this computer option, then you'll need to add another cookie yourself which lives longer than the session. You only need to ensure that you generate a long, unique and hard-to-guess value for the cookie, otherwise it's too easy to hack. Look how PHP did it by checking the cookie with the name phpsessionid in your webbrowser.
Cookies can be manipulated very easily. Manage login/logout with Sessions. If you want, you can store the users emailaddress/username in a cookie, and fill the username box for them the next time they visit after the present session has expired.
I would try to find a session engine so you don't have to deal with the misc. security issues that bite you in the ass if you do the slightest thing wrong. I use django which has a session engine built in. I'm not aware of the other offerings in the field although I would assume most frameworks would have one.
The way they did it in django was by placing a cryptographic hash in the user's cookies that gets updated every page view and saving all other session information in a database on your server to prevent user tampering and security issues.
As BalusC mentions, the session_-functions in php are the way to go, your basic idea is sound. But there are still many different realisations, some of them have their pitfalls.
For example, as Jonathan Samson explains, using cookies can result in security holes.
My PHP is a bit rusty, but I remember that the session_-functions can also use session IDs that are encoded in URLs. (There was also an option to have this automatically added to all local links (as GET) and form targets (as POST). But that was not without risks, either.) One way to prevent session hijacking by copying the SID is to remember the IP address and compare it for any request that comes with a valid session ID to to IP that sent this request.
As you can see, the underlying method is only the start, there are many more things to consider. The recommendation by SapphireSun is therefore something to be considered: By using a well tested library, you can gain a good level of security, without using valuable development time for developing your own session system. I would recommend this approach for any system that you want to deploy in the real world.
OTOH, if you want to learn about PHP sessions and security issues, you should definitely do it yourself, if only to understand how not to do it ;-)

What is the best practice for using Cookies for authentication with PHP?

I'm looking for tips and ideas on how to best incorporate authentication with PHP using Cookies.
Should each php script check for the cookie value to determine if the user is still logged in? Should there be one script that does this check and Include that script from each of the other scripts? Can the cookie value be seen by php from different depths of the filesystem?
Like: blahblahblah.com/ and blahblahblah.com/login/
Can they both read the cookie?
Lots of questions on one post, but thanks!
nothing is safe on the client side.
You change the login flag on Cookies easily on any browser. Thus it is more recommended to be saving login-related data on php's $_SESSION
If you wish to extend the session, simply look at session_set_cookie_params().
By default, the same session will be used for the current domain and all the paths on that domain. Thus it is readable for both blahblahblah.com/ and blahblahblah.com/login/
When the user logs in, save the username and the hash of the password in the Session.
At the start of each script, verify the Session's username and password with the one in database. If is correct, then set a flag (e.g. $userLoggedIn = true) to indicate on server-side that the user is logged in. else false.
Some thoughts, in no particular order:
Separate out the various layers: persistent storage vs authentication.
PHP sessions are quite robust and are the recommended way to maintain persistent storage.
You can have a valid session, but not a valid login.
Avoid multiple cookies. One is enough. PHP sessions work with one cookie.
You can set sub-domains and paths on cookies, but there's really little point unless you set lots, which is not recommended (see above).
Put everything you think you might want in a cookie in the session instead.
You should have some common code that all your pages include. That is where you initialize your session. Then everything will Just Work. It can also verify the login is valid, too.
Have one place that does the login authentication and everything associated with that.
Don't forget a logout screen!
Its a good idea to have one script do the session/login check and include it in the secure pages. AS for the depth , you can define that in the setcookie() if the directory parameter is set to "/" then its accessible all across.
Generally its a good idea to use sessions instead of cookies , as thats more secure , but you can decide to build your own session system based on encrypted data in the cookie and that can work too , but again sessions, which store data on the server side are recommended.
The cookie is per domain, so no matter how deep you are in your directory structure, the cookie will be read OK (as long as your domain stays the same - NB this means that www.example.com and example.com can be different cookies).
I'd suggest having an authentication check that compares the session ID in the cookie with eg a database table listing logged in users and their session ID - this check can be in its own method/include file that is include()'d on each page. That way the check will be performed on every page load. NB this is basic and there are much more secure methods - some of which have been mentioned in other comments here.
As Mauris said though, nothing is safe on the client side - don't use a cookie to store a "logged_in" value which you check for true/false!

Categories