Errors when retrieving user details from Microsoft Graph using oauth2-microsoft - php

I am using oauth2-microsoft to develop a 'sign in with Microsoft' tool for my app. I'm successfully authenticating and receiving a token, but then I receive an error from the sample code.
I am using the sample code below and have tried various combinations of URLs in the 'urlResourceOwnerDetails' field, including leaving it blank.
$provider = new \Stevenmaguire\OAuth2\Client\Provider\Microsoft([
'clientId' => '<redacted>',
'clientSecret' => '<redacted>',
'redirectUri' => 'http://localhost/test.php',
'urlAuthorize' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
'urlAccessToken' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
'urlResourceOwnerDetails' => 'https://graph.microsoft.com/v1.0/me/drive'
]);
$options = [
'scope' => ['wl.basic', 'wl.signin']
];
After this comes authentication and token generation.
Then this line throws errors:
$user = $provider->getResourceOwner($token);
A token is definitely being generated, as I can echo $token and see it.
The above code should create a $user object that contains details about the logged in user. However, instead it generates these errors:
If 'urlResourceOwnerDetails' is set to https://graph.microsoft.com/v1.0/me/drive I get:
League\OAuth2\Client\Provider\Exception\IdentityProviderException: Access token is empty
If 'urlResourceOwnerDetails' is set to https://outlook.office.com/api/v2.0/me I get:
UnexpectedValueException: Invalid response received from Authorization Server. Expected JSON.
And if 'urlResourceOwnerDetails' is empty I get:
GuzzleHttp\Exception\RequestException: cURL error 3: malformed (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
Any ideas, please?

It appears oauth2-microsoft does not support Microsoft Graph Auth to a full extent at the moment, refer for example this thread
Regarding the error
League\OAuth2\Client\Provider\Exception\IdentityProviderException:
Access token is empty
access token is expected to be passed as Authorization header but according to Microsoft.php provider implementation it is passed instead as query string:
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
$uri = new Uri($this->urlResourceOwnerDetails);
return (string) Uri::withQueryValue($uri, 'access_token', (string) $token);
}
The way how library is designed, the following provider class could be introduced to support Microsoft Graph calls (by including access token in the Authorization header of a request)
class MicrosoftGraphProvider extends AbstractProvider
{
/**
* Get provider url to fetch user details
*
* #param AccessToken $token
*
* #return string
*/
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return 'https://graph.microsoft.com/v1.0/me';
}
protected function getAuthorizationHeaders($token = null)
{
return ['Authorization'=>'Bearer ' . $token->getToken()];
}
public function getBaseAuthorizationUrl()
{
return 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
}
public function getBaseAccessTokenUrl(array $params)
{
return 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
}
protected function getDefaultScopes()
{
return ['openid profile'];
}
protected function checkResponse(\Psr\Http\Message\ResponseInterface $response, $data)
{
// TODO: Implement checkResponse() method.
}
protected function createResourceOwner(array $response, AccessToken $token)
{
return (object)$response;
}
}

Related

Issue with DocuSign sending Envelopes

