7

我之前使用的是 Laravel 的内置 api 令牌身份验证,但我想为不同的客户端提供多个 api 令牌,并且使用 Laravel 7.x,我正在尝试迁移到 Laravel Sanctum。

API 似乎可以毫无问题地对用户进行身份验证,但是当我尝试使用 获取用户数据时Auth::user();,它返回 null。也 Auth::guard('api')->user();返回 null 。

我应该使用什么作为 Auth 守卫?还是根据提供的令牌获取用户数据的正确方法?

非常感谢....

4

8 回答 8

21

首先,通过 sanctum auth 中间件进行路由。

Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum');

然后,获取用户。

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function MyMethod(Request $request) {
        return $request->user();
    }
}

auth()->user()是一个全局助手,Auth::user()是一个支持门面,并$request->user()使用 http。你可以使用它们中的任何一个。要快速测试,请尝试

Route::get('/test', function() {
    return auth()->user();
})->middleware('auth:sanctum');

请务必在标头中发送您的令牌,如下所示:

Authorization: Bearer UserTokenHere
于 2020-07-16T20:13:14.223 回答
11

auth('sanctum')->user()->id
auth('sanctum')->check()


没有中间件,你可以使用这些。
于 2021-04-19T09:24:56.973 回答
3

当您登录用户时,在您的登录功能中使用类似这样的东西

public function login(Request $request)
{
    if(Auth::attempt($credentials))
    {
         $userid = auth()->user()->id;
    }
}

然后将此用户 ID 发送给客户端,并让它以安全的方式存储在客户端。然后对于每个请求,您都可以使用此用户 ID 为下一个请求提供数据。

于 2020-09-11T18:44:19.340 回答
1

授权标头

在 Authorization 标头中发送令牌,下面的代码返回 auth 用户。

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/profile/me', function (Request $request) {
        return $request->user();
    });
});

如果是 restful api,建议您发送Accept标头,以便在未通过身份验证的情况下在身份验证中间件检查重定向。默认情况下,如果用户未通过身份验证,restful api 将重定向到登录表单(如果有)。

namespace App\Http\Middleware;

protected function redirectTo($request)
{
    if (!$request->expectsJson()) {
        return route('login');
    }
}
于 2020-07-16T20:38:00.807 回答
0

我看到尚未接受任何答案。我只是遇到了我的 sacntum auth 不起作用的问题。auth() 助手总是返回 null。

为了解决这个问题,我删除了 api 键下 kernel.php 中的注释。它是关于这个类\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class的。这是因为它默认被注释掉了。

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

之后,我可以使用 auth() 助手访问 User 对象。

于 2021-12-29T21:36:38.783 回答
0
 private $status_code= 200; // successfully

    public function register(Request $request)
    {
        // $validator = $this->validator($request->all())->validate();
        $validator = Validator::make($request->all(),
            [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255'], // , 'unique:users'
                'password' => ['required', 'string', 'min:4'],
            ]
        );
        if($validator->fails()) {
            return response()->json(["status" => "failed", "message" => "Please Input Valid Data", "errors" => $validator->errors()]);
        }
        $user_status = User::where("email", $request->email)->first();
        if(!is_null($user_status)) {
           return response()->json(["status" => "failed", "success" => false, "message" => "Whoops! email already registered"]);
        }

        $user = $this->create($request->all());
        if(!is_null($user)) {
            $this->guard()->login($user);
            return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registration completed successfully", "data" => $user]);
        }else {
            return response()->json(["status" => "failed", "success" => false, "message" => "Failed to register"]);
        }
    }
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:4'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     * @author Mohammad Ali Abdullah .. 
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
    protected function guard()
    {
        return Auth::guard();
    }
    /**
     * method public
    * @author Mohammad Ali Abdullah
    * @date 01-01-2021.
    */
    public function login(Request $request)
    {

        $validator = Validator::make($request->all(),
            [
                "email"             =>          "required|email",
                "password"          =>          "required"
            ]
        );
        // check validation email and password .. 
        if($validator->fails()) {
            return response()->json(["status" => "failed", "validation_error" => $validator->errors()]);
        }
        // check user email validation ..
        $email_status = User::where("email", $request->email)->first();
        if(!is_null($email_status)) {
            // check user password validation ..
            // ---- first try -----
            // $password_status    =   User::where("email", $request->email)->where("password", Hash::check($request->password))->first();
            // if password is correct ..
            // ---- first try -----
            // if(!is_null($password_status)) {
            if(Hash::check($request->password, $email_status->password)) {
                $credentials = $request->only('email', 'password');
                if (Auth::attempt($credentials)) {
                    // Authentication passed ..
                    $authuser = auth()->user();
                    return response()->json(["status" => $this->status_code, "success" => true, "message" => "You have logged in successfully", "data" => $authuser]);
                }
            }else {
                return response()->json(["status" => "failed", "success" => false, "message" => "Unable to login. Incorrect password."]);
            }
        }else{
            return response()->json(["status" => "failed", "success" => false, "message" => "Email doesnt exist."]);
        }
    }

    public function logout()
    {
        Auth::logout();
        return response()->json(['message' => 'Logged Out'], 200);
    }
于 2021-06-01T10:09:06.440 回答
-1

我在同一条船上;迁移到 Sanctum 并想知道为什么我所有的 $request->user() 都是空的。我的解决方案是将一些中间件扔到堆栈上以修改请求的 user() 解析器:

namespace App\Http\Middleware;

use Illuminate\Http\Request;

class PromoteSanctumUser
{
    /**
     * @param Request $request
     * @param \Closure $next
     */
    public function handle(Request $request, \Closure $next)
    {
        $sanctumUser = auth('sanctum')->user();

        if ($sanctumUser) {
            $request->setUserResolver(function() use ($sanctumUser) {
                return $sanctumUser;
            });
        }

        return $next($request);
    }
}
于 2021-12-09T18:27:02.790 回答
-1

确保 sanctum 中间件在 api 中

于 2021-10-27T11:47:22.227 回答