This commit is contained in:
2025-10-20 14:10:54 +02:00
parent 75ca8fd840
commit d2c1970ef8
732 changed files with 101915 additions and 2 deletions

View File

@@ -0,0 +1,5 @@
/build
/vendor
composer.phar
composer.lock
.DS_Store

View File

@@ -0,0 +1,35 @@
filter:
excluded_paths: [tests/*]
checks:
php:
code_rating: true
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
tools:
external_code_coverage:
timeout: 600
runs: 3
php_analyzer: true
php_code_coverage: false
php_code_sniffer:
config:
standard: PSR2
filter:
paths: ['src']
php_loc:
enabled: true
excluded_dirs: [vendor, tests]
php_cpd:
enabled: true
excluded_dirs: [vendor, tests]

View File

@@ -0,0 +1,45 @@
language: php
matrix:
include:
- php: 5.6
- php: 7.0
- php: 7.1
- php: nightly
- php: hhvm-3.6
sudo: required
dist: trusty
group: edge
- php: hhvm-3.9
sudo: required
dist: trusty
group: edge
- php: hhvm-3.12
sudo: required
dist: trusty
group: edge
- php: hhvm-3.15
sudo: required
dist: trusty
group: edge
- php: hhvm-nightly
sudo: required
dist: trusty
group: edge
fast_finish: true
allow_failures:
- php: nightly
- php: hhvm-nightly
before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
- travis_retry phpenv rehash
script:
- ./vendor/bin/phpcs --standard=psr2 src/
- ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover

View File

@@ -0,0 +1,108 @@
# Changelog
All Notable changes to `oauth2-microsoft` will be documented in this file
## 2.2.0 - 2017-06-07
### Added
- Nothing
### Deprecated
- Nothing
### Fixed
- Nothing
### Removed
- Support for retrieving image urls.
### Security
- Nothing
## 2.1.0 - 2017-06-04
### Added
- Support for custom authorization urls, previous URLs serve as default values.
### Deprecated
- Nothing
### Fixed
- Nothing
### Removed
- Nothing
### Security
- Nothing
## 2.0.0 - 2017-01-25
### Added
- PHP 7.1 Support
### Deprecated
- Nothing
### Fixed
- Nothing
### Removed
- PHP 5.5 Support
### Security
- Nothing
## 1.0.0 - 2017-01-25
Bump for base package parity
## 0.2.1 - 2015-11-12
### Added
- Nothing
### Deprecated
- Nothing
### Fixed
- Improved null checks in checkResponse method
### Removed
- Nothing
### Security
- Nothing
## 0.2.0 - 2015-08-20
### Added
- Upgrade to support version 1.0 release of core client
### Deprecated
- Nothing
### Fixed
- Nothing
### Removed
- Nothing
### Security
- Nothing
## 0.1.0 - 2015-03-21
### Added
- Initial release!
### Deprecated
- Nothing
### Fixed
- Nothing
### Removed
- Nothing
### Security
- Nothing

View File

@@ -0,0 +1,42 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/stevenmaguire/oauth2-microsoft).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option.
- **Create topic branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass.
- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails.
## Running Tests
``` bash
$ ./vendor/bin/phpunit
```
## Running PHP Code Sniffer
``` bash
$ ./vendor/bin/phpcs src --standard=psr2 -sp
```
**Happy coding**!

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Steven Maguire
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,140 @@
# Microsoft Provider for OAuth 2.0 Client
[![Latest Version](https://img.shields.io/github/release/stevenmaguire/oauth2-microsoft.svg?style=flat-square)](https://github.com/stevenmaguire/oauth2-microsoft/releases)
[![Build Status](https://img.shields.io/travis/stevenmaguire/oauth2-microsoft/master.svg?style=flat-square)](https://travis-ci.org/stevenmaguire/oauth2-microsoft)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/stevenmaguire/oauth2-microsoft.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-microsoft/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/stevenmaguire/oauth2-microsoft.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-microsoft)
[![Total Downloads](https://img.shields.io/packagist/dt/stevenmaguire/oauth2-microsoft.svg?style=flat-square)](https://packagist.org/packages/stevenmaguire/oauth2-microsoft)
[![Software License](https://img.shields.io/packagist/l/stevenmaguire/oauth2-microsoft.svg?style=flat-square)](LICENSE.md)
This package provides Microsoft OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).
## Installation
To install, use composer:
```
composer require stevenmaguire/oauth2-microsoft
```
## Usage
Usage is the same as The League's OAuth client, using `\Stevenmaguire\OAuth2\Client\Provider\Microsoft` as the provider.
### Authorization Code Flow
```php
$provider = new Stevenmaguire\OAuth2\Client\Provider\Microsoft([
// Required
'clientId' => '{microsoft-client-id}',
'clientSecret' => '{microsoft-client-secret}',
'redirectUri' => 'https://example.com/callback-url',
// Optional
'urlAuthorize' => 'https://login.windows.net/common/oauth2/authorize',
'urlAccessToken' => 'https://login.windows.net/common/oauth2/token',
'urlResourceOwnerDetails' => 'https://outlook.office.com/api/v1.0/me'
]);
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
$user = $provider->getResourceOwner($token);
// Use these details to create a new profile
printf('Hello %s!', $user->getFirstname());
} 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();
}
```
#### Managing Scopes and State
When creating your Microsoft authorization URL, you can specify the state and scopes your application may authorize.
```php
$options = [
'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE',
'scope' => ['wl.basic', 'wl.signin'] // array or string
];
$authorizationUrl = $provider->getAuthorizationUrl($options);
```
If neither are defined, the provider will utilize internal defaults.
At the time of authoring this documentation, the following scopes are available.
##### Core
- wl.basic
- wl.offline_access
- wl.signin
##### Extended
- wl.birthday
- wl.calendars
- wl.calendars_update
- wl.contacts_birthday
- wl.contacts_create
- wl.contacts_calendars
- wl.contacts_photos
- wl.contacts_skydrive
- wl.emails
- wl.events_create
- wl.imap
- wl.phone_numbers
- wl.photos
- wl.postal_addresses
- wl.skydrive
- wl.skydrive_update
- wl.work_profile
- office.onenote_create
## Testing
``` bash
$ ./vendor/bin/phpunit
```
## Contributing
Please see [CONTRIBUTING](https://github.com/stevenmaguire/oauth2-microsoft/blob/master/CONTRIBUTING.md) for details.
## Credits
- [Steven Maguire](https://github.com/stevenmaguire)
- [All Contributors](https://github.com/stevenmaguire/oauth2-microsoft/contributors)
## License
The MIT License (MIT). Please see [License File](https://github.com/stevenmaguire/oauth2-microsoft/blob/master/LICENSE) for more information.

View File

@@ -0,0 +1,38 @@
{
"name": "stevenmaguire\/oauth2-microsoft",
"description": "Microsoft OAuth 2.0 Client Provider for The PHP League OAuth2-Client",
"license": "MIT",
"authors": [
{
"name": "Steven Maguire",
"email": "stevenmaguire@gmail.com",
"homepage": "https:\/\/github.com\/stevenmaguire"
}
],
"keywords": [
"oauth",
"oauth2",
"client",
"authorization",
"authorisation",
"microsoft"
],
"require": {
"league\/oauth2-client": "^2.0"
},
"require-dev": {
"phpunit\/phpunit": "~4.0",
"mockery\/mockery": "~0.9",
"squizlabs\/php_codesniffer": "~2.0"
},
"autoload": {
"psr-4": {
"Pshowsso\\Scope68f5e85e9608b\\Stevenmaguire\\OAuth2\\Client\\": "src\/"
}
},
"autoload-dev": {
"psr-4": {
"Pshowsso\\Scope68f5e85e9608b\\Stevenmaguire\\OAuth2\\Client\\Test\\": "tests\/src\/"
}
}
}

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<logging>
<log type="coverage-html"
target="./build/coverage/html"
charset="UTF-8"
highlight="false"
lowUpperBound="35"
highLowerBound="70"/>
<log type="coverage-clover"
target="./build/coverage/log/coverage.xml"/>
</logging>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
<exclude>
<directory suffix=".php">./vendor</directory>
<directory suffix=".php">./tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,99 @@
<?php
namespace Pshowsso\Scope68f5e85e9608b\Stevenmaguire\OAuth2\Client\Provider;
use Pshowsso\Scope68f5e85e9608b\GuzzleHttp\Psr7\Uri;
use Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Provider\AbstractProvider;
use Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Token\AccessToken;
use Pshowsso\Scope68f5e85e9608b\Psr\Http\Message\ResponseInterface;
class Microsoft extends AbstractProvider
{
/**
* Default scopes
*
* @var array
*/
public $defaultScopes = ['wl.basic', 'wl.emails'];
/**
* Base url for authorization.
*
* @var string
*/
protected $urlAuthorize = 'https://login.live.com/oauth20_authorize.srf';
/**
* Base url for access token.
*
* @var string
*/
protected $urlAccessToken = 'https://login.live.com/oauth20_token.srf';
/**
* Base url for resource owner.
*
* @var string
*/
protected $urlResourceOwnerDetails = 'https://apis.live.net/v5.0/me';
/**
* Get authorization url to begin OAuth flow
*
* @return string
*/
public function getBaseAuthorizationUrl()
{
return $this->urlAuthorize;
}
/**
* Get access token url to retrieve token
*
* @return string
*/
public function getBaseAccessTokenUrl(array $params)
{
return $this->urlAccessToken;
}
/**
* Get default scopes
*
* @return array
*/
protected function getDefaultScopes()
{
return $this->defaultScopes;
}
/**
* Check a provider response for errors.
*
* @throws IdentityProviderException
* @param ResponseInterface $response
* @return void
*/
protected function checkResponse(ResponseInterface $response, $data)
{
if (isset($data['error'])) {
throw new IdentityProviderException(isset($data['error']['message']) ? $data['error']['message'] : $response->getReasonPhrase(), $response->getStatusCode(), $response);
}
}
/**
* Generate a user object from a successful user details request.
*
* @param array $response
* @param AccessToken $token
* @return MicrosoftResourceOwner
*/
protected function createResourceOwner(array $response, AccessToken $token)
{
return new MicrosoftResourceOwner($response);
}
/**
* Get provider url to fetch user details
*
* @param AccessToken $token
*
* @return string
*/
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
$uri = new Uri($this->urlResourceOwnerDetails);
return (string) Uri::withQueryValue($uri, 'access_token', (string) $token);
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Pshowsso\Scope68f5e85e9608b\Stevenmaguire\OAuth2\Client\Provider;
use Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Provider\ResourceOwnerInterface;
class MicrosoftResourceOwner implements ResourceOwnerInterface
{
/**
* Raw response
*
* @var array
*/
protected $response;
/**
* Creates new resource owner.
*
* @param array $response
*/
public function __construct(array $response = array())
{
$this->response = $response;
}
/**
* Get user id
*
* @return string|null
*/
public function getId()
{
return $this->response['id'] ?: null;
}
/**
* Get user email
*
* @return string|null
*/
public function getEmail()
{
return $this->response['emails']['preferred'] ?: null;
}
/**
* Get user firstname
*
* @return string|null
*/
public function getFirstname()
{
return $this->response['first_name'] ?: null;
}
/**
* Get user lastname
*
* @return string|null
*/
public function getLastname()
{
return $this->response['last_name'] ?: null;
}
/**
* Get user name
*
* @return string|null
*/
public function getName()
{
return $this->response['name'] ?: null;
}
/**
* Get user urls
*
* @return string|null
*/
public function getUrls()
{
return isset($this->response['link']) ? $this->response['link'] . '/cid-' . $this->getId() : null;
}
/**
* Return all of the owner details available as an array.
*
* @return array
*/
public function toArray()
{
return $this->response;
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Pshowsso\Scope68f5e85e9608b\Stevenmaguire\OAuth2\Client\Test\Provider;
use Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Tool\QueryBuilderTrait;
use Mockery as m;
class MicrosoftTest extends \PHPUnit_Framework_TestCase
{
use QueryBuilderTrait;
protected $provider;
protected function setUp()
{
$this->provider = new \Pshowsso\Scope68f5e85e9608b\Stevenmaguire\OAuth2\Client\Provider\Microsoft(['clientId' => 'mock_client_id', 'clientSecret' => 'mock_secret', 'redirectUri' => 'none']);
}
public function tearDown()
{
m::close();
parent::tearDown();
}
public function testAuthorizationUrl()
{
$url = $this->provider->getAuthorizationUrl();
$uri = parse_url($url);
parse_str($uri['query'], $query);
$this->assertArrayHasKey('client_id', $query);
$this->assertArrayHasKey('redirect_uri', $query);
$this->assertArrayHasKey('state', $query);
$this->assertArrayHasKey('scope', $query);
$this->assertArrayHasKey('response_type', $query);
$this->assertArrayHasKey('approval_prompt', $query);
$this->assertNotNull($this->provider->getState());
}
public function testScopes()
{
$scopeSeparator = ',';
$options = ['scope' => [uniqid(), uniqid()]];
$query = ['scope' => implode($scopeSeparator, $options['scope'])];
$url = $this->provider->getAuthorizationUrl($options);
$encodedScope = $this->buildQueryString($query);
$this->assertContains($encodedScope, $url);
}
public function testGetAuthorizationUrl()
{
$url = $this->provider->getAuthorizationUrl();
$uri = parse_url($url);
$this->assertEquals('/oauth20_authorize.srf', $uri['path']);
}
public function testGetBaseAccessTokenUrl()
{
$params = [];
$url = $this->provider->getBaseAccessTokenUrl($params);
$uri = parse_url($url);
$this->assertEquals('/oauth20_token.srf', $uri['path']);
}
public function testSettingAuthEndpoints()
{
$customAuthUrl = uniqid();
$customTokenUrl = uniqid();
$customResourceOwnerUrl = uniqid();
$token = m::mock('Pshowsso\Scope68f5e85e9608b\League\OAuth2\Client\Token\AccessToken');
$this->provider = new \Pshowsso\Scope68f5e85e9608b\Stevenmaguire\OAuth2\Client\Provider\Microsoft(['clientId' => 'mock_client_id', 'clientSecret' => 'mock_secret', 'redirectUri' => 'none', 'urlAuthorize' => $customAuthUrl, 'urlAccessToken' => $customTokenUrl, 'urlResourceOwnerDetails' => $customResourceOwnerUrl]);
$authUrl = $this->provider->getAuthorizationUrl();
$this->assertContains($customAuthUrl, $authUrl);
$tokenUrl = $this->provider->getBaseAccessTokenUrl([]);
$this->assertContains($customTokenUrl, $tokenUrl);
$resourceOwnerUrl = $this->provider->getResourceOwnerDetailsUrl($token);
$this->assertContains($customResourceOwnerUrl, $resourceOwnerUrl);
}
public function testGetAccessToken()
{
$response = m::mock('Pshowsso\Scope68f5e85e9608b\Psr\Http\Message\ResponseInterface');
$response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token","authentication_token":"","code":"","expires_in":3600,"refresh_token":"mock_refresh_token","scope":"","state":"","token_type":""}');
$response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
$client = m::mock('Pshowsso\Scope68f5e85e9608b\GuzzleHttp\ClientInterface');
$client->shouldReceive('send')->times(1)->andReturn($response);
$this->provider->setHttpClient($client);
$token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
$this->assertEquals('mock_access_token', $token->getToken());
$this->assertLessThanOrEqual(time() + 3600, $token->getExpires());
$this->assertGreaterThanOrEqual(time(), $token->getExpires());
$this->assertEquals('mock_refresh_token', $token->getRefreshToken());
$this->assertNull($token->getResourceOwnerId());
}
public function testUserData()
{
$email = uniqid();
$firstname = uniqid();
$lastname = uniqid();
$name = uniqid();
$userId = rand(1000, 9999);
$urls = uniqid();
$postResponse = m::mock('Pshowsso\Scope68f5e85e9608b\Psr\Http\Message\ResponseInterface');
$postResponse->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token","authentication_token":"","code":"","expires_in":3600,"refresh_token":"mock_refresh_token","scope":"","state":"","token_type":""}');
$postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
$userResponse = m::mock('Pshowsso\Scope68f5e85e9608b\Psr\Http\Message\ResponseInterface');
$userResponse->shouldReceive('getBody')->andReturn('{"id": ' . $userId . ', "name": "' . $name . '", "first_name": "' . $firstname . '", "last_name": "' . $lastname . '", "emails": {"preferred": "' . $email . '"}, "link": "' . $urls . '"}');
$userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
$client = m::mock('Pshowsso\Scope68f5e85e9608b\GuzzleHttp\ClientInterface');
$client->shouldReceive('send')->times(2)->andReturn($postResponse, $userResponse);
$this->provider->setHttpClient($client);
$token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
$user = $this->provider->getResourceOwner($token);
$this->assertEquals($email, $user->getEmail());
$this->assertEquals($email, $user->toArray()['emails']['preferred']);
$this->assertEquals($firstname, $user->getFirstname());
$this->assertEquals($firstname, $user->toArray()['first_name']);
$this->assertEquals($lastname, $user->getLastname());
$this->assertEquals($lastname, $user->toArray()['last_name']);
$this->assertEquals($name, $user->getName());
$this->assertEquals($name, $user->toArray()['name']);
$this->assertEquals($userId, $user->getId());
$this->assertEquals($userId, $user->toArray()['id']);
$this->assertEquals($urls . '/cid-' . $userId, $user->getUrls());
$this->assertEquals($urls . '/cid-' . $userId, $user->toArray()['link'] . '/cid-' . $user->toArray()['id']);
}
/**
* @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException
**/
public function testExceptionThrownWhenErrorObjectReceived()
{
$message = uniqid();
$postResponse = m::mock('Pshowsso\Scope68f5e85e9608b\Psr\Http\Message\ResponseInterface');
$postResponse->shouldReceive('getBody')->andReturn('{"error": {"code": "request_token_expired", "message": "' . $message . '"}}');
$postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
$postResponse->shouldReceive('getStatusCode')->andReturn(500);
$client = m::mock('Pshowsso\Scope68f5e85e9608b\GuzzleHttp\ClientInterface');
$client->shouldReceive('send')->times(1)->andReturn($postResponse);
$this->provider->setHttpClient($client);
$token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
}
}