首页 > 解决方案 > 我只能在我 auth()->login() 的方法中访问我的 auth()->user() 而不能在同一个控制器中访问其他方法

问题描述

我正在尝试在新控制器中使用护照实现我自己的登录/注销。

class AuthController extends AccessTokenController
{
    use AuthenticatesUsers;
.
.

我的登录方法工作正常:

public function login(ServerRequestInterface $request)
    {
        if (!auth()->attempt([
            'email' => $request->getParsedBody()['email'],
            'password' => $request->getParsedBody()['password']
        ])) {
            return response()->json('failed attempt...');
        }
        auth()->login(User::where('id', Auth::user()->id)->first());
        .
        .
        // I can access auth()->user() here just fine ..
    }

但是我无法在注销方法中访问经过身份验证的用户,因此我可以获取他的令牌并删除它们。

public function logout()
    {
        //I can't access the authenticated user here
        return auth()->user();

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

我究竟做错了什么?注意:我在登录方法中省略了与颁发令牌相关的任何内容,因为它与问题无关。

更新:我的路线/api.php

Route::post('register', 'Auth\RegisterController@register');
Route::post('login', 'Auth\AuthController@login');
Route::post('logout', 'Auth\AuthController@logout');

标签: laravel

解决方案


如果您正在使用,api那么您应该发送authorization header否则它应该适用于session基于authentication

然后您可以使用请求访问经过身份验证的用户

public function logout(Request $request)
{
  return $request->user(); //the user that made the request (the authenticated user)
}

或者:

public function logout(Request $request)
{
   return Auth::user(); //the user that made the request (the authenticated user)
}

推荐阅读