I recently changed my DocuSign integration to use the JWT OAuth flow. To achieve this I have a few classes.
OAuth Client
<?php
namespace App\DocuSign;
use DocuSign\eSign\Client\ApiClient;
use DocuSign\eSign\Client\Auth\OAuth;
use DocuSign\eSign\Configuration;
use Exception;
use Illuminate\Support\Facades\Log;
/**
* Helper class to generate a DocuSign Client instance using JWT OAuth2.
*
* #see
*
*/
class OAuthClient
{
/**
* Create a new DocuSign API Client instance using JWT based OAuth2.
*/
public static function createApiClient()
{
$config = (new Configuration())->setHost(config('docusign.host'));
$oAuth = (new OAuth())->setOAuthBasePath(config('docusign.oauth_base_path'));
$apiClient = new ApiClient($config, $oAuth);
try {
$response = $apiClient->requestJWTUserToken(
config('docusign.integrator_key'),
config('docusign.user_id'),
config('docusign.private_key'),
'signature impersonation',
60
);
if ($response) {
$accessToken = $response[0]['access_token'];
$config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);
$apiClient = new ApiClient($config);
return $apiClient;
}
} catch (Exception $e) {
// If consent is required we just need to give the consent URL.
if (strpos($e->getMessage(), 'consent_required') !== false) {
$authorizationUrl = config('docusign.oauth_base_path') . '/oauth/auth?' . http_build_query([
'scope' => 'signature impersonation',
'redirect_uri' => config('docusign.redirect_url'),
'client_id' => config('docusign.integrator_key'),
'response_type' => 'code'
]);
Log::critical('Consent not given for DocuSign API', [
'authorization_url' => $authorizationUrl
]);
abort(500, 'Consent has not been given to use the DocuSign API');
}
throw $e;
}
}
}
Signature Client Service
<?php
namespace App\DocuSign;
use DocuSign\eSign\Api\EnvelopesApi;
use DocuSign\eSign\Client\ApiClient;
class SignatureClientService
{
/**
* DocuSign API Client
*/
public ApiClient $apiClient;
/**
* Create a new instance of our class.
*/
public function __construct()
{
$this->apiClient = OAuthClient::createApiClient();
}
/**
* Getter for the EnvelopesApi
*/
public function getEnvelopeApi(): EnvelopesApi
{
return new EnvelopesApi($this->apiClient);
}
}
Then, in my constructors where I want to use it I'm doing
/**
* Create a new controller instance
*/
public function __construct()
{
$this->clientService = new SignatureClientService();
$this->envelopesApi = $this->clientService->getEnvelopeApi();
}
Finally, I use it like so
$envelopeSummary = $this->envelopesApi->createEnvelope(config('docusign.api_account_id'), $envelopeDefinition);
But I get an error that reads
DocuSign\eSign\Client\ApiException: Error while requesting server,
received a non successful HTTP code [400] with response Body:
O:8:"stdClass":2:{s:9:"errorCode";s:21:"USER_LACKS_MEMBERSHIP";s:7:"message";s:60:"The
UserID does not have a valid membership in this Account.";} in
/homepages/45/d641872465/htdocs/sites/ita-portal/vendor/docusign/esign-client/src/Client/ApiClient.php:344
I researched this and this would imply that the user is not within the account, but they are. I also checked that this account owns the envelopes that I'm trying to send.
For reference I took inspiration for envelope sending from here: https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-template-remote/
What I think is happening is that the request is going to the wrong server or the wrong account.
I'd suggest using a packet analyser like Fiddler or Wireshark to log where your requests are headed (or just log the request within your application)
The auth URLs seem to be correct since you're not getting a 401 unauthorised error but the envelopes and other queries' must match the base URL located in your account under the Apps and Keys page. It would be of the form demo.docusign.net for our demo environment or xxx.docusign.net for our production environment

Storing and retrieving session variables in unit/feature tests in Laravel

In a Laravel feature test, I'm trying to store a variable in a session so that I can use it in the rest of my tests, like so:
public function testLogin()
{
$response = $this->json('POST', '/login', $myCredentials);
$response
->assertStatus(200)
->assertJson([
'token' => true
]);
session(['token' => $response['token']]);
}
When I run "phpunit" in the command line, I get this error:
PHP Fatal error: Uncaught ReflectionException: Class session does
not exist in
/vendor/laravel/framework/src/Illuminate/Container/Container.php:752
Apparently the "session()" global helper doesn't work in test classes. I also tried to work with the class directly by using "Illuminate\Session" or just "\Session", but both returned in "not found" errors. How can I store and retrieve session variables within test classes?
In tests it's a bit different.
https://laravel.com/docs/5.2/testing#sessions-and-authentication
Here is an example:
public function testApplication()
{
$this->withSession(['foo' => 'bar'])
->visit('/');
}
There a way to do that you want. The unic problem it's that doesn't work with session.
When you start the test, you must generate the function "master" that will call the rest of functions.
/**
* Try to login the api client (if you have another middleware use it)
* #group groupTests
* #test
*/
public function masterFunction() {
//create the body data to try generate the oauth token
$body = [
'client_id' => $this->client_id_test,
'client_secret' => $this->secret,
'grant_type' => 'client_credentials',
'scope' => ''
];
//get the response with the data
$response = $this->json('POST','/oauth/token',$body,['Accept' => 'application/json']);
//check that return a valid token
$response->assertStatus(200)->assertJsonStructure(['token_type','expires_in','access_token']);
//get token data in var
$token = $response->json("token_type")." ".$response->json("access_token");
//send string token to the next function
$this->childrenFunction($token);
}
When you construct "children functions" must make them like this:
/**
* This function get the token as param
* #param String $token The token that we want
* #group groupTests
*/
private function childrenFunction($token){
//here can call to $token as a var
dd($token);
}
It's important that "children functions" doesn't have * #test at the header description.

Symfony Oauth2 with gard

I am trying to configure guard with an OAuth 2 connection.
I am trying to do this with a redirection in the getCredentials function to the Microsoft login website but I can't make it work. I don't know how I can make it worked.
It seems there is no redirection possible in this function.
public function getCredentials(Request $request)
{
$provider = new Microsoft([
'clientId' => '0000000032624',
'clientSecret' => 'my-secret',
'redirectUri' => 'https://mysite/oauthlogin'
]);
if(!$request->query->has('code')){
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$request->getSession()->set('oauth2state', $provider->getState());
//This doesn't work
return new RedirectResponse($authUrl);
// Check given state against previously stored one to mitigate CSRF attack
}elseif ( empty($request->query->get('state')) || ($request->query->get('state')!==$request->getSession()->get('oauth2state')) ){
return null;
}else{
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $request->query->get('code')
]);
try {
//when log with microsoft, check if user is allowed
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
} catch (Exception $e) {
// Failed to get user details
}
}
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
return $userProvider->loadUserByUsername($user->getEmail());
}
public function checkCredentials($credentials, UserInterface $user)
{
// check credentials - e.g. make sure the password is valid
// no credential check is needed in this case
// return true to cause authentication success
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$url = $this->router->generate('homepage');
return new RedirectResponse($url);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
);
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $data);
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
Function getCredentials() is not supposed to return a Response, it provide the credentials used in getUser().
In the getUser() documentation :
The credentials are the return value from getCredentials()
You may throw an AuthenticationException if you wish. If you return
null, then a UsernameNotFoundException is thrown for you.
In case of exception thrown, onAuthenticationFailure() is called and here you can return your RedirectResponse.
For more detailled informations, see the source code of the \Symfony\Component\Security\Guard\GuardAuthenticatorInterface which contains a lots of explanations in its methods.

