Good Day,
I am creating a webpage that users login called "index.html" which POSTs data to the "home.php" site when the user submits the form from "index.html." Now that I am inside the "home.php" I can retrieve the posted variables, check them against the database and authenticate the user. Once I am in the "home.php" file, I would like the user to issue a GET request to the "home.php" site to display different data. Is there a way to do that and maintain the authentication?
Right now I am getting a notice saying that the POST variables are undefined. (Obviously, since I am not posting anything)
Notice: Undefined index: pass in C:\xampp\htdocs\home.php on line 7
Thanks,
Matt
It sounds like you want to use sessions.
See: http://www.w3schools.com/php/php_sessions.asp
See: http://www.tizag.com/phpT/phpsessions.php
Once you perform your initial authentication check, which would be the form submission and account verification, you should assign the user some form of session token. This is a token that you can verify is authentic that you use for a short-hand verification for subsequent requests. You can create this token a few ways:
Create a simple table to keep track of authorized session tokens and their expiration date. This ensures that only sessions you create are allowed, tied to a single account, and have a guaranteed expiration date.
Create an encrypted token format so the session token is actually an encrypted data container which you can only read on the server side with a private, rotating key. The token would contain information about the user and expiration and eliminate the need for a server side table.
In addition to the basic information for each token it would also be good to include references to the UserAgent and IPAddress of the initial authentication request so you can ensure there is no session hijacking taking place.
Once you create your token you will want to store it in a cross-request location; which can be either a session or cookie variable. This is primarily a preference, but either way, you should ensure it is only accessible from an HTTP request and not a JS request to prevent XSS (cross site scripting). Check out these artickes on sessions and cookies:
http://www.w3schools.com/php/php_sessions.asp
http://www.w3schools.com/php/php_cookies.asp
Now that you have a token you can use from anywhere in your site you will want to make an authentication handler for each of your pages to check this token and verify it is valid. Once you confirm it is authentic you can use it to figure out which user is viewing the page and what permissions they should have.
Do this
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
You can for example do that :
echo "<form method='post' action='home.php?parameter1=".$variable1."'>";
Then you have both POST and GET variables.
Edit: But I think I misunderstood you, use SESSION variables to persist the authentication through pages.
Related
I have to maintain user log-in that is authenticated by webservice (SOAP WSDL) in PHP, it returns id_session if logging successfully, there will be function to return error if the given id_session expired.
When Logging in with the user credential, I use ajax in a specific php file to verify it, so the result will be receiving from ajax response (JS), how would I use it to maintain the session in php?
if I use cookie to maintain it only, is it enough? is there a way to store the session id encrypted securely but still can use it?
The only idea I have is storing it in cookie, & remove the cookie's value when it's expired which does not seem to be good practice.
First of all never store a plain password in a session. Also you should check the session everytime the user does something (refresh page, do a query, ...)
Also sessions aren't available in JS. You are probably thinking about cookies. And those aren't secure cause they can be tampered with if wanted to.
Are cookies necessary to create a login page with php (that keeps you logged in across several pages), or could a session variable do the trick without use of cookies?
Answer simply is yes.
Sessions rely on a session id.
Sessions in php use a cookie to store this id, but you can change it to append the id to each url instead of saving it in cookies.
ini_set('session.use_cookies', false);
in the config variable url_rewriter.tags, you see which URLs automatically get rewritten to append this id:
"a=href,area=href,frame=src,form=,fieldset="
As Pekka mentions, jQuery requests and special JS/Ajax/jQuery calls are not getting rewritten by default and you have to append the id manually like:
<script>
$.get('/yourpage/?PHPSESSID=<?php echo session_id(); ?>');
</script>
the session name can be obtained via session_name();, default is in the config variable: session.name.
Use ini_get(); or phpinfo(); to see your configuration.
Actually if you are using sessions you can use a cookie or a special GET/POST fields to identify yourself towards the server. The server then using the user id, passed either by GET/POST or a cookie - knows which data set is connected to the current user/client at server side. This way using sessions you can store data at server side with only sending a special user id to the client.
This way you can save login data for each user, thus login functionality can be implemented using sessions in PHP.
And yes, you can solve login with no other cookie just the Session user ID, or use the POST/GET session id.
Typically sessions are more reliable when working with keeping a user logged in. Sessions are stored on the server, whereas cookies are stored client sided. So that falls down to: do you want your login dependent on something the client can control and manipulate?
I've had first hand issues with logins being hacked with cookies, so I suggest sessions.
No, you do not need cookies in order to set up a login system, sessions suffice. However, if you seek a "Remember me" option, you need cookies in order to keep the user logged in beyond the point when the user closes the browser or the session expires.
http://www.php.net/manual/en/features.sessions.php
For maintaining a session with server, you need to identify yourself (your page) to server. So that server can keep track of your page's subsequent request and maintain a session.
So, if you only have username and password option on your login page, then cookies may not be required. Refer to the following link:
Passing the Session ID from page to Server
You can have a special URL which will have identifier as part of URL, which will inform server about your subsequent request.
However, please note that using this type of special URL is not always the recommended approach. Because this is insecure than cookie based session. For example, someone may paste their own link on a chat or in an email, and other person will be entered to your site without username/password.
You can do authentication without cookies (or sessions which are a special case of cookies) but it won't be on a page. This method is called HTTP Authentication.
In our current project, we implement persistent sessions by using cookies. When the user logs in a session hash is generated and sent via a user cookie. On every page load that is checked with the corresponding session entry in the database and the user is authenticated.
In the past if i had to do csrf token check, i would normally have assined a session variable for the particualar session. And on every subsequent ajax calls i would have matched the csrf token sent as a custom header in the ajax request, with the session variable.
However for the present project i cannot find a proper way to do this. A secure hash can be created and can be added as a custom header or as a hidden input field or even as a parameter in the ajax request. But how do i validate it on the client side ?
For the time being i am doing something like str_rot13(base64_encode(some_secret_key)) and sending it as the csrf token.
Then on the server side i am doing the reverse, obtaining the secret_key and matching it with the secret key that i have configured for my app. This however doesn't seem at all secure to me. I have thought of using openssl_random_pseudo_bytes(32) , openssl_random_pseudo_bytes(16) etc.. But again, thats a hash i would be generating. How would I validate it on the server side?!
What can be some best practices that i can adopt, given the user authentication mechanism that i am following?
I am trying to understand security when it comes to session cookies in php. I've been reading a lot about it, but I still lack the specifics. I need the basics, someone to show examples.
For example: Do I place session_regenerate_id() before every session cookie? What more shall I think about. I am asking about specifics in code - examples if possible.
Thank you very much.
I am using 4 session cookies after logging in.
SESSION "site_logged_in" = true
SESSION "site_user_nr" = the number of the user to access user_table_nr
SESSION "site_user_id" = the user's id to use when changing data in tables
SESSION "site_user_name" = the name of the user to display on page
When I check if the user has access, I check if all 4 cookies are set, and if site_logged_in is set to true.
Are there better ways? Do I have the completely wrong idea about this? Can users easily be hacked?
In fact you need to have only one session in your website. When you call session_start() session is being created on server and user automatically gets session cookie. Think like session is a some sort of container that placed on the server, you can put whatever you want in that container. However session cookie is just a key to access that container on the server.
It means that you can safely put some data in the $_SESSION and only the user that have cookie with matching session id can read it.
About users being hacked. Yes they can be hacked as long as you don't use HTTPS connection, because cookies and all other data is being transferred in clear text, so if someone intercept users cookie he can access the data stored in the session.
Always use a security token for logging users. This security token could be generated by using crypt(). After logging users in, change the security token periodically until they log out. Also keep the server backup of all the session variables including the security token (in a database). This would also help you to track user login history.
One more personal suggestion: Never use any data from the database as session variables without encrypting it with any of the hashing functions or functions like crypt().
The session information is stored server-side. What you should check is that they're logged in, and that they exists/can log in (in case of deletions/bans).
As you're checking they exist/can log in, you can pull the other information from the database such as name, nr and so on. All you really need is a key called 'logged_in_user' or something that stores the ID of the logged in user. As Alex Amiryan said, the cookie can be copied, so you might also want to store the IP address of the last accessing view in the session, so you can try to ensure security.
I have designed a website which uses AJAX. I have a PHP page named store.php which accepts data sent by POST method and stores in the database.
How do I implement authentication into store.php? I only want a user logged into my site to use store.php.
Currently I am using htaccess to redirect the requests for store.php but I don't think that is a good solution.
Any AJAX Call to a Server Script will still include the session id in the request. If you are implementing sessions in your site, then start the session and you will be able to see session variables for the currently logged in user.
Store a token associated with the user in your database. Make sure that the token will be unique and not guessable. Also store the same token in a hidden form field so that it gets posted back to the page. Ensure on the server that the token is present in the posted form values and check that it is valid.
The security of Ajax requests is not a simple matter. They can be susceptible to man-in-the-middle attacks and replay attacks, to name a few. I'd recommend reading this book: http://www.amazon.com/Ajax-Security-Billy-Hoffman/dp/0321491939. It will give you lots of good information on the subject.
As for your question, specifically: once your PHP session has been set up, those session cookies will apply to Ajax requests as well.
What you are looking for is a persistent state for the user. The best way to implement this in PHP is to utilize sessions.
There is great documentation on it: http://www.php.net/manual/en/book.session.php
I normally just include the exact same code I use to authenticate on the rest of my site in the ajax-called page. I use SESSION to hold a sessionID, and the rest is handled in my DB. I usually end up just adding a line like this..
require_once('loginProcedures.php');
//Login Authentication takes place here using SESSION ID
if (!$me['validLogin']) die("Invalid Authentication");
//perform actions and echo your result for a valid login.