laravel自定义身份验证-try(),会话

时间:2019-02-11 10:51:04

标签: laravel authentication

我正在学习如何创建自定义身份验证系统。我创建了自己的后卫球员。在我的测试函数中,我使用usimg try()对用户进行身份验证。检查通过。然后,我创建了test2方法,该方法仅适用于登录用户。

我的路线是:

Route::get('test', 'MyController@test');
Route::get('test2', 'MyController@test2')->middleware('auth');

我的控制器是:

class MyController extends Controller
{
    public function test()
    {
        $cr = ['name' => 'pl', 'password' => 'pl'];

        if (Auth::guard('player')->attempt($cr)) {
            $user = Auth::guard('player')->user();
            return 'ok';
        }

        return 'not found';
    }

    public function test2()
    {
        return 'test2';
    }
}

我的后卫配置是:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'player' => [
            'driver' => 'session',
            'provider' => 'player',
        ],

        'club' => [
            'driver' => 'session',
            'provider' => 'club',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'player' => [
            'driver' => 'eloquent',
            'model' => App\Player::class,
        ],

        'club' => [
            'driver' => 'eloquent',
            'model' => App\Club::class,
        ],
    ],

我想在执行测试功能后手动访问test2路由(而不是通过重定向),但是我不能。我收到Auth默认登录表单。

我应该编写自己的中间件还是手动设置会话?请帮忙。

2 个答案:

答案 0 :(得分:0)

我建议您这样做可以解决这个问题!

public function test()
{
    $cr = ['name' => 'pl', 'password' => 'pl'];

    if (Auth::guard('player')->attempt($cr)) {
        $user = Auth::guard('player')->user();
        return 'ok';
redirect("test2(view)");
    }

答案 1 :(得分:0)

您需要编写自己的中间件,

<?php

namespace App\Http\Middleware;

use Closure;

class RedirectIfNotPlayer
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = 'player')
    {
        if(!auth()->guard($guard)->check()) {
            return redirect(url('/player/login'));
        }

        return $next($request);

    }
}

将此中间件添加到kernel.php内的routeMiddleware文件中,

'player' => \App\Http\Middleware\RedirectIfNotPlayer::class,

然后您可以在路由中使用中间件

Route::get('test2', 'MyController@test2')->middleware('player');