簡體   English   中英

Laravel Passport Auth::user()->token 返回 null 而 Auth::user 不是 null

[英]Laravel Passport Auth::user()->token return null while Auth::user is not null

我正在嘗試 output Laravel 中當前用戶的訪問令牌。這是我當前的 controller Class PassportController.php

class PassportController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->user = Auth::user();
            if (Auth::user() == null) return response(['message' => 'Unauthenticated']);
            return $next($request);
        });
    } 
    public function getToken()
    {
        $token = Auth::user()->token;
        return response($token);
    }
}

model 用戶.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; // use Illuminate\Database\Eloquent\Casts\Attribute; use Laravel\Passport\HasApiTokens; use Illuminate\Notifications\Notifiable;


    class User extends Authenticatable
    {
        use HasFactory, HasApiTokens, Notifiable;
    
        
        protected $fillable = ['username', 'password'];
        public function messages()
        {
            return $this->hasMany(Message::class);
        }
    
        public function rooms()
        {
            return $this->belongsToMany(Room::class, 'room_user', 'user_id', 'room_id');
        }
    
        protected $hidden = ['created_at', 'password', 'updated_at', 'rmb_token'];
    }

路線

  Route::get('/tokens', 'API\PassportController@getToken');

我還確保在我的 Postman 請求中包含授權 header,內容為 Bearer {access_token}。 當我嘗試 Auth::user()->token 時,Auth::user 返回的用戶與預期的一樣,但它給了我

App\Models\User::token 必須返回一個關系實例

錯誤,當我dd(Auth::user()->token)我得到它作為 null。我還記得輸入

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

在 config/auth.php 中,所以我不確定是什么原因造成的。 我正在運行最新版本的 Laravel (laravel 9.45.0)。

Auth::user() - 這是一個數據 object,其中包含有關授權用戶的信息,有關該用戶的數據又存儲在用戶表中的數據庫中。

此表中的令牌未存儲且未存儲,如果您使用護照。 然后您的令牌存儲在 oauth_access_tokens 表中。

因此,您為什么決定在 Auth::user() object 中包含授權令牌? 當然,除非你通過某種拐杖以某種方式將它寫在那里,修改 object。但這是根本錯誤的!

您的授權 controller 應如下所示:

<?php

namespace App\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;
use App\Requests\LoginRequest;

/**
 * Class LoginController
 * @package App\Controllers\Auth
 */
class LoginController extends Controller
{
    /**
     * @param LoginRequest $request
     * @return JsonResponse
     */
    public function login (LoginRequest $request): JsonResponse
    {
        $credentials = $request->only('email', 'password');

        if (\Auth::attempt($credentials) === false) {
            return response()->json([
                'status' => false,
                'errors' => ['message' => __('auth.login_error')],
                'data'   => []
            ], 403);
        }

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

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

請求 class 看起來像這樣:

<?php

namespace App\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;

/**
 * Class LoginRequest
 * @package App\Requests
 */
class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'email' => 'required|string|email|max:100',
            'password' => 'required|string|min:6|max:20',
        ];
    }

    /**
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
        // remove the redirect for authorization by api
        $errors = (new ValidationException($validator))->errors();
        throw new HttpResponseException(
            response()->json([
                'status' => false,
                'errors' => $errors,
                'data'   => []
            ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM