yii2
Yii2 OAuth2 - Ex: consument facebook OAuth2
Zoeken…
Maak een app op Facebook-ontwikkelaar
Ga naar de [ https://developers.facebook.com/Buch(https://developers.facebook.com/) en maak uw app.
Klik op Add product
en kies Facebook Login
Installeer yii2-authclient
Voordat u deze extensie installeert, moet u yii2-app installeren. In dit voorbeeld gebruik ik yii2-basissjabloon. Handleiding voor installatie hier .
Rennen
composer require --prefer-dist yiisoft/yii2-authclient
of voeg toe
"yiisoft/yii2-authclient": "~2.1.0"
naar het require
gedeelte van je composer.json
.
Voeg config authClientCollection
aan uw config components
:
return [
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => 'facebook_client_id',
'clientSecret' => 'facebook_client_secret',
],
],
]
],
// ...
];
facebook_client_id
is applicatie-ID en facebook_client_secret
is app-geheim.
Auth-actie toevoegen en callback instellen
- Knop Toevoegen
Login as facebook account
aan uw aanmeldingsweergave:
Bewerk site/login.php
in views map, voeg deze regel toe aan de inhoud van de pagina login:
<?= yii\authclient\widgets\AuthChoice::widget([ 'baseAuthUrl' => ['site/auth'], 'popupMode' => false, ]) ?>
Hierboven hebben we ingesteld dat auth
actie in SiteController
OAuth2-stroom afhandelt.
Nu maken we het.
class SiteController extends Controller
{
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'onAuthSuccess'],
],
];
}
public function onAuthSuccess($client)
{
// do many stuff here, save user info to your app database
}
}
We gebruiken yii\authclient\AuthAction
voor het maken van een URL en omleiden naar de Facebook-inlogpagina.
Functie onAuthSuccess
gebruikt om gebruikersinfo te krijgen, log in op uw app.
Voeg redirect_url toe aan de app-instelling van Facebook
Als u prettyUrl inschakelt in uw yii2-app, is uw redirect_uri:
http://<base_url>/web/site/auth
En schakel mooie url uit:
http://<base_url>/web/index.php?r=site%2Fauth
Voorbeeld:
Voorbeeld voor de functie onAuthSuccess
/**
* @param $client ClientInterface
*/
public function onAuthSuccess($client)
{
//Get user info
/** @var array $attributes */
$attributes = $client->getUserAttributes();
$email = ArrayHelper::getValue($attributes, 'email'); //email info
$id = ArrayHelper::getValue($attributes, 'id'); // id facebook user
$name = ArrayHelper::getValue($attributes, 'name'); // name facebook account
//Login user
//For demo, I will login with admin/admin default account
$admin = User::findByUsername('admin');
Yii::$app->user->login($admin);
}