b0f143c3
Yarik
first commit
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
|
Yii2 EAuth extension
====================
EAuth extension allows to authenticate users with accounts on other websites.
Supported protocols: OpenID, OAuth 1.0 and OAuth 2.0.
EAuth is an extension to provide a unified (does not depend on the selected service) method to authenticate the user. The extension itself does not perform login, does not register the user and does not bind the user accounts from different providers.
* [Demo](http://nodge.ru/yii-eauth/demo2/)
* [Demo project](https://github.com/Nodge/yii2-eauth-demo/)
* [Installation](#installation)
* [Version for yii 1.1](https://github.com/Nodge/yii-eauth/)
### Why own extension and not a third-party service?
The implementation of the authorization on your own server has several advantages:
* Full control over the process: What will be written in the authorization window, what data we get, etc.
* Ability to change the appearance of the widget.
* When logging in via OAuth, it is possible to invoke methods on the API.
* Fewer dependencies on third-party services - more reliable application.
### The extension allows you to:
* Ignore the nuances of authorization through the different types of services and use the class based adapters for each service.
* Get a unique user ID that can be used to register the user in your application.
* Extend the standard authorization classes to obtain additional data about the user.
* Work with the API of social networks by extending the authorization classes.
* Set up a list of supported services, customize the appearance of the widget, use the popup window without closing your application.
### Extension includes:
* The component that contains utility functions.
* A widget that displays a list of services in the form of icons and allowing authorization in the popup window.
* Base classes to create your own services.
* Ready to authenticate via Google, Twitter, Facebook and other providers.
### Included services:
* OpenID:
* Yahoo
* Steam
* OAuth1:
* Twitter
* LinkedIn
* OAuth2:
* Google
* Facebook
* Live
* GitHub
* LinkedIn
* Instagram
* Yandex (ru)
* VKontake (ru)
* Mail.ru (ru)
* Odnoklassniki (ru)
### Resources
* [Yii EAuth](https://github.com/Nodge/yii2-eauth)
* [Demo](http://nodge.ru/yii-eauth/demo2/)
* [Demo project](https://github.com/Nodge/yii2-eauth-demo/)
* [Yii Framework](http://yiiframework.com/)
* [OpenID](http://openid.net/)
* [OAuth](http://oauth.net/)
* [OAuth 2.0](http://oauth.net/2/)
* [LightOpenID](https://github.com/iignatov/LightOpenID)
* [PHPoAuthLib](https://github.com/Lusitanian/PHPoAuthLib)
### Requirements
* Yii 2.0 or above
* curl php extension
* LightOpenId
* PHPoAuthLib
# Installation
This library can be found on [Packagist](https://packagist.org/packages/nodge/yii2-eauth).
The recommended way to install this is through [composer](http://getcomposer.org).
Edit your `composer.json` and add:
```json
{
"require": {
"nodge/yii2-eauth": "~2.0"
}
}
```
And install dependencies:
```bash
$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar install
```
# Usage
## Demo project
The source code of the [demo](http://nodge.ru/yii-eauth/demo2/) is available [here](https://github.com/Nodge/yii2-eauth-demo/).
## Basic setup
### Configuration
Add the following in your config:
```php
<?php
...
'components' => [
'eauth' => [
'class' => 'nodge\eauth\EAuth',
'popup' => true, // Use the popup window instead of redirecting.
'cache' => false, // Cache component name or false to disable cache. Defaults to 'cache' on production environments.
'cacheExpire' => 0, // Cache lifetime. Defaults to 0 - means unlimited.
'httpClient' => [
// uncomment this to use streams in safe_mode
//'useStreamsFallback' => true,
],
'services' => [ // You can change the providers and their classes.
'google' => [
// register your app here: https://code.google.com/apis/console/
'class' => 'nodge\eauth\services\GoogleOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'title' => 'Google',
],
'twitter' => [
// register your app here: https://dev.twitter.com/apps/new
'class' => 'nodge\eauth\services\TwitterOAuth1Service',
'key' => '...',
'secret' => '...',
],
'yandex' => [
// register your app here: https://oauth.yandex.ru/client/my
'class' => 'nodge\eauth\services\YandexOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'title' => 'Yandex',
],
'facebook' => [
// register your app here: https://developers.facebook.com/apps/
'class' => 'nodge\eauth\services\FacebookOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'yahoo' => [
'class' => 'nodge\eauth\services\YahooOpenIDService',
//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
],
'linkedin' => [
// register your app here: https://www.linkedin.com/secure/developer
'class' => 'nodge\eauth\services\LinkedinOAuth1Service',
'key' => '...',
'secret' => '...',
'title' => 'LinkedIn (OAuth1)',
],
'linkedin_oauth2' => [
// register your app here: https://www.linkedin.com/secure/developer
'class' => 'nodge\eauth\services\LinkedinOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'title' => 'LinkedIn (OAuth2)',
],
'github' => [
// register your app here: https://github.com/settings/applications
'class' => 'nodge\eauth\services\GitHubOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'live' => [
// register your app here: https://account.live.com/developers/applications/index
'class' => 'nodge\eauth\services\LiveOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'steam' => [
'class' => 'nodge\eauth\services\SteamOpenIDService',
//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
],
'instagram' => [
// register your app here: https://instagram.com/developer/register/
'class' => 'nodge\eauth\services\InstagramOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'vkontakte' => [
// register your app here: https://vk.com/editapp?act=create&site=1
'class' => 'nodge\eauth\services\VKontakteOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'mailru' => [
// register your app here: http://api.mail.ru/sites/my/add
'class' => 'nodge\eauth\services\MailruOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
],
'odnoklassniki' => [
// register your app here: http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=13992188
// ... or here: http://www.odnoklassniki.ru/dk?st.cmd=appsInfoMyDevList&st._aid=Apps_Info_MyDev
'class' => 'nodge\eauth\services\OdnoklassnikiOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'clientPublic' => '...',
'title' => 'Odnoklas.',
],
],
],
'i18n' => [
'translations' => [
'eauth' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@eauth/messages',
],
],
],
// (optionally) you can configure pretty urls
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'login/<service:google|facebook|etc>' => 'site/login',
],
],
// (optionally) you can configure logging
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'logFile' => '@app/runtime/logs/eauth.log',
'categories' => ['nodge\eauth\*'],
'logVars' => [],
],
],
],
...
],
...
```
### User model
You need to modify your User model to login with EAuth services.
Example from demo project:
```php
<?php
...
/**
* @var array EAuth attributes
*/
public $profile;
public static function findIdentity($id) {
if (Yii::$app->getSession()->has('user-'.$id)) {
return new self(Yii::$app->getSession()->get('user-'.$id));
}
else {
return isset(self::$users[$id]) ? new self(self::$users[$id]) : null;
}
}
/**
* @param \nodge\eauth\ServiceBase $service
* @return User
* @throws ErrorException
*/
public static function findByEAuth($service) {
if (!$service->getIsAuthenticated()) {
throw new ErrorException('EAuth user should be authenticated before creating identity.');
}
$id = $service->getServiceName().'-'.$service->getId();
$attributes = [
'id' => $id,
'username' => $service->getAttribute('name'),
'authKey' => md5($id),
'profile' => $service->getAttributes(),
];
$attributes['profile']['service'] = $service->getServiceName();
Yii::$app->getSession()->set('user-'.$id, $attributes);
return new self($attributes);
}
...
```
Then you can access to EAuth attributes through:
```php
<?php
$identity = Yii::$app->getUser()->getIdentity();
if (isset($identity->profile)) {
VarDumper::dump($identity->profile, 10, true);
}
```
### Controller
Attach OpenID Controller behavior to disable CSRF validation for OpenID callbacks.
Or you can disable CSRF validation by yourself.
```php
<?php
...
public function behaviors() {
return [
'eauth' => [
// required to disable csrf validation on OpenID requests
'class' => \nodge\eauth\openid\ControllerBehavior::className(),
'only' => ['login'],
],
];
}
...
```
Add the following to your Login action:
```php
<?php
...
public function actionLogin() {
$serviceName = Yii::$app->getRequest()->getQueryParam('service');
if (isset($serviceName)) {
/** @var $eauth \nodge\eauth\ServiceBase */
$eauth = Yii::$app->get('eauth')->getIdentity($serviceName);
$eauth->setRedirectUrl(Yii::$app->getUser()->getReturnUrl());
$eauth->setCancelUrl(Yii::$app->getUrlManager()->createAbsoluteUrl('site/login'));
try {
if ($eauth->authenticate()) {
// var_dump($eauth->getIsAuthenticated(), $eauth->getAttributes()); exit;
$identity = User::findByEAuth($eauth);
Yii::$app->getUser()->login($identity);
// special redirect with closing popup window
$eauth->redirect();
}
else {
// close popup window and redirect to cancelUrl
$eauth->cancel();
}
}
catch (\nodge\eauth\ErrorException $e) {
// save error to show it later
Yii::$app->getSession()->setFlash('error', 'EAuthException: '.$e->getMessage());
// close popup window and redirect to cancelUrl
// $eauth->cancel();
$eauth->redirect($eauth->getCancelUrl());
}
}
// default authorization code through login/password ..
}
...
```
### View
```php
...
<?php
if (Yii::$app->getSession()->hasFlash('error')) {
echo '<div class="alert alert-danger">'.Yii::$app->getSession()->getFlash('error').'</div>';
}
?>
...
<p class="lead">Do you already have an account on one of these sites? Click the logo to log in with it here:</p>
<?php echo \nodge\eauth\Widget::widget(['action' => 'site/login']); ?>
...
```
## Extending
To receive all the necessary data to your application, you can override the base class of any provider.
Base classes are stored in `@eauth/src/services`.
Examples of extended classes can be found in `@eauth/src/services/extended/`.
After overriding the base class, you need to update your configuration file with a new class name.
## Working with OAuth API
You can extend base classes with necessary methods and then write something like this:
```php
<?php
/** @var $eauth EAuthServiceBase */
$eauth = Yii::$app->eauth->getIdentity('facebook');
// to get protected resources user should be authenticated:
if ($eauth->getIsAuthenticated()) {
$eauth->callProtectedApiMethod();
$eauth->callAnotherProtectedApiMethod();
}
// or you can get public resources at any time:
$eauth->callPublicApiMethod();
$eauth->callAnotherPublicApiMethod();
```
Example of an API call method:
```php
<?php
class FacebookOAuth2Service extends \nodge\eauth\services\FacebookOAuth2Service
{
public function fooApiMethod($bar) {
$api_method = 'me'; // ex. for Facebook this results to https://graph.facebook.com/me
// get protected resource
$response = $this->makeSignedRequest($api_method, [
'query' => [ 'foo' => 'bar' ], // GET arguments
'data' => [ 'foo' => 'bar' ], // POST arguments
'headers' => [ 'X-Foo' => 'bar' ], // Extra HTTP headers
]);
// you can get public resources with the same API:
//$response = $this->makeRequest($api_method, $options);
// process $response
$data = process($response);
// return results
return $data;
}
}
```
API calls are performed if the current user has a valid access token (saved during the authentication).
You can save access_token to your database by using custom token storage in your config:
```php
<?php
...
'components' => [
'eauth' => [
'class' => 'nodge\eauth\EAuth',
'tokenStorage' => [
'class' => '@app\eauth\DatabaseTokenStorage',
],
],
...
],
...
```
## Translation
To use translations, add the following in your config:
```php
<?php
...
'components' => [
'i18n' => [
'translations' => [
'eauth' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@eauth/messages',
],
],
],
...
],
...
```
Available translations can be found in `@eauth/src/messages`.
# License
The extension was released under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php), so you'll find the latest version on [GitHub](https://github.com/Nodge/yii2-eauth).
|