I've tried both of these libraries for the Oauth 2.0 process:
1) https://github.com/thephpleague/oauth2-client
2) https://github.com/tpavlek/oauth2-bnet
But I haven't really made either of them work. I'm fairly new to Laravel but I want to use this framework for this project.
Here's the code I've been working on:
Routes
Route::get('oAuth/authRequest', 'CommunityOAuthProfile#authRequest');
Route::get('oAuth/authCode', 'CommunityOAuthProfile#authCode');
Controllers(CommunityOAuthProfile.php)
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use OAuth;
class CommunityOAuthProfile extends Controller
{
public function authRequest()
{
$provider = new \Depotwarehouse\OAuth2\Client\Provider\WowProvider([
'clientId' => <client_id>, // The client ID assigned to you by the provider
'clientSecret' => <client_secret>, // The client password assigned to you by the provider
'redirectUri' => 'https://sc2data.com/oAuth/authCode',
]);
if (!isset($_GET['code']))
{
$authorizationUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authorizationUrl);
exit;
}
elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else
{
try
{
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
$user = $this->provider->getResourceOwner($token);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
// echo $accessToken->getToken() . "\n";
// echo $accessToken->getRefreshToken() . "\n";
// echo $accessToken->getExpires() . "\n";
// echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// // Using the access token, we may look up details about the
// // resource owner.
// $resourceOwner = $provider->getResourceOwner($accessToken);
// var_export($resourceOwner->toArray());
// // The provider provides a way to get an authenticated API request for
// // the service, using the access token; it returns an object conforming
// // to Psr\Http\Message\RequestInterface.
// $request = $provider->getAuthenticatedRequest(
// 'GET',
// 'http://brentertainment.com/oauth2/lockdin/resource',
// $accessToken
// );
}
catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e)
{
exit($e->getMessage());
}
}
}
public function authCode()
{
$provider = new \Depotwarehouse\OAuth2\Client\Provider\WowProvider([
'clientId' => <client_id>, // The client ID assigned to you by the provider
'clientSecret' => <client_secret>, // The client password assigned to you by the provider
'redirectUri' => 'https://sc2data.com/oAuth/authCode',
]);
try
{
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
$user = $this->provider->getResourceOwner($token);
}
catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e)
{
exit($e->getMessage());
}
}
}
By the way, is there any recommended oauth2 library for php? So far, these 2 are the most promising I've seen but there may be others I'm not aware of?
Related
Using Google APIs, I would have liked to retrieve the list of channels for which I am subscribed from my Youtube account. For that I used the following PHP library: https://packagist.org/packages/league/oauth2-client. After applying all the necessary information I get the following error: Fatal error: Uncaught UnexpectedValueException: Invalid response received from Authorization Server. Expected JSON ....
Here is my code:
<?php
require 'vendor/autoload.php';
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => 'my_oauth_client_id', // The client ID assigned to you by the provider
'clientSecret' => 'my_oauth_client_secret', // The client password assigned to you by the provider
'redirectUri' => 'http://localhost/oauthytb/index.php',
'urlAuthorize' => 'https://accounts.google.com/o/oauth2/v2/auth',
'urlAccessToken' => 'https://oauth2.googleapis.com/token',
'urlResourceOwnerDetails' => 'https://www.googleapis.com/auth/youtube.readonly'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
$options = [
'scope' => ['https://www.googleapis.com/auth/youtube.readonly']
];
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl($options);
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'https://www.googleapis.com/youtube/v3/subscriptions',
$accessToken
);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
?>
Thank you in advance for your help
I finally solved the problem.
I replaced :
'urlResourceOwnerDetails' => 'https://www.googleapis.com/auth/youtube.readonly'
By :
'urlResourceOwnerDetails' => 'https://www.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&mine=true&key=AIzaSyDay5KNU_TPCD-s_n7t6XqqrHYumUtjytI'
I am trying to consume Zoom's API using PHP and Oauth2. I was able to connect to the aplication and get the token using the generic lib oauth2-client. But, when I try to make a simple request, I get an error, saying that the email is missing. This is my code:
<?php
session_start();
require __DIR__ . '/vendor/autoload.php';
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => 'meuclientid',
'clientSecret' => 'meuclientsecret',
'redirectUri' => 'http://localhost/teste_oauth2/',
'urlAuthorize' => 'https://zoom.us/oauth/authorize',
'urlAccessToken' => 'https://zoom.us/oauth/token',
'urlResourceOwnerDetails' => 'https://api.zoom.us/v2/users/me'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
}
elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.zoom.us/v2/users/email',
$accessToken,
['email' => 'meuemail#gmail.com']
);
var_dump($provider->getResponse($request));
die('aqui');
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
echo $e->getMessage();
exit;
}
}
?>
As you can see, I am passing the email on the request. But I am getting the Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://api.zoom.us/v2/users/email resulted in a 400 Bad Request response: {"code":300,"message":"Email is required."}
Can anyone help me?
You are using
['email' => 'meuemail#gmail.com']
which is not allowed in the function $provider->getAuthenticatedRequest
You need to pass it with the existing URL:
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.zoom.us/v2/users/email?email=meuemail#gmail.com',
$accessToken
);
I hope this helps..!!
Zoom API Reference: https://marketplace.zoom.us/docs/api-reference/zoom-api/users/useremail
OAuth Reference: https://github.com/thephpleague/oauth2-client
I'm trying to use djchen's Fitbit wrapper for thephpleague code to get Fitbit OAuth2 access for my website. It can be found here: https://github.com/djchen/oauth2-fitbit
This was working perfectly for a while and now suddenly, I'm getting "Forbidden" error. I can't remember changing any code on the login.php file. Any ideas as to why this would happen?
Here is my main code:
<?php namespace djchen\OAuth2\Client\Provider;
require __DIR__.'/vendor/autoload.php';
require __DIR__.'/vendor/oauth2-fitbit-master/src/Provider/Fitbit.php';
require __DIR__.'/vendor/oauth2-fitbit-master/src/Provider/FitbitUser.php';
use djchen\Oauth2\Client\Provider\Fitbit;
use djchen\Oauth2\Client\Provider\FitbitUser;
$provider = new Fitbit([
'clientId' => '****',
'clientSecret' => '****',
'redirectUri' => '****'
]);
ob_start();
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/var/php_sessions'));
session_start();
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
echo "going down this path \n";
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
echo $_SESSION['oauth2state'] . " is the oauth2state saved \n";
echo $_GET['state'] . " is the get_state \n";
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
echo "still going...";
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request1 = $provider->getAuthenticatedRequest(
Fitbit::METHOD_GET,
Fitbit::BASE_FITBIT_API_URL . '/1/user/-/profile.json',
$accessToken,
['headers' => [Fitbit::HEADER_ACCEPT_LANG => 'en_US'], [Fitbit::HEADER_ACCEPT_LOCALE => 'en_US']]
// Fitbit uses the Accept-Language for setting the unit system used
// and setting Accept-Locale will return a translated response if available.
// https://dev.fitbit.com/docs/basics/#localization
);
// Make the authenticated API request and get the parsed response.
$response1 = $provider->getParsedResponse($request1);
//eventually will set variables here...
$deviceSpecificID=$response1['user']['encodedId'];
$firstName=$response1['user']['firstName'];
$lastName=$response1['user']['lastName'];
//making repeat request to get more data
$request2 = $provider->getAuthenticatedRequest(
Fitbit::METHOD_GET,
Fitbit::BASE_FITBIT_API_URL . '/1/user/-/activities/date/2017-09-23.json',
$accessToken,
['headers' => [Fitbit::HEADER_ACCEPT_LANG => 'en_US'], [Fitbit::HEADER_ACCEPT_LOCALE => 'en_US']]);
$response2=$provider->getParsedResponse($request2);
$stepsToday=$response2['summary']['steps'];
$stepGoal=$response2['goals']['steps'];
$todaysDate=date("Y-m-d");
//add variables to the session
$_SESSION['loggedin']=True;
$_SESSION['device']="fitbit";
$_SESSION['deviceSpecificID']=$deviceSpecificID;
$_SESSION['firstName'] = $firstName;
$_SESSION['lastName']=$lastName;
$_SESSION['activityArray']=$activityArray;
$_SESSION['steps']=$stepsToday;
$_SESSION['dailyGoal']=$stepGoal;
$_SESSION['todaysDate']=$todaysDate;
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
?>
I'm fairly confident that I've deduced the error is being thrown when running the line:
$accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
Any ideas why the error of "Forbidden" would show up? I'm not getting any php errors on my cgi_error log in my webhost's control panel.
Thank you so much in advance. I'm near pulling my hair out, and I'm not sure where to go from here.
Brett
I am trying to use the Admin-paterson oauth library for PHP to connect to slack
(https://github.com/adam-paterson/oauth2-slack)
When I run the sample code:
include("slack-vendor/autoload.php");
include("slacker/src/Provider/Slack.php");
$provider = new \AdamPaterson\OAuth2\Client\Provider\Slack([
'clientId' => $$slackid,
'clientSecret' => $slacksecret,
'redirectUri' => $returnURL,
]);
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: '.$authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$team = $provider->getResourceOwner($token);
// Use these details to create a new profile
printf('Hello %s!', $team->getName());
} catch (Exception $e) {
// Failed to get user details
exit('Oh dear...');
}
// Use this to interact with an API on the users behalf
echo $token->getToken();
}
I get an error back from slack saying :
Invalid permissions requested
Requested scopes cannot be blank
I tried adding a "scope" to the call like this:
$provider = new \AdamPaterson\OAuth2\Client\Provider\Slack([
'clientId' => $slackid,
'clientSecret' => $slacksecret,
'redirectUri' => $returnURL,
'scope' => 'channels:write,groups:write,team:read'
]);
but it still returns the same error.
When I look at the url the scope field is blank
what do I need to do to send scope to the server?
Add your scope in getAuthorizationUrl() method like this
$authUrl = $provider->getAuthorizationUrl([
'scope' => 'channels:write'
]);
use the scope as defined in https://api.slack.com/apps/ in your App, under OAuth, e.g. 'scope' => 'users.profile:read'
I am using an OAuth plugin in my php application. All works well when I use all the code in one function. But I want split the OAuth call, and the OAuth token treatment. I try to create a global var for the provider object, but it doesn't work. I always have an error with the $provider object.
This is the function I have for the moment :
function login(){
$provider = new Stevenmaguire\OAuth2\Client\Provider\Microsoft([
'clientId' => 'myclientid',
'clientSecret' => 'mysecret',
'redirectUri' => 'https://mywebsite'
//'redirectUri' => 'https://mywebsite/loginMicrosoft' //The url where I want use the token
]);
if (!isset($_GET['code'])) {
$authUrl = $provider->getAuthorizationUrl();
$this->Session->write('oauth2state', $provider->getState());
// This is the part I want put in the function loginMicrosoft. All else if and else
} elseif (empty($_GET['state']) || ($_GET['state'] !== $this->Session->read('oauth2state'))) {
$this->Session->destroy();
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Use this to interact with an API on the users behalf
$this->log( $token->getToken());
}
}
//This is the function where I want put the elseif and else treatment
function loginMicrosoft (){
}
Thanks for your help.
EDIT : I also try to put my provider object in session, but I have the message "Call to a member function getAccessToken() on a non object"
EDIT 2 : After unsuccessfully tried, I keep all the OAuth code in the same function