README.md 10.3 KB
Newer Older
1 2 3
AuthClient Extension for Yii 2
==============================

4 5
This extension adds [OpenID](http://openid.net/), [OAuth](http://oauth.net/) and [OAuth2](http://oauth.net/2/) consumers
for the Yii framework 2.0.
6 7 8 9 10 11 12 13 14 15


Installation
------------

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
16
composer require --prefer-dist yiisoft/yii2-authclient "*"
17 18 19 20 21 22 23 24
```

or add

```json
"yiisoft/yii2-authclient": "*"
```

Qiang Xue committed
25
to the `require` section of your composer.json.
26 27


28 29
Quick start
-----------
30

31 32 33 34 35
This extension provides the ability of the authentication via external credentials providers.
It covers OpenID, OAuth1 and OAuth2 protocols.

You need to setup auth client collection application component:

Klimov Paul committed
36
```php
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
'components' => [
    'authClientCollection' => [
        'class' => 'yii\authclient\Collection',
        'clients' => [
            'google' => [
                'class' => 'yii\authclient\clients\GoogleOpenId'
            ],
            'facebook' => [
                'class' => 'yii\authclient\clients\Facebook',
                'clientId' => 'facebook_client_id',
                'clientSecret' => 'facebook_client_secret',
            ],
        ],
    ]
    ...
]
```

55
Then you need to add [[yii\authclient\AuthAction]] to web controller:
56

Klimov Paul committed
57
```php
58 59 60 61 62 63 64 65 66
class SiteController extends Controller
{
    public function actions()
    {
        return [
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'successCallback'],
            ],
Arthur Khachaturov committed
67
        ];
68 69 70 71
    }

    public function successCallback($client)
    {
Qiang Xue committed
72
        $attributes = $client->getUserAttributes();
73 74 75 76 77
        // user login or signup comes here
    }
}
```

78
You may use [[yii\authclient\widgets\AuthChoice]] to compose auth client selection:
79

Klimov Paul committed
80
```php
81
<?= yii\authclient\widgets\AuthChoice::widget([
82
     'baseAuthUrl' => ['site/auth']
Qiang Xue committed
83 84
]) ?>
```
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103


Base auth clients overview
--------------------------

This extension provides the base client class for each supported auth protocols:
 - [[yii\authclient\OpenId]] supports [OpenID](http://openid.net/)
 - [[yii\authclient\OAuth1]] supports [OAuth 1/1.0a](http://oauth.net/)
 - [[yii\authclient\OAuth2]] supports [OAuth 2](http://oauth.net/2/)

You may use these classes as they are to use external auth provider, or extend them
in order to create some particular provider oriented client.

Please, refer to the particular base client class documentation for its actual usage.

Although, all clients are different they shares same basic interface [[yii\authclient\ClientInterface]],
which governs some common API.

Each client has some descriptive data, which can be used for different purposes:
104 105
 - `id` - unique client id, which separates it from other clients, it could be used in URLs, logs etc.
 - `name` - external auth provider name, which this client is match too. Different auth clients
106 107 108
 can share the same name, if they refer to the same external auth provider.
 For example: clients for Google OpenID and Google OAuth have same name "google".
 This attribute can be used inside the database, CSS styles and so on.
109
 - `title` - user friendly name for the external auth provider, it is used to present auth client
110 111
 at the view layer.

112
Each auth client has different auth flow, but all of them supports `getUserAttributes()` method,
113 114 115 116
which can be invoked if authentication was successful.
This method allows you to get information about external user account, such as id, email address,
full name, preferred language etc.
Defining list of attributes, which external auth provider should return, depends on client type:
117 118
 - [[yii\authclient\OpenId]]: combination of `requiredAttributes` and `optionalAttributes`
 - [[yii\authclient\OAuth1]] and [[yii\authclient\OAuth2]]: field `scope`, note that different
119 120
 providers use different formats for the scope.

121
Each auth client has `viewOptions` attribute. It is an array, which stores name-value pairs,
122
which serve to compose client representation in the view.
123
For example widget [[yii\authclient\widgets\AuthChoice]] uses keys `popupWidth` and `popupHeight` to
124 125 126 127 128 129
determine the size of authentication popup window.


External API usage
------------------

130
Both [[yii\authclient\OAuth1]] and [[yii\authclient\OAuth2]] provide method `api()`, which
131 132 133 134 135
can be used to access external auth provider REST API. However this method is very basic and
it may be not enough to access full external API functionality. This method is mainly used to
fetch the external user account data.
To use API calls, you need to setup [[yii\authclient\BaseOAuth::apiBaseUrl]] according to the
API specification. Then you can call [[yii\authclient\BaseOAuth::api()]] method:
Klimov Paul committed
136 137

```php
138 139 140 141 142 143 144 145 146 147 148 149 150
use yii\authclient\OAuth2;

