Check/Validate and reuse CodeIgniter session - php

I have a website for my website with 20 api calls (REST). for every call the user/pass input is required.
The API calls can be made from C++, Python, PHP, Java, ASP etc...
the issue I have now is it creates tons of sessions. I want to change this to allow all calls to re-use the session id assigned.
so the first call will be to "authenticate", this return a token (encrypted session id)
then I decrypt this token and check if the session id exists in the database. If it does, i want to load or assign this session
I found a pge from ellislab explaining session but it does not help me since this page creates new session.
example:
call #1: authenticate(user,password)
call #2: get_report(token, 1) // get report id 1
call #3: add_user(token, [array of user data])
How can i reuse the session in codeigniter?

You just need to save the token in session if not exist.
1) Get the token form your request like username I think user name is unique for you.
2)
$this->load->library('session');
$user_data = $this->session->userdata('$username');
if(!empty($user_data)){
//use the same session
}else{
$this->session->set_userdata('$username', 'isvalid');
}

Related

Set one session per user in laravel

I ned to set a session per every user, so when the user log ou from his account and login again in another account the old session will not be shown but the new that related to his new account will be shown
I am using the normal method in laravel to do it
Session::put('key', 'value');
But the problem as explained is that the session will br shown in all user using this computer
Session ids are supposed to be non-guessable. You're going to have to resolve (attempted) duplicates serverside. If you search through every existing session for a match then your not going to be able to scale this / its going to be very slow. That means you need an access path to the session data based on the username AS WELL AS the session id.
There are lots of solutions to this. I don't think any of them are exposed directly in Laravel.
You need to deal with maintaining the mapping directly in the session management - so you will need a custom session handler. The session handler deals with serialized data - so you need to think about how the username is resolved within the session handler. You could put it in the session and deserialize the data again the handler, or read the value from a global variable. Or you could write a prototytype of the session into a database with the sessionid as the primary key and the username as an indexed lookup before the session close handler is called.
Another approach would be to store the session as the username rather than using the session id. You still need to protect the username though and avoid session fixation, hence you would need to explicity generate the session id using a mechansim where only you can recover the username from it, e.g.
$data=array($username, openssl_random_pseudo_bytes(16));
$sessionid = encrypt(serialize($data), $your_secret_key);
(You still need to write your own session handler for this).

Using a php application session into another codeigniter application

I am using a existing php application which has different interfaces like admin, agent and customer.
I have created a new agent interface using codeignitor. FOr login into agent portal, I am using the existing agent login page from old application but after login is successful my new agent interface is supposed to be loaded.
In the old application, there are sessions used and the agent_id is stored in the session variable.
when I am trying to use this session variable in my new code, I get an error message ...variable can't be found. How can I use the session variable from my first application into my new interface?
when I print the session name in my first application and in one of new codeignitor code page,, I can see both the sessions are different. I think this is the problem because codeignitor manages its session.
I searched on the google and came to know about the sessions settings save path and all, I am not sure what exactly I need to do here to resolve this.
Remember both projects/applications should exist on the same server
By default codeignitor follows the COOKIE's as a session so you have to ovwerwrite that library with any of the PHP native session libraries.
Then pass the session_id to that project through CRUL or POST or URL in a two way encrypted format. Don't forget to encrypt the session id
From Project 1 :
//to get the session id
$id = session_id();
//do some custom encryption
$id = 'ajhkdhfasjdhfajsdfhkjadf';
**Ref:**
http://www.php.net/manual/en/function.mcrypt-encrypt.php
From Project 2:
Ref:
http://www.php.net/manual/en/function.mcrypt-decrypt.php
The initialize the session id before start the session like below
//do some custom encryption
$id = $this->input->get('id');
//decrypt the value
session_id($id);
session_start();
Now you can access the session values.
when I print the session name in my first application and in one of
new codeignitor code page,, I can see both the sessions are different.
I think this is the problem because codeignitor manages its session.
You are correct about CI handling its own sessions, the way around this issue is to use the native session library.
https://github.com/EllisLab/CodeIgniter/wiki/Native-session
The other way is to make CI use database sessions and just pass the session ID to your new application so you can select the correct data from the database.