Server returns 500 error on phpmailer get outh token file

When I try to access phpmailer/get_outh_token.php to get refresh token server returns:
HTTP ERROR 500
Client ID, Secret key and redirect Uri are correct, and i am using it already in Wordpress.
I have downloaded last version of phpmailer, also tested with old version with same result.
I found what cause this, it is this part:
namespace League\OAuth2\Client\Provider;
When I remove it, then script loads with errors of course because
Provider namespace is not loaded.
Website working on PHP 7.
This is full code of get_outh_token.php, and it is original (just credentials are different of course):
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
/**
* Get an OAuth2 token from Google.
* * Install this script on your server so that it's accessible
* as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
* e.g.: http://localhost/phpmail/get_oauth_token.php
* * Ensure dependencies are installed with 'composer install'
* * Set up an app in your Google developer console
* * Set the script address as the app's redirect URL
* If no refresh token is obtained when running this file, revoke access to your app
* using link: https://accounts.google.com/b/0/IssuedAuthSubTokens and run the script again.
* This script requires PHP 5.4 or later
* PHP Version 5.4
*/
namespace League\OAuth2\Client\Provider; //when i remove this line, than page load without 500, but with errors.
require 'vendor/autoload.php';
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
session_start();
//If this automatic URL doesn't work, set it yourself manually
$redirectUri = 'https://www.secret.co/phpmailer/get_oauth_token.php';
//These details obtained are by setting up app in Google developer console.
$clientId = 'secret.apps.googleusercontent.com';
$clientSecret = 'secret';
class Google extends AbstractProvider
{
use BearerAuthorizationTrait;
const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'id';
/**
* #var string If set, this will be sent to google as the "access_type" parameter.
* #link https://developers.google.com/accounts/docs/OAuth2WebServer#offline
*/
protected $accessType;
/**
* #var string If set, this will be sent to google as the "hd" parameter.
* #link https://developers.google.com/accounts/docs/OAuth2Login#hd-param
*/
protected $hostedDomain;
/**
* #var string If set, this will be sent to google as the "scope" parameter.
* #link https://developers.google.com/gmail/api/auth/scopes
*/
protected $scope;
public function getBaseAuthorizationUrl()
{
return 'https://accounts.google.com/o/oauth2/auth';
}
public function getBaseAccessTokenUrl(array $params)
{
return 'https://accounts.google.com/o/oauth2/token';
}
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return ' ';
}
protected function getAuthorizationParameters(array $options)
{
if (is_array($this->scope)) {
$separator = $this->getScopeSeparator();
$this->scope = implode($separator, $this->scope);
}
$params = array_merge(
parent::getAuthorizationParameters($options),
array_filter([
'hd' => $this->hostedDomain,
'access_type' => $this->accessType,
'scope' => $this->scope,
// if the user is logged in with more than one account ask which one to use for the login!
'authuser' => '-1'
])
);
return $params;
}
protected function getDefaultScopes()
{
return [
'email',
'openid',
'profile',
];
}
protected function getScopeSeparator()
{
return ' ';
}
protected function checkResponse(ResponseInterface $response, $data)
{
if (!empty($data['error'])) {
$code = 0;
$error = $data['error'];
if (is_array($error)) {
$code = $error['code'];
$error = $error['message'];
}
throw new IdentityProviderException($error, $code, $data);
}
}
protected function createResourceOwner(array $response, AccessToken $token)
{
return new GoogleUser($response);
}
}
//Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
$provider = new Google(
array(
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'scope' => array('https://mail.google.com/'),
'accessType' => 'offline'
)
);
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',
array(
'code' => $_GET['code']
)
);
// Use this to get a new access token if the old one expires
echo 'Refresh Token: ' . $token->getRefreshToken();
}
I know this question is old, but I was having same issue.
All I did was to install league/oauth2-google via composer
composer require league/oauth2-google
This helped me figure it out
Hope it help some else.

