【Laravel】認証(Auth)
参考
https://qiita.com/darum/items/82f5b0ab83f175c45687
25.4.14 カスタムガード
Laravelの認証状態の判定、ログインユーザーの指定方法を自前で定義できるようにカスタムするための仕組み
\Auth::check()などで真偽値が返ってくるのは、ガードが動いているから。
デフォルトのガード
code:php
// config/auth.php
'guards' => [
'web' => [
'driver' => 'session', // ← 標準ガード
'provider' => 'users',
],
],
driverの部分でガードを指定する
デフォルトは、Illuminate\Auth\SessionGuard
カスタムする場合の流れ
Guardクラスを用意する
Illuminate\Contrrancts\Auth\Guardを設計する
code:php
interface Illuminate\Contracts\Auth\Guard {
public function check();
public function guest();
public function user();
public function id();
public function validate(array $credentials = []);
public function setUser(Authenticatable $user);
public function hasUser();
}
AuthServiceProviderに登録
config:auth.phpに設定
Guardクラスを用意する | Illuminate\Contrrancts\Auth\Guardを設計する
app/app/Services/Auth/SampleGuard.phpという感じで用意する
上の要件を満たすよう、自作クラスに定義しておく
code:php
class SampleGuard implements Guard {
... // checkとかguestとか、呼ばれた時の処理を書く
AuthServiceProviderに登録
ポリシーの登録・ガードやプロバイダの追加ができる
自作したガードを登録しよう
code:php
Auth::extend('sample', function ($app, $name, array $config) {
return new \...\SampleGuard(
Auth::createUserProvider($config'provider'),
$app'request'
);
});
config:auth.phpに設定
code:php
'guards' => [
// デフォルトのsessionガード
'web' => [
'driver' => 'session',
'provider' => 'users',
],
// ★ カスタムガードの定義
'guard_sample' => [
'driver' => 'sample', // ← Auth::extend() で登録した名前
'provider' => 'users',
],
],
これで自作ガードから、check()の処理などを呼ぶことができるようになるわけだ
\Auth::guard('sample')->check();
デフォルトで呼びたいならデフォルトで指定する感じ