PHP session variables and GET request

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.

How to validate user session on every page

I'm working on this project in Codeigniter and i created login and register script but I don't know how to validate user on every page.
When user logs in what data to store in session (Ci session user_data), so i can compare it to database on every page to se if the session is valid?
I'm using codeigniter's session class and I'm storing the values automatically in the database. Please help me I'm stuck here...
My session is handled like this :
1. When ever any user reaches my webpage he gets unique hashed (md5) session id that is checked when ever a page is loaded. If it exists do nothing if it doesn't generate a new one. It changes every 5 minutes.
2. When user logs in what data to pass to so i can compare it to the database later on ( on every page load)
I don't know if storing only the 'is_logged' = 1 cookie is safe. I want to check cookies on every server request.
Upon succesful login, you create a
$this->session->set_userdata(array('authorized' => true));
You can then make an auth library, or a model method, whatever suits you that just checks if this session data exists.
function is_logged()
{
return (bool)$this->session->userdata('authorized');
}
if FALSE, user is not logged, if TRUE it is. You can call this function on every controller's method you need to place behind authentication, or in controllr's constructor if you need it for all methods (ex. an admin panel)
have a look, for ex., on how Ion Auth, one of the mainstream Auth Libraries in CI, handles the thing (uses the logged_in() method which does the same as in my example code. Keep in mind that sessions are encrypted, and if stored in database security is even higher);
https://github.com/benedmunds/CodeIgniter-Ion-Auth/blob/2/libraries/Ion_auth.php
Sessions are stored on the server so no validation is required. You only need to validate what you put in the session.
Sessions are authenticated by the user supplying a session_id cookie (PHPSESSID).
Cookies on the other do require validation, but cookies shouldn't be used to store critical data so it's a bit moot.
You should have write a function in helper like session_helper.And in constructor of your class call this helper method.If your user is logged in correctly then it will continue,other wise it will redirect to log in page.Your Helper should be like this
function session_set()
{
$ch=&get_instance();
if($ch->session->userdata('your_session_id')=='')
{
redirect('your_login_page');
}
and in controller you should check like this(constructor)
session_set();
Hope this will work for you

Are sessions modifiable by the client/user?

In my PHP Web-App I use sessions to store the user's data. For exmaple, if a user logs in, then an instance of the User class is generated and stored in a Session.
I have access levels associated with each user to determine their privileges.
Store the user in a session by:
$_SESSION['currentUser'] = new User($_POST['username']);
For example:
if($_SESSION['currentUser'] -> getAccessLevel() == 1)
{
//allow administration functions
}
where getAccessLevel() is simply a get method in the User class that returns the _accesslevel member variable.
Is this secure? Or can the client somehow modify their access level through session manipulation of some sort?
No, the client cannot modify their access level. The only thing stored on the client is the session key which is either propagated via cookie or GET parameter. The session key ties to a corresponding session record which is a file stored on the server side (usually in a temp directory) which contains the 'punch'.
What you don't want, is for a session key to get leaked to a third party:
A leaked session id enables the third
party to access all resources which
are associated with a specific id.
Take a look at this: http://www.php.net/manual/en/session.security.php
The session information is stored on the server and the user only has access to a key. In practice I have used something of this sort, with extra steps. After validating the user details and storing the User object, I would have a query that is run when viewing any of your protected pages to validate what is in the session is okay with what they're trying to view.
In the top of your page.php
if(!validUser($user)){
// Relocate the user
}
where
validUser(User $user)
{
// Some query to verify the information in the session
// Return the results of verification
}
I thought the only way for the user to manipulate something like that was if it was stored in a cookie on the users computer.
Is the getaccesslevel stored to a cookie or is it called from the server only after checking the login cookie and not stored on the users computer?
I would assume that if it is called on the server only after the user is logged in then they would not be able to easily manipulate that other than through other means of security holes.
Just my guess tho, im not that great with security myself yet. I will keep an eye on this to see what others have to say and maybe I can learn something.

Categories