質問編集履歴

2 localhost/public/master -> localhost/master に記載変更しました。

aoki_monpro

aoki_monpro score 45

2019/03/07 09:19  投稿

laravel5.5 マルチ認証でログインができない
これらの記事を参考に、マルチ認証を実装したく、
[https://takahashi-it.com/php/laravel54-multi-auth/](https://takahashi-it.com/php/laravel54-multi-auth/)
[https://qiita.com/s_of_p/items/3c066f56123cb05a24f1](https://qiita.com/s_of_p/items/3c066f56123cb05a24f1)
php artisan make:auth で userを作成後、
tinkerで masterユーザー作成し、
http://localhost/newbook/public/master/login にアクセスし、ログインしようとするものの、
http://localhost/newbook/public/master/home にリダイレクトがかかりません。
http://localhost/newbook/master/login にアクセスし、ログインしようとするものの、
http://localhost/newbook/master/home にリダイレクトがかかりません。
どこかの記載が足りないと思うのですが検討つかず・・
お手数ですがアドバイスいただけませんでしょうか。
環境:laravel 5.5
```php
//config/auth.php
<?php
return [
   'defaults' => [
       'guard' => 'user',
       'passwords' => 'users',
   ],
   'guards' => [
       'web' => [
           'driver' => 'session',
           'provider' => 'users',
       ],
       'api' => [
           'driver' => 'token',
           'provider' => 'users',
       ],
       'user' => [
           'driver' => 'session',
           'provider' => 'users',
       ],
       'manage' => [
           'driver' => 'session',
           'provider' => 'manages',
       ],
       'master' => [
           'driver' => 'session',
           'provider' => 'master',
       ],
   ],
   'providers' => [
       'users' => [
           'driver' => 'eloquent',
           'model' => App\User::class,
       ],
       'manages' => [
           'driver' => 'eloquent',
           'model' => App\Models\Manage::class,
       ],
       'master' => [
           'driver' => 'eloquent',
           'model' => App\Models\Master::class,
       ],
       // 'users' => [
       //    'driver' => 'database',
       //    'table' => 'users',
       // ],
   ],
   'passwords' => [
       'users' => [
           'provider' => 'users',
           'table' => 'password_resets',
           'expire' => 60,
       ],
       'manages' => [
           'provider' => 'manages',
           'table' => 'password_resets',
           'expire' => 60,
       ],
       'master' => [
           'provider' => 'master',
           'table' => 'password_resets',
           'expire' => 60,
       ],
   ],
];
```
```php
//app/Exceptions/Handler.php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
  //略
    /**
    * 認証していない場合にガードを見てそれぞれのログインページへ飛ばず
    *
    * @param \Illuminate\Http\Request $request
    * @param AuthenticationException $exception
    * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
    */
   public function unauthenticated($request, AuthenticationException $exception)
   {
       if($request->expectsJson()){
           return response()->json(['error' => 'Unauthenticated.'], 401);
       }
       if (in_array('master', $exception->guards(), true)) {
           return redirect()->guest(route('master.login'));
       }
       return redirect()->guest(route('login'));
   }
}
```
```php
//web.php
/*
|--------------------------------------------------------------------------
| Master without auth
|--------------------------------------------------------------------------
*/
Route::group(['prefix' => 'master'], function() {
   Route::get('/',        function () { return redirect('/master/home'); });
   Route::get('login',    'Master\LoginController@showLoginForm')->name('master.login');
   Route::post('login',   'Master\LoginController@login')->name('master.login');
});
/*
|--------------------------------------------------------------------------
| Master with auth
|--------------------------------------------------------------------------
*/
Route::group(['prefix' => 'master', 'middleware' => 'auth:master'], function() {
   Route::post('logout',  'Master\LoginController@logout')->name('master.logout');
   Route::get('home',     'Master\HomeController@index')->name('master.home');
});
```
```php
//App/Models/Master.php
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Master extends Authenticatable
{
   use Notifiable;
   protected $table = 'masters';
   public $timestamps = false;
   public $incrementing = false;
   protected $fillable = [
       'name', 'email', 'password',
   ];
   protected $hidden = [
       'password', 'remember_token',
   ];
}
```
```php
//App/Http/Controller/Master/LoginController.php
<?php
namespace App\Http\Controllers\Master;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
   use AuthenticatesUsers;
   protected $redirectTo = 'master/home';
   public function __construct()
   {
       $this->middleware('guest:master')->except('logout');
   }
   public function showLoginForm()
   {
       return view('master.login'); //管理者ログインページのテンプレート
   }
   protected function guard()
   {
       return Auth::guard('master'); //管理者認証のguardを指定
   }
   public function logout(Request $request)
   {
       Auth::guard('master')->logout();
       $request->session()->flush();
       $request->session()->regenerate();
       return redirect('master.login');
   }
}
```
```php
//App/Http/Controller/Master/HomeController.php
<?php
namespace App\Http\Controllers\Master;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
   public function __construct() // guard setting is set to route.php. This construct is to make sure.
   {
       $this->middleware('auth:master');
   }
   public function index()
   {
       return view('master.home');
   }
}
```
```php
//views/master/login.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
   <!-- 抜粋 -->
   
   <form class="form-horizontal" method="POST" action="{{ route('master.login') }}">
   {{ csrf_field() }}
   <div class="columns is-mobile is-centered">
   <div class="column is-half">
   Master/login
   <div class="field">
   <label class="label">Email</label>
   <div class="control has-icons-left has-icons-right">
       <input id="email" type="email" class="input is-danger" name="email" type="email" placeholder="Email input" value="{{ old('email') }}">
       <span class="icon is-small is-left">
       <i class="fas fa-envelope"></i>
       </span>
       <span class="icon is-small is-right">
       <i class="fas fa-exclamation-triangle"></i>
       </span>
   </div>
   <p class="help is-danger">This email is invalid</p>
   </div>
   <div class="field">
   <label class="label">Password</label>
   <div class="control">
       <input id="password" type="password" class="input" name="password" required>
       @if ($errors->has('password'))
       <span class="help-block">
       <strong>{{ $errors->first('password') }}</strong>
       </span>
       @endif
   </div>
   </div>
   <div class="field">
   <div class="control">
       <label class="checkbox">
       <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}>
       Remember Me
       </label>
   </div>
   </div>
   <div class="field is-grouped">
       <div class="control">
           <button type="submit" class="button is-link">Login</button>
       </div>
   </div>
   </div>
   </div>
   
   </form>
   </div><!-- container -->
</div>
   <!-- Scripts -->
   <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
```
```php
views/master/home.blade.php
@extends('layouts.app_master')
@section('content')
<div class="container">
   <div class="row">
       <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
               <div class="panel-heading">Dashboard</div>
               <div class="panel-body">
                   @if (session('status'))
                       <div class="alert alert-success">
                           {{ session('status') }}
                       </div>
                   @endif
                   You are logged in!
               </div>
           </div>
       </div>
   </div>
</div>
@endsection
```
  • Laravel

    5105 questions

    LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

1 Handler のreturn内を master/login → master.login に修正しました。

aoki_monpro

aoki_monpro score 45

2019/03/06 11:38  投稿

laravel5.5 マルチ認証でログインができない
これらの記事を参考に、マルチ認証を実装したく、
[https://takahashi-it.com/php/laravel54-multi-auth/](https://takahashi-it.com/php/laravel54-multi-auth/)
[https://qiita.com/s_of_p/items/3c066f56123cb05a24f1](https://qiita.com/s_of_p/items/3c066f56123cb05a24f1)
php artisan make:auth で userを作成後、
tinkerで masterユーザー作成し、
http://localhost/newbook/public/master/login にアクセスし、ログインしようとするものの、
http://localhost/newbook/public/master/home にリダイレクトがかかりません。
どこかの記載が足りないと思うのですが検討つかず・・
お手数ですがアドバイスいただけませんでしょうか。
環境:laravel 5.5
```php
//config/auth.php
<?php
return [
   'defaults' => [
       'guard' => 'user',
       'passwords' => 'users',
   ],
   'guards' => [
       'web' => [
           'driver' => 'session',
           'provider' => 'users',
       ],
       'api' => [
           'driver' => 'token',
           'provider' => 'users',
       ],
       'user' => [
           'driver' => 'session',
           'provider' => 'users',
       ],
       'manage' => [
           'driver' => 'session',
           'provider' => 'manages',
       ],
       'master' => [
           'driver' => 'session',
           'provider' => 'master',
       ],
   ],
   'providers' => [
       'users' => [
           'driver' => 'eloquent',
           'model' => App\User::class,
       ],
       'manages' => [
           'driver' => 'eloquent',
           'model' => App\Models\Manage::class,
       ],
       'master' => [
           'driver' => 'eloquent',
           'model' => App\Models\Master::class,
       ],
       // 'users' => [
       //    'driver' => 'database',
       //    'table' => 'users',
       // ],
   ],
   'passwords' => [
       'users' => [
           'provider' => 'users',
           'table' => 'password_resets',
           'expire' => 60,
       ],
       'manages' => [
           'provider' => 'manages',
           'table' => 'password_resets',
           'expire' => 60,
       ],
       'master' => [
           'provider' => 'master',
           'table' => 'password_resets',
           'expire' => 60,
       ],
   ],
];
```
```php
//app/Exceptions/Handler.php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
  //略
    /**
    * 認証していない場合にガードを見てそれぞれのログインページへ飛ばず
    *
    * @param \Illuminate\Http\Request $request
    * @param AuthenticationException $exception
    * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
    */
   public function unauthenticated($request, AuthenticationException $exception)
   {
       if($request->expectsJson()){
           return response()->json(['error' => 'Unauthenticated.'], 401);
       }
       if (in_array('master', $exception->guards(), true)) {
           return redirect()->guest(route('master/login'));
           return redirect()->guest(route('master.login'));
       }
       return redirect()->guest(route('login'));
   }
}
```
```php
//web.php
/*
|--------------------------------------------------------------------------
| Master without auth
|--------------------------------------------------------------------------
*/
Route::group(['prefix' => 'master'], function() {
   Route::get('/',        function () { return redirect('/master/home'); });
   Route::get('login',    'Master\LoginController@showLoginForm')->name('master.login');
   Route::post('login',   'Master\LoginController@login')->name('master.login');
});
/*
|--------------------------------------------------------------------------
| Master with auth
|--------------------------------------------------------------------------
*/
Route::group(['prefix' => 'master', 'middleware' => 'auth:master'], function() {
   Route::post('logout',  'Master\LoginController@logout')->name('master.logout');
   Route::get('home',     'Master\HomeController@index')->name('master.home');
});
```
```php
//App/Models/Master.php
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Master extends Authenticatable
{
   use Notifiable;
   protected $table = 'masters';
   public $timestamps = false;
   public $incrementing = false;
   protected $fillable = [
       'name', 'email', 'password',
   ];
   protected $hidden = [
       'password', 'remember_token',
   ];
}
```
```php
//App/Http/Controller/Master/LoginController.php
<?php
namespace App\Http\Controllers\Master;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
   use AuthenticatesUsers;
   protected $redirectTo = 'master/home';
   public function __construct()
   {
       $this->middleware('guest:master')->except('logout');
   }
   public function showLoginForm()
   {
       return view('master.login'); //管理者ログインページのテンプレート
   }
   protected function guard()
   {
       return Auth::guard('master'); //管理者認証のguardを指定
   }
   public function logout(Request $request)
   {
       Auth::guard('master')->logout();
       $request->session()->flush();
       $request->session()->regenerate();
       return redirect('master.login');
   }
}
```
```php
//App/Http/Controller/Master/HomeController.php
<?php
namespace App\Http\Controllers\Master;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
   public function __construct() // guard setting is set to route.php. This construct is to make sure.
   {
       $this->middleware('auth:master');
   }
   public function index()
   {
       return view('master.home');
   }
}
```
```php
//views/master/login.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
   <!-- 抜粋 -->
   
   <form class="form-horizontal" method="POST" action="{{ route('master.login') }}">
   {{ csrf_field() }}
   <div class="columns is-mobile is-centered">
   <div class="column is-half">
   Master/login
   <div class="field">
   <label class="label">Email</label>
   <div class="control has-icons-left has-icons-right">
       <input id="email" type="email" class="input is-danger" name="email" type="email" placeholder="Email input" value="{{ old('email') }}">
       <span class="icon is-small is-left">
       <i class="fas fa-envelope"></i>
       </span>
       <span class="icon is-small is-right">
       <i class="fas fa-exclamation-triangle"></i>
       </span>
   </div>
   <p class="help is-danger">This email is invalid</p>
   </div>
   <div class="field">
   <label class="label">Password</label>
   <div class="control">
       <input id="password" type="password" class="input" name="password" required>
       @if ($errors->has('password'))
       <span class="help-block">
       <strong>{{ $errors->first('password') }}</strong>
       </span>
       @endif
   </div>
   </div>
   <div class="field">
   <div class="control">
       <label class="checkbox">
       <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}>
       Remember Me
       </label>
   </div>
   </div>
   <div class="field is-grouped">
       <div class="control">
           <button type="submit" class="button is-link">Login</button>
       </div>
   </div>
   </div>
   </div>
   
   </form>
   </div><!-- container -->
</div>
   <!-- Scripts -->
   <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
```
```php
views/master/home.blade.php
@extends('layouts.app_master')
@section('content')
<div class="container">
   <div class="row">
       <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
               <div class="panel-heading">Dashboard</div>
               <div class="panel-body">
                   @if (session('status'))
                       <div class="alert alert-success">
                           {{ session('status') }}
                       </div>
                   @endif
                   You are logged in!
               </div>
           </div>
       </div>
   </div>
</div>
@endsection
```
  • Laravel

    5105 questions

    LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る