I am working on a WordPress plugin and I have a problem where I get the WordPress logged-in users id & session and i need to create a comment on this user's behalf from my server.
[Update] What I mean by "my server" is from my own Java server. My comment system creates the comments on the Java server and the Java server needs also to create the same comment on the wordpress PHP server. In order to create the comment on the user account i am sending the session to the Java server so it will as the wordpress to convert the session to the user, so it will be secure.
[/update]
The problem is that in order to make this operation secure i need to check with WordPress that the session i got is valid and matches the user id.
I couldn't find any API that convert the session into the user id in order to check that it matches.
anyway to do that with WordPress API?
There are a number of ways you can get the user id from the auth cookie, depending on the path you want to take this are the functions you should check:
get_current_user_id ->Returns the ID of the current user.
wp_get_current_user ->Retrieve the current user object (WP_User).
Wrapper of get_currentuserinfo() using the global variable $current_user. You can check the code of this function here to have an ideea how you can build your script.
wp_validate_auth_cookie -Validates authentication cookie. It returns the user id.
I'm thinking you'll have to use the last one like it is used in get_currentuserinfo:
$user = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' )
if ($user != 0) { //then we have a valid user...}
Related
I have hosted 2 website, these two website use same database to populate data. eg: users - table
has user login details, both website users can access their login via this table.
Now I want to do this:
Before access both website they need to login.
My "Website A" has link call "Read More" when user click on it, that user
should be redirect to "Website B". Now I want to skip "Login" process from B website(because that user
already loged in A). How to do that,
I got mind this option, but less security:
A website read more link as
B_website/?username=abc&password=123&page=12
I guess this is not good option, what are the ways i can do this with keep high security?
No no no - do not pass the username + password in plain text in the URL!
I would recommend taking a look at how you know that the user is logged in on site A. Is there some sort of flag in your database marking this user as logged in? Could site B somehow be aware of this flag? Since your two sites share a database, this would definitely be possible.
Consider the following scenario:
User logs into site A.
A unique "login token" is generated, saved in your database and also sent to the client.
User arrives at site B.
The user sends the "login token" they previously recieved to the server.
If the login token sent by the user matches the record in the database you can skip the authentication phase and mark that user as logged into site B.
Server sessions are basically hand-designed to solve this problem. If your websites already access the same database you can utilize a PHP built-in feature, which is to create a session_handler that opens a database connection and stores your session in a database table.
I am personally a big fan of Symfony's HttpFoundation (see below). However, you can do this natively without relying on any outside libraries.
Start by creating a table (this is a MySQL table, but it should be pretty easy to adapt this:
CREATE TABLE sessions (
sess_id VARBINARY(128) NOT NULL,
data BLOB NOT NULL,
sess_expires int(11) UNSIGNED NOT NULL
) COLLATE utf8_bin, Engine=InnoDB;
Next, create a session handler session_set_save_handler(), as per PHP Documentation. Create callable functions, and assign each function like so:
Open
Create the database connection.
Close
Closes the database connection.
Read
Retrieves session from the database.
Write
Stores session in the database.
Destroy
Destroys the session.
Clean
Cleans old session data based on your system settings.
Here are some different implementations. They all should work so whichever one you find most attractive can be used as a base. Once you settle on your style, you simply copy the code in each of your client sites and it will pull a shared session!
A tutorial by Chris Shiflett is probably the most basic and accessible if you are unfamiliar with much of how this sort of thing would work.
DevShed has an object oriented approach which can probably be copied and pasted for the most part. They also do a good job explaining how to use the session in other places.
HttpFoundation - Uses locking and other mechanisms and is pretty much get-up-and-go. If you follow object oriented programming and are familiar or interested in Composer, this is an absolute breeze to get set up.
If you store the login via PHP builtin sessions and both websites use the same session_save_path, then this is quite simple to achieve. Just Pass the session id as parameter SID inside the URL. The session from Website A should then be picked up by Website B and as the user Base is shared, the session can just continue on the other website.
The read more link should be generated something like this:
Read more...
If you manually store some kind of sessionID in a cookie, you have different options. Either you always set the cookies for the domains of both websites when logging in. Like this the user is autamatically logged in on both websites, no matter on which of the two he logged in.
setcookie("SESSIONID", $session_id, time() + 86400, "/", $domain_A);
setcookie("SESSIONID", $session_id, time() + 86400, "/", $domain_B);
Another way would be to make the more link on Website A point to a special page on Website A which would then set the necessary cookie to be logged in on Website B and then do a Redirect (via 302 Header) to Website B. The link would look like:
A_website/redirect_B.php?page=12
redirect_B.php would do the work then:
setcookie("SESSIONID", $session_id, time() + 86400, "/", $domain_B);
header("Location: B_website/?page=12", true, 302);
The best method to pass the session to the other server depends on how you implemented the login. With more details about how you manage the login sessions, it would be possible to give a more precise answer.
The most secure way is to use Single Sign On through SAML.
You should use token based security i.e. when user enters his credentials in website A then website A returns a access-token,then by using this token you can validate user on both websites i.e. send access-token with every request.
This is basically how social-site login works,they also provide access-token and this is called auth protocol.
You can send through AJAX authentication data from the website "A" to the web "B" when you click on the "Read more" button: after it, you check if these data are correct. If so redirect to the page "B" (You could do this through an ajax response)
$.ajax({
type: 'post',
url: 'b.php',
data: userauth,
error: function(errors) {
console.error(errors);
},
complete: function(data) {
if(data=="correct"){ /*redirect*/ }else{ /*nothing*/ }
}
});
I think that would be an option...
¡Regards!
Best way that i would suggesgt:
1: Every time user logs in a seesion id is generated
now user below table structure
uname | password | seesion id | user ip address |isloogenid
a pwd1 sessionidcreated user looged in ip
is all paramerts are same login in user otherwise no
$seesionifdromdb
$ipfromdb
$userloggedinfromdb
$currentipwheresiteisopened
$valeofphpsessionif
if(($seesionifdromdb == $valeofphpsessionif) && ($ipfromdb == $currentipwheresiteisopened) && ($userloggedinfromdb==1)){
// here start session neede to make user logged in
}
As per your situation lets have a logical view.
sites:"Website A","website B"
Let have the general login flow If a user login to a "Website A" or "Website B",then a session will be created for that user with some session Id and some custom session variables that you will set-up to keep the user logged in to throughout the website
eg: $_SESSION['user_id'] = {some id from database};
$_SESSION['prefered_language_code']='eng';
$_SESSION['user_name'] = 'abc';
Then you are checking biapasing the login process till these variables are available in the session
eg:function checkSession(){
if($_SESSION['user_id']!=''){
return true;}
else{return false;}
}
on the other pages of both website
if(checkSession()){
return true;
}else{
//send to login page of website A or Website B respectively;
}
Something like this function you are using to check the user access for the rest of the web pages.when he log's out then you must be destroying that session variable.
So now the answer to your question is:
1)As you are managing two website and as per your comment i.e "Now I want to skip "Login" process from B website(because that user already loged in A)" it means in both the case login credentials for the user should be same.Now the solution is to achieve desired situation you should follow the same login process with same session variables (only those which are used to check login status of the user) and login checkin in both the website i.e "website A and Website B".
Then they seems to be two different websites but logically the work as single one as they are sharing the login session variable.It means if a user login in to one site then logically he is by passing the login process of other website.
2)You can set some login track field type in database to keep the track of user login
eg:loggin_token; comment some uniquely generated key or login_key
and sets these with some session variable
Now you can check the session for the session variable to keep a login check on both sites
Hope this will help as it is the most simple way to manage these
Ignore any advice sending the password.
Lix' answer with the one time token is a valid approach. If you don't want to bother with an implementation you might be interested in existing single sign-on implementations.
You must use techniques like SAML or Open ID for this.
https://github.com/onelogin/php-saml
https://github.com/openid/php-openid
I am working on a group project where my group member is working on the user part while I am working in the post ads, view ads i.e. other parts of the project. I want to create fake users which will determine the admin and user through the session . Is there a way to do this? Thank you very much.
It depends on how you are going to detect if a user is signed in, I usually create a couple of sessions depending on the results of a SQL request. If you are going down this route, you can temporarily add these sessions to the top of your files, like so:
$_SESSION['user'] = 'admin';
You can then use these session later in your code to make sure the user is signed in and to get their username ect.
I developed a small application Contact Manager and while updating the contacts, the contact id is being sent using GET method. But a user can change the Id and edit any contact, how can i add security to it?
<td>
Update
</td>
http://localhost/contmanager/home.php?action=update&contactid=1
If i change the id to some other number, another contact will show up.
You can't control what the client asks the server to do.
If you want to add restrictions on who can modify particular contacts then you need to Authenticate (username + password, client SSL cert, OpenID, etc) users and then check if they are Authorized (this will depend on the business logic you decide on) to modify the entry in question.
As Quentin pointed out, your logic is going wrong here, data like these should be stored inside sessions and shouldn't be passed using $_GET or $_POST, unless and until required, if you still need to pass for some reason, than you can read my answer ahead for a solution.
Store the user id in a session, so when the user updates, just compare the session id and $_GET id, if it matches, update the entry else throw an error.
When the user logs in
$_SESSION['user_id'] = $db_data['col_name'];
Now, before the entry is updated...
if(!empty($_GET['user_id'])) {
//First validate, you can check whether the id is only numeric, is valid db entry etc
$user_id = $_GET['user_id']; //Store the id in a variable
} else {
//Invalid
}
if($_SESSION['user_id'] == $user_id) { //Compare the ids
//Process
} else {
//Not Valid
}
Note: Make sure you use session_start() at the very top of the page,
before you start writing anything.
You need to use session and to store the data inside like this:
<?php
session_start();
$_SESSION['contact_id']=$contact->contact_id;
<td>Update</td>
?>
use it like this:
http://localhost/contmanager/home.php?action=update
and when you need to use contact_id(after the GET) :
session_start();
if(isset($_SESSION['contact_id']) && !empty($_SESSION['contact_id'])){
$contact_id=$_SESSION['contact_id'];
}
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
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.
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.