Completed
Pull Request — master (#572)
by Frédéric
01:32
created

MicrosoftGraph::requestAccessToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
4
namespace OAuth\OAuth2\Service;
5
6
use OAuth\Common\Consumer\CredentialsInterface;
7
use OAuth\Common\Http\Client\ClientInterface;
8
use OAuth\Common\Http\Exception\TokenResponseException;
9
use OAuth\Common\Http\Uri\Uri;
10
use OAuth\Common\Http\Uri\UriInterface;
11
use OAuth\Common\Storage\TokenStorageInterface;
12
use OAuth\Common\Token\TokenInterface;
13
use OAuth\OAuth2\Token\StdOAuth2Token;
14
15
/**
16
 * Class Azure
17
 * @package OAuth\OAuth2\Service
18
 * @author Juan Diaz - FuriosoJack <[email protected]>
19
 */
20
class MicrosoftGraph extends AbstractService
21
{
22
    private $resources = array(
23
        'graph' => 'https://graph.microsoft.com', // https://graph.windows.net
24
    );
25
    public function __construct(CredentialsInterface $credentials, ClientInterface $httpClient, TokenStorageInterface $storage, array $scopes = array(), UriInterface $baseApiUri = null, $stateParameterInAutUrl = false, $apiVersion = "")
26
    {
27
        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, $stateParameterInAutUrl, $apiVersion);
28
        if (is_null($baseApiUri)) {
29
            $this->baseApiUri = new Uri($this->resources['graph'].'myorganization/');
30
        }
31
    }
32
33
    /**
34
     * Parses the access token response and returns a TokenInterface.
35
     *
36
     *
37
     * @param string $responseBody
38
     *
39
     * @return TokenInterface
40
     *
41
     * @throws TokenResponseException
42
     */
43
    protected function parseAccessTokenResponse($responseBody)
44
    {
45
        $data = json_decode($responseBody, true);
46
        if (null === $data || !is_array($data)) {
47
            throw new TokenResponseException('Unable to parse response.');
48
        } elseif (isset($data['error_description'])) {
49
            throw new TokenResponseException('Error in retrieving token: "' . $data['error_description'] . '"');
50
        } elseif (isset($data['error'])) {
51
            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
52
        }
53
54
        $token = new StdOAuth2Token();
55
        $token->setAccessToken($data['access_token']);
56
        $token->setLifeTime($data['expires_in']);
57
        if (isset($data['refresh_token'])) {
58
            $token->setRefreshToken($data['refresh_token']);
59
            unset($data['refresh_token']);
60
        }
61
        unset($data['access_token']);
62
        unset($data['expires_in']);
63
        $token->setExtraParams($data);
64
        return $token;
65
    }
66
67
    /**
68
     * Returns the authorization API endpoint.
69
     *
70
     * @return UriInterface
71
     */
72
    public function getAuthorizationEndpoint()
73
    {
74
        return new Uri('https://login.microsoftonline.com/common/oauth2/authorize');
75
    }
76
77
    /**
78
     * Returns the access token API endpoint.
79
     *
80
     * @return UriInterface
81
     */
82
    public function getAccessTokenEndpoint()
83
    {
84
        return new Uri('https://login.microsoftonline.com/common/oauth2/token');
85
    }
86
87
    /**
88
     * @param $code
89
     * @param null $state
90
     * @return TokenInterface
91
     * @throws Exception\InvalidAuthorizationStateException
92
     * @throws TokenResponseException
93
     */
94
    public function requestAccessToken($code, $state = null)
95
    {
96
        if (null !== $state) {
97
            $this->validateAuthorizationState($state);
98
        }
99
        $bodyParams = array(
100
            'code'          => $code,
101
            'client_id'     => $this->credentials->getConsumerId(),
102
            'client_secret' => $this->credentials->getConsumerSecret(),
103
            'redirect_uri'  => $this->credentials->getCallbackUrl(),
104
            'grant_type'    => 'authorization_code',
105
            'resource' => $this->resources['graph'],
106
        );
107
        $responseBody = $this->httpClient->retrieveResponse(
108
            $this->getAccessTokenEndpoint(),
109
            $bodyParams,
110
            $this->getExtraOAuthHeaders()
111
        );
112
        $token = $this->parseAccessTokenResponse($responseBody);
113
        $this->storage->storeAccessToken($this->service(), $token);
114
        return $token;
115
    }
116
117
    /**
118
     * Devuelve los heades que tendra obtener el AccessToken
119
     * @return array
120
     */
121
    protected function getExtraOAuthHeaders()
122
    {
123
        return array(
124
            'Content-Type'=>'application/x-www-form-urlencoded',
125
        );
126
    }
127
128
    /**
129
     * Returns a class constant from ServiceInterface define el metodo e autorizacion del API
130
     * Header is the sane default.
131
     *
132
     * @return int
133
     */
134
    protected function getAuthorizationMethod()
135
    {
136
        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
137
    }
138
}
139