使用Laravel Sanctum获取用户数据

8cdiaqws  于 2023-01-14  发布在  其他
关注(0)|答案(9)|浏览(246)

我之前使用的是Laravel的内置API令牌身份验证,但我想为不同的客户端提供多个api令牌,而使用Laravel 7.x时,我正尝试迁移到Laravel Sanctum。
API看起来验证用户没有任何问题,但是当我尝试用Auth::user();获取用户数据时,它返回null。
我应该使用什么作为身份验证保护?或者基于提供的令牌获取用户数据的方法是否正确?
非常感谢您的评分

r1zhe5dt

r1zhe5dt1#

auth('sanctum')->user()->id
auth('sanctum')->check()
没有中间件,你可以使用这些。

ipakzgxi

ipakzgxi2#

首先,通过sancutum 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
2w2cym1i

2w2cym1i3#

在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');
    }
}
7eumitmz

7eumitmz4#

当您登录用户时,请在登录函数中使用类似以下内容

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

然后将这个用户id发送到客户端,并以安全的方式将其存储在客户端,然后在每次请求时,您都可以使用这个用户id为下一次请求提供数据。

p5cysglq

p5cysglq5#

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);
    }
1aaf6o9v

1aaf6o9v6#

我发现还没有答案被接受。我只是遇到了我的sacntum auth不起作用的问题。auth()助手总是返回null。
为了解决这个问题,我删除了kernel.php中API键下的注解,它是关于\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class类的,这是因为默认情况下它被注解掉了。

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

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

nmpmafwu

nmpmafwu7#

最简单的方法是使用auth助手,如

$user =  auth('sanctum')->user();

也可以通过请求对象获取

//SomeController.php
public function exampleMethod(Request $request)
{
   $user = $request->user();
}

要通过sactum标记字符串获取用户,请执行以下操作

2|bTNlKViqCkCsOJOXWbtNASDKF7SyHwzHOPLNH

代码是这样的

use Laravel\Sanctum\PersonalAccessToken;
//...
$token = PersonalAccessToken::findToken($sactumToken);
$user = $token->tokenable;

**注意:**传递令牌的最常用方法是通过载体从授权标头传递

x3naxklr

x3naxklr8#

确保sancutum中间件使用API

bn31dyow

bn31dyow9#

我也在同一条船上我迁移到了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);
    }
}

相关问题