LoginSignup
3
2

More than 1 year has passed since last update.

Laravelで認証・認可処理の諸々実装

Last updated at Posted at 2021-08-01

はじめに  

認証・認可関係の処理を実装した際の諸々をメモ。
細かい説明は抜きでとりあえず動く部分のみ書いてます。

  • やったこと  

    • 未認証の場合ログイン画面に遷移させる  
    • ログイン後、再びログイン画面にいくと特定の画面にリダイレクトさせる
    • ログイン後の遷移先を設定
    • 権限によってアクセス制限を行う

1. 未認証の場合ログイン画面に遷移させる

ルーティングでミドルウェアを通します。


Route::middleware('auth')->group(function (){
    Route::get('/', [Controllers\StudentsController::class, 'show'])->name('top');
});

ログインしていないとき、'/'にアクセスするとログイン画面に飛ばされます。

2. ログイン後、再びログイン画面にいくと特定の画面にリダイレクトさせる

仮定として、usersテーブルにはroleカラムがあり、1or2の数字を権限として与えます。

ミドルウェアのRedirectIfAuthenticated.phpをいじっていきます。

//省略    
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                if(Auth::user()->role==1){
                    return redirect('/home1');
                }elseif(Auth::user()->role==2){
                    return redirect('/home2');
                }
            }
        }
        return $next($request);
    }
  • 説明

ログイン後のリダイレクト画面の設定をしています。

        if(Auth::user()->role==1){
            return redirect('/home1');
        }elseif(Auth::user()->role==2){
            return redirect('/home2');
        }

ここでログインしているユーザーのroleがどれか確認しています。
roleが1であれば/home1へリダイレクトしています。
roleが2であれば/home2へリダイレクトしています。
(他に良い方法があればご指摘くださいっ。)

その他RedirectIfAuthenticated.phpに関する処理で気になる部分がある方はこちらの記事に詳しく書かれていました。

【Laravel】Closure $next, ...$guardsとは?

ちなみにログイン後の遷移先はLoginController.phpに同様な処理を追加しました。

//省略
    public function authenticated(Request $request, $user)
    {
        if(Auth::user()->role==1){
            return redirect('/home1');
        }elseif(Auth::user()->role==2){
            return redirect('/home2');
        }
    }

3. 権限によってアクセス制限を行う

Gateの機能を使用。プロバイダーのAuthServiceProvider.phpに以下を追記。

//省略
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('admin',function ($user){
            return($user->role == 1);
        });

        Gate::define('teacher',function ($user){
            return($user->role == 2);
        });
    }

そしてルーティングでミドルウェアを通します。

Route::middleware(['can:admin','auth'])->group(function (){
    Route::get('/', [Controllers\StudentsController::class, 'show'])->name('top');
});

middleware('can:admin')と記載することで権限がadmin、つまりroleが1のユーザーだけが'/'画面に遷移できます。
それ以外のユーザーには403エラーが返されます。

おわりに

探り探りで初めての実装もりもりでしたがとりあえず想定通りの動きはできました・・・。
細かい部分の処理を見ていかないと、どのように認証が行われているか理解が難しいですね。。
動きだけでもどこか参考になれば幸いでございます。
(もっとこうしたほうが良いなどあればご指摘お願いします!)

以上!

3
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2