Laravel Redirect::to() not working

I am creating a twitter log in feature for my project, the oauth step where the user has granted permission for my app to use their data returns the user to the /twitter-auth route, this route in turn initiates this method:
public function auth() {
/* Oauth token */
$token = Input::get('oauth_token');
/* Verifier token */
$verifier = Input::get('oauth_verifier');
/* Request access token */
$accessToken = Twitter::oAuthAccessToken($token, $verifier);
/* Set the session variables from the acccess token above */
Session::set('user_id', $accessToken['user_id']);
Session::set('username', $accessToken['screen_name']);
Session::set('oauth_token', $accessToken['oauth_token']);
Session::set('oauth_token_secret', $accessToken['oauth_token_secret']);
/* Determine if the user already exists in the database, if he/she does, then
only update the user, otherwise, store a new user. Also pass an instance of the
accessToken as flash data in both instances. */
if( User::where('twitter_id', $accessToken['user_id'])->first() == null )
{
$newUser = array(
'username' => $accessToken['screen_name'],
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'twitter_id' => $accessToken['user_id']
);
User::create( $newUser );
return Redirect::to('/');
}
else
{
$userToUpdate = User::where('twitter_id', Session::get('user_id'))->first();
$userToUpdate->username = $accessToken['screen_name'];
$userToUpdate->oauth_token = $accessToken['oauth_token'];
$userToUpdate->oauth_token_secret = $accessToken['oauth_token_secret'];
$userToUpdate->twitter_id = $accessToken['user_id'];
$userToUpdate->save();
return Redirect::to('/');
}
}
The user is saved/updated as necessary, but the user is not redirected to the home page. This happens with the redirect code both inside and outside of the IF statement. I was wondering if anyone could give me any clues as to why the redirect isn't working?
You are missing a return
your function in this case auth() is returning the Redirect object but is the function calling your auth() function is returning the result back to the controller?
Please make sure that in your controller, you return the Redirect class that is from auth() function.
Just tested your code and works :
let's say you have a UserController :
routes.php
Route::get('twitter-auth',array('as'=>'twitter-auth', 'uses'=>'UserController#twitterAuth'));
UserController
the user model class is just passed by dependency injection, to test this part also.
<?php
class UserController extends BaseController {
public function __construct(User $u){
$this->user = $u;
}
public function twitterAuth(){
return $this->user->auth();
}
}
User model :
I had to modify the code a little to fit my setup also
public function auth(){
/* Oauth token */
$token = Input::get('oauth_token');
/* Verifier token */
$verifier = Input::get('oauth_verifier');
/* Request access token */
//$accessToken = Twitter::oAuthAccessToken($token, $verifier);
//emulate the request of access Token
$accessToken = [
'user_id'=>'11',
'screen_name'=>'fewfewfew',
'oauth_token'=>'12312321',
'oauth_token_secret'=>'12312232323'
];
/* Set the session variables from the acccess token above */
Session::set('user_id', $accessToken['user_id']);
Session::set('username', $accessToken['screen_name']);
Session::set('oauth_token', $accessToken['oauth_token']);
Session::set('oauth_token_secret', $accessToken['oauth_token_secret']);
/* Determine if the user already exists in the database, if he/she does, then
only update the user, otherwise, store a new user. Also pass an instance of the
accessToken as flash data in both instances. */
if( User::where('twitter_id', $accessToken['user_id'])->first() == null )
{
$newUser = array(
'username' => $accessToken['screen_name'],
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'twitter_id' => $accessToken['user_id']
);
User::create( $newUser );
return Redirect::to('/');
}
else
{
$userToUpdate = User::where('twitter_id', Session::get('user_id'))->first();
$userToUpdate->username = $accessToken['screen_name'];
$userToUpdate->oauth_token = $accessToken['oauth_token'];
$userToUpdate->oauth_token_secret = $accessToken['oauth_token_secret'];
$userToUpdate->twitter_id = $accessToken['user_id'];
$userToUpdate->save();
return Redirect::to('/');
}
}
Let me know if this is what you wanted
Returning a Redirect to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send()
Redirect::to('login')->send();

Categories