如何使用Laravel和Passport登录用户

时间:2018-09-12 09:13:23

标签: php laravel

我必须为课程做一份工作。我必须尝试为Laravel创建Rest API。为此,我安装了Passport。

我遵循了互联网上的一些教程,并在我的Auth / LoginController中实现了登录功能

public function login(Request $request)
{
    $this->validateLogin($request);

    if ($this->attemptLogin($request)) {
        $user = Auth::user();
        $success['token'] = $user->createToken('auth')->accessToken;
        $success['user'] = $user;
        return response()->json($success, 201);
    }

    return $this->sendFailedLoginResponse($request);
}

我与Postman进行了测试,一切似乎都可以正常进行。以及我的注销功能

public function logout()
{
    $user = Auth::user();
    $user->token()->revoke();
    $user->token()->delete();

    return response()->json(null, 204);
}

现在,我尝试将其集成到前端。

我可以使用Laravel的基本登录表单进行连接。只有他将我重定向到我的login()函数的json。

当我刷新页面时,它会将我重定向到仪表板(这是我连接良好)。在我的数据库中,令牌创建得很好。

如何使用基本的Laravel身份验证来使用Passport,或者我不了解某些内容?

2 个答案:

答案 0 :(得分:0)

// When you make login request, basically u r making a post request, 
// But when u refresh the page, get request is made

So, to go to dashboard page on login success, you must redirect to dashboard page
on login attempt success, e.g

enter code here// use Auth attempt to login with the provided credentials

// if get success redirect to the dashboard
public function login(Request $request) {
    $this->validateLogin($request);

    if ($this->attemptLogin($request)) {
        $user = Auth::user();
        $success['token'] = $user->createToken('auth')->accessToken;
        $success['user'] = $user;

        // return response()->json($success, 201);
        return redirect('/dashboard'); // your dashboard path
    }

    return $this->sendFailedLoginResponse($request);
}

Hope it works...

答案 1 :(得分:0)

安装passport后。
您可以按照以下代码进行操作

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);

        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();

        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;

        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addDays(5);
        $token->save();

        return response()->json([
            'token' => $tokenResult->accessToken,
            'user' => auth()->user(),
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

要注销,您必须在api路由中设置注销路由-

Route::group(['middleware' => 'auth:api'], function () {
        Route::post('logout','UserController@logout');
});

然后在身份验证控制器中使用注销功能

     /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout()
    {
        auth()->user()->tokens->each(function ($token, $key) {
            $token->delete();
        });

        return response()->json('Logged out successfully', 200);
    }