$client = new OAuth2;
...
$client->apiBaseUrl = 'https://www.googleapis.com/oauth2/v1';
$userInfo = $client->api('userinfo', 'GET');
```


Predefined auth clients
-----------------------

This extension provides the list of ready to use auth clients, which covers most
151
popular external authentication providers. These clients are located under `yii\authclient\clients`
152 153 154
namespace.

Following predefined auth clients are available:
155 156 157 158 159 160 161 162 163 164
 - [[yii\authclient\clients\Facebook]] - [Facebook](https://www.facebook.com/) OAuth2 client.
 - [[yii\authclient\clients\GitHub]] - [GitHub](https://github.com/) OAuth2 client.
 - [[yii\authclient\clients\GoogleOAuth]] - [Google](https://www.google.com/) OAuth2 client.
 - [[yii\authclient\clients\GoogleOpenId]] - [Google](https://www.google.com/) OpenID client.
 - [[yii\authclient\clients\LinkedIn]] - [LinkedIn](http://www.linkedin.com/) OAuth2 client.
 - [[yii\authclient\clients\Live]] - [Microsoft Live](http://live.com/) OAuth2 client.
 - [[yii\authclient\clients\Twitter]] - [Twitter](https://twitter.com/) OAuth1 client.
 - [[yii\authclient\clients\VKontakte]] - [VKontakte](http://vk.com/) OAuth2 client.
 - [[yii\authclient\clients\YandexOAuth]] - [Yandex](http://www.yandex.ru/) OAuth2 client.
 - [[yii\authclient\clients\YandexOpenId]] - [Yandex](http://www.yandex.ru/) OpenID client.
165 166 167 168

Please, refer to the particular client class documentation for its actual usage.


Klimov Paul committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
Customize auth clients
----------------------

All predefined auth clients have a default configuration like `authUrl`, `apiBaseUrl` and so on.
However in some cases you may want to change these values in order to achieve some specific results.
For example: using `yii\authclient\clients\Facebook` you may want the auth window appear in popup display
mode, which is setup via `authUrl`:

```php
'components' => [
    'authClientCollection' => [
        'class' => 'yii\authclient\Collection',
        'clients' => [
            'facebook' => [
                'class' => 'yii\authclient\clients\Facebook',
                // Facebook login form will be displayed in 'popup' mode
                'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
                'clientId' => 'facebook_client_id',
                'clientSecret' => 'facebook_client_secret',
            ],
        ],
    ]
    ...
]
```


196 197 198 199 200 201 202
Creating your own auth clients
------------------------------

You may create your own auth client for any external auth provider, which supports
OpenId or OAuth protocol. To do so, first of all, you need to find out which protocol is
supported by the external auth provider, this will give you the name of the base class
for your extension:
203 204 205 206

 - For OAuth 2 use [[yii\authclient\OAuth2]].
 - For OAuth 1/1.0a use [[yii\authclient\OAuth1]].
 - For OpenID use [[yii\authclient\OpenId]].
207 208 209 210

At this stage you can determine auth client default name, title and view options, declaring
corresponding methods:

Klimov Paul committed
211
```php
212 213 214 215
use yii\authclient\OAuth2;

class MyAuthClient extends OAuth2
{
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    protected function defaultName()
    {
        return 'my_auth_client';
    }

    protected function defaultTitle()
    {
        return 'My Auth Client';
    }

    protected function defaultViewOptions()
    {
        return [
            'popupWidth' => 800,
            'popupHeight' => 500,
        ];
    }
233 234 235 236 237
}
```

Depending on actual base class, you will need to redeclare different fields and methods.

238
### [[yii\authclient\OpenId]]
239

240
All you need is to specify auth URL, by redeclaring `authUrl` field.
241 242 243
You may also setup default required and/or optional attributes.
For example:

Klimov Paul committed
244
```php
245 246 247 248
use yii\authclient\OpenId;

class MyAuthClient extends OpenId
{
249
    public $authUrl = 'https://www.my.com/openid/';
250

251 252 253
    public $requiredAttributes = [
        'contact/email',
    ];
254

255 256 257 258
    public $optionalAttributes = [
        'namePerson/first',
        'namePerson/last',
    ];
259 260 261
}
```

262
### [[yii\authclient\OAuth2]]
263 264

You will need to specify:
265 266 267 268 269

- Auth URL by redeclaring `authUrl` field.
- Token request URL by redeclaring `tokenUrl` field.
- API base URL by redeclaring `apiBaseUrl` field.
- User attribute fetching strategy by redeclaring `initUserAttributes()` method.
270 271 272

For example:

Klimov Paul committed
273
```php
274 275 276 277
use yii\authclient\OAuth2;

class MyAuthClient extends OAuth2
{
278
    public $authUrl = 'https://www.my.com/oauth2/auth';
279

280
    public $tokenUrl = 'https://www.my.com/oauth2/token';
281

282
    public $apiBaseUrl = 'https://www.my.com/apis/oauth2/v1';
283

284 285 286 287
    protected function initUserAttributes()
    {
        return $this->api('userinfo', 'GET');
    }
288 289 290 291 292
}
```

You may also specify default auth scopes.

293 294
> Note: Some OAuth providers may not follow OAuth standards clearly, introducing
  differences, and may require additional efforts to implement clients for.
295

296
### [[yii\authclient\OAuth1]]
297 298

You will need to specify:
299 300 301 302 303 304

- Auth URL by redeclaring `authUrl` field.
- Request token URL by redeclaring `requestTokenUrl` field.
- Access token URL by redeclaring `accessTokenUrl` field.
- API base URL by redeclaring `apiBaseUrl` field.
- User attribute fetching strategy by redeclaring `initUserAttributes()` method.
305 306 307

For example:

Klimov Paul committed
308
```php
309 310 311 312
use yii\authclient\OAuth1;

class MyAuthClient extends OAuth1
{
313
    public $authUrl = 'https://www.my.com/oauth/auth';
314

315
    public $requestTokenUrl = 'https://www.my.com/oauth/request_token';
316

317
    public $accessTokenUrl = 'https://www.my.com/oauth/access_token';
318

319
    public $apiBaseUrl = 'https://www.my.com/apis/oauth/v1';
320

321 322 323 324
    protected function initUserAttributes()
    {
        return $this->api('userinfo', 'GET');
    }
325 326 327 328 329
}
```

You may also specify default auth scopes.

330 331 332
> Note: Some OAuth providers may not follow OAuth standards clearly, introducing
  differences, and may require additional efforts to implement clients for.