I am quite new to wordpress and OAuth. I have two sites. One hosted on the web,and the second one hosted on my local machine. I want to use OAuth in order to login to my local machine site if i am logged in to the other site.
What i managed to do:
I had installed WP OAuth Server on web hosted site and created new client;
On my local machine i wrote the following code using https://github.com/adoy/PHP-OAuth2;
require('vendor/autoload.php');
const CLIENT_ID = 'my client id';
const CLIENT_SECRET = 'my client secret';
const REDIRECT_URI = '';
const AUTHORIZATION_ENDPOINT = '';
const TOKEN_ENDPOINT = '';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
$response = (object) $response;
$result = (object) $response->result;
//echo json_encode($result->access_token);
echo "<pre>";
print_r($response);
}
When i run this script i got the following response:
stdClass Object
(
[result] => Array
(
[access_token] => rhfnpz6ifgnjufoq0rby0utphtzpxhrmsytnjh5z
[expires_in] => 86400
[token_type] => Bearer
[scope] => basic
[refresh_token] => lgrklt5kwiv29ch3nmdhhieedjbudg8liv48l6c7
)
[code] => 200
[content_type] => application/json
)
How can i use this access token in order to login to my local hosted site? What i am missing? Thank you!
After you have a response with the access_token you can log the user in without having to accept and process the normal WP email+password flow. Do this by
session the access_token and refresh_token (for future calls to the API Resource endpoint, if any)
call wp_set_auth_cookie() to create a WP session for the user.
You'll want to include in your code a hook for the WP logout where you'll clear the tokens from the session.
OAuth2 Server
Your web-hosted WordPress website needs an OAuth2 server plugin. This is our premium product: https://lana.codes/product/lana-passport/
The OAuth2 server plugin provides the authentication server that is connected to the WordPress user system. It also provides the /authorize, /token and /resource endpoints, to which the client can connect and generate a token, and then use the token to access user data.
Basically, the Authorization Code grant type should be used for this purpose, because it also provides the WordPress login interface if you are not logged in and need to identify yourself. This is the most user-friendly and most popular grant type.
OAuth2 Client
And your local machine-hosted WordPress website needs an OAuth2 client. This is our free product: https://wordpress.org/plugins/lana-sso/
This creates a Single Sign On button for the WordPress login interface, which is connected to the configured OAuth2 server.
How does it work:
If the client went through the authentication process and received the access_token, it requests the user data from the OAuth server at the /resource endpoint.
If the user can be found on the client website based on the user data, the user is logged in using the wp_set_current_user() and wp_set_auth_cookie() functions. If the user is not found and registration is enabled, a new user is created using the wp_insert_user() function on the client website and logged in.
If you want to know more about the OAuth2 process, we have a case study that specifically discusses the single sign on solution for two WordPress websites: https://lana.codes/case-study/oauth2-server-and-client-wordpress-plugin/
Related
I am Using OAuth2 of PingFedarate I am able to successfully log in. Now is the question of how to call the API to log out and what is the parameter for that? Below is the example code I am using for revoke using curl request.
When I run the revoke script, it deletes the access_token and shows that the configuration failed.
But when I run my OAuth2 main script for login it automatically gets logged in: a new token is generated. In the below code refresh code when I revoke the token, I should get my login page to enter the login credentials again but it is not happening.
$objectData=array();$curl=curl_init();define('OAUTH2_TOKEN_URL','https://abcd.com/as/revoke_token.oauth2?');define('OAUTH2_CLIENT_ID', 'abcd');define('OAUTH2_ACCESS_TOKEN', 'hfefhhjfhj');define('OAUTH2_ACCESS_TOKEN_HINT_TYPE','refresh_token');define('OAUTH2_CLIENT_SECRET','bhfbfhjbhjbjbnvjevfbrfhrefbjebf');define('OAUTH2_REDIRECT_URI', 'https://www.abcde.com/Oauth/PingRedirect.php');define('OAUTH2_GRANT_TYPE', 'authorization_code');
$params = array(CURLOPT_URL => OAUTH2_TOKEN_URL."client_id=".OAUTH2_CLIENT_ID."&token=".OAUTH2_ACCESS_TOKEN."&token_type_hint=".OAUTH2_ACCESS_TOKEN_HINT_TYPE."&client_secret=".OAUTH2_CLIENT_SECRET."&redirect_uri=".OAUTH2_REDIRECT_URI,CURLOPT_RETURNTRANSFER => true,CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT => 30,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "POST",CURLOPT_NOBODY => false,CURLOPT_HTTPHEADER => array("cache-control: no-cache","content-type: application/x-www-form-urlencod",accept: *","accept-encoding: gzip, deflate",),);curl_setopt_array($curl, $params);$response = curl_exec($curl);$objectData=json_decode($response);
For logout with OAuth use cases, you should be considering SLO or the session revocation features. Access Token and Refresh Token revocation itself does not affect existing web sessions. You could also rely on Authentication Sessions and their validity to affect Access Token validation.
More details on some of the options available are here:
https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=vrl1564002994868.html
https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=pmr1564002990528.html
I'm having a problem connecting through the google apiclient 2.0.0 as installed via composer.
Here's what I've done so far:
I installed apiclient via composer.
I went to https://console.cloud.google.com/apis/credentials?my-project and navigated to the API manager > Credentials page.
I created credentials for a Service Account and downloaded the json. I then uploaded the json to my server.
I enabled Domain Wide Delegation for the account by managing my service accounts.
I verified my domain name under the 'Domain Verification' tab.
Next I navigated to my calendar and shared the calendar with the email address associated with my service account, granting manage access.
Then I shared my calendar with the email address of the service account.
Now I'm trying to use the api to connect and running into authorization problems.
$json_file = '/path/to/service-account-credentials.json';
$scopes = [
Google_Service_Calendar::CALENDAR,
Google_Service_Calendar::CALENDAR_READONLY
];
// create a new client and authorize
$client = new Google_Client();
// set the basic information of the client
$client->setApplicationName("Apointments");
$client->setSubject( email-address-to-masquerade-as#mycompany.com );
$client->setAccessType('offline');
// load the json credential file
$client->setAuthConfig( $json_file );
$client->setScopes( $scopes );
// check to see if the token is stored in the session
if( isset( $_SESSION['service_token'] ) )
{
// token was stored, use it with the cilent
$client->setAccessToken( $_SESSION['service_token'] );
}
// test the authorization to see if it is expired
if( $client->isAccessTokenExpired() )
{
// Failed authorization, get a new token
$client->refreshTokenWithAssertion();
}
// store the token in the session
$_SESSION['service_token'] = $client->getAccessToken();
From a stacktrace, I've identified the offending line of code to be:
$client->refreshTokenWithAssertion();
Which yields an error message:
Client error response [url] https://www.googleapis.com/oauth2/v4/token [status code] 401 [reason phrase] Unauthorized
Any thoughts as to where I've gone awry?
Thanks in advance,
Adam
The way you are using Service account is only valid to access data related to your application or to your service account itself. Since you wish to access Google Calendar data, you must be a Google Apps domain administrator with privileges to access any of your domain user's data. Google Calendar data belong to users so you need to specify which user you are trying to access.
You need to authenticate the user, need to get an access token and pass that. If you are getting an access token, you can call token info passing access token to get more information about who the user is associated with it.
Here's a Quick start demo app, use this as your reference: https://developers.google.com/+/web/samples/php
I'm using Twitter API with CodeBird (PHP).
Here is a quote from Twitter's docs:
so for users already signed in to twitter.com who have authorized the application, no UI is shown - instead, they are automatically redirected back to the application.
In the case where the user is already signed in to twitter.com and has granted access to the website, this redirect happens immediately.
https://dev.twitter.com/web/sign-in/desktop-browser
Why this does not work for me? Twitter asks user's permission for each time.
My code for obtaining authorization URL:
\Codebird\Codebird::setConsumerKey(
$this->config['twitter']['consumer_key'],
$this->config['twitter']['consumer_secret']
);
$cb = \Codebird\Codebird::getInstance();
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'https://***/login/twitter'
]);
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$this->session->twitter_oauth_token = $reply->oauth_token;
$this->session->twitter_oauth_token_secret = $reply->oauth_token_secret;
$this->session->twitter_oauth_verify = true;
return $this->redirect($cb->oauth_authorize());
Solved!
oauth_authorize will always ask user for a permission.
oauth_authenticate will request it only once and will perform automatic redirect, if access already granted.
My situation is the following.
I am the owner of a facebook app,and a facebook page.I would like to programatically(from code) post to this facebook page.
As far as I know I need a facebook app to do that so I created one.
I am using the facebook php sdk and code igniter.(I am not using the javascript sdk).
I have the facebook object.I printed it's methods and tried printint the user id while I was logged into facebook.
This did not work.
My questions are the following:
1)Why does it not work to print the facebook id?
2)What is the most simplest solution to programatically post to my facebook page ?(from my app,or from my user)
What am I doing wrong ?
This is my code
$config = array(
'appId' => 'xxxx',
'secret' => 'xxxx',
'cookie' => true,
);
$this->load->library('facebook', $config);
echo '<pre>';print_r(get_class_methods($this->facebook));
$id = $this->facebook->getAppId();
$secret =$this->facebook->getApiSecret();
$uri = "http://tipsterscorner.com/stats/display/facebook1";//callback_url se pare ca nu e bun
//i build the facebook url.If I use this in the browser ,I get a series of popups(do you allow the application to blabla)
//I read somewhere that if I change the last parametere to code,and use curl,I will get the token in the response
//printed on the screen of the return url,but that does not happen
$facebook_url = "https://www.facebook.com/dialog/oauth?`client_id=$id&client_secret=$secret&redirect_uri=$uri&scope=publish_stream,offline_access,read_stream,manage_pages&response_type=token";`
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $facebook_url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
This is the url.
http://tipsterscorner.com/stats/display/facebook1
Thank you very much.
To post on facebook by yourself and on behalf of other's using the app you need to obtain user access token. There are two kinds of Access Tokens namely App Access Token and User Access Token. When app is posting on user's behalf User Access Token is required. User Access Token is generated when a User gives permissions for the app(The dialog popup which you experienced when entering the facebook url in browser). Its solely upon user whether or not to grant permission to the app to post on their behalf. App should be developed to handle both the situations. Once User have given permission(Basic Permission which includes all publicly available info of the user), user access token will be generated. You can either store it in database table or in SESSION. Sometimes user access tokens may become invalid and new token has to be retrieved. During that time curl can be used to retrieve because user has already granted permission for the app.
http://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
We have our PHP application that requires authentication, and for our clients that run SharePoint we'd like to offer some kind of SSO service, so that the users can use their SharePoint credentials (we did something similar with Google Apps, CAS, ...)
Note: Obviously, our app is not hosted on the same domain/premices as SharePoint
I can't find the litterature about it, so any pointer would be welcome !
NB: we'd like to implement a proper tier authentification mechanism, so that the user can log into our app directly by typing the URL, and choose to login using SharePoint, exactly like you'd do with OAuth and the like...
Thanks in advance !
SharePoint Online (SPO) supports claims based authentication.
The below picture demonstrates how authentication is performed in SPO:
According to this post the authentication process consists of the following steps:
Steps:
Send SAML Request to STS
Receive SAML Response
Send the Security Token to SharePoint Online
Receive the authentication cookies
Send requests including authentication cookies
phpSPO - SharePoint client for PHP supports SPO authentication.
The library provides a SharePoint Online (SPO) client for PHP
applications. It allows you to performs CRUD operations on SharePoint
data using an SharePoint 2013 REST/OData based API.
Examples
How to perform authentication in SharePoint Online (SPO):
try {
$client = new SPOClient($url);
$client->signIn($username,$password);
echo 'You have authenticated successfully\n';
}
catch (Exception $e) {
echo 'Authentication failed: ', $e->getMessage(), "\n";
}
The following examples demonstrates how to perform CRUD operations on SharePoint list data:
<?php
require_once 'SPOClient.php';
$username = 'username#tenant.onmicrosoft.com';
$password = 'password';
$url = "https://tenant.sharepoint.com/";
$client = new SPOClient($url);
$client->signIn($username,$password);
//Get Tasks list
$listTitle = 'Tasks';
$list = $client->getList($listTitle);
//Create a Task item
$itemProperties = array('Title' => 'Order Approval', 'Body' => 'Order approval task');
$taskItem = $list->addItem($itemProperties);
print "Task '{$taskItem->Title}' has been created succesfully.\r\n";
$itemId = $taskItem->Id;
//Update a Task item
$itemProperties = array('PercentComplete' => 1);
$list->updateItem($itemId,$itemProperties);
//Delete a Task item
$list->deleteItem($itemId);
?>
References
SharePoint Online client for PHP
Not sure if you still need help on this - Sharepoint is usually set to sync up with Active directory (AD/LDAP). So really if you have users that use sharepoint AND are being internally authenticated in their company via their Active directory login, then what you may want to look at is authenticating your app against LDAP (and use the email address or domain id as the username)
Here is some more info on that:
Authenticating in PHP using LDAP through Active Directory