Laravel Passport Token 没有return 系列代码

Laravel Passport Token doesn't return series of code

我目前很困惑,为什么我对令牌的回复 JSON 没有提供令牌代码。

"token": {
    "token": {
        "name": "appToken",
        "abilities": [
            "*"
        ],
        "tokenable_id": 1,
        "tokenable_type": "App\Models\User",
        "updated_at": "2021-08-29T17:35:00.000000Z",
        "created_at": "2021-08-29T17:35:00.000000Z",
        "id": 7
    }
},

这是响应代码。

public function login()
{
    if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
        $user = Auth::user();
        $success['token'] = $user->createToken('appToken')->accessToken;
       //After successfull authentication, notice how I return json parameters
        return response()->json([
          'success' => true,
          'token' => $success,
          'user' => $user
      ]);
    } else {
   //if authentication is unsuccessfull, notice how I return json parameters
      return response()->json([
        'success' => false,
        'message' => 'Invalid Email or Password',
    ], 401);
    }
}

我想要这些验证码:Bearer

您是否阅读了 Laravel Passport Documentation 密码授予令牌?

Once you have created a password grant client, you may request an access token by issuing a POST request to the /oauth/token route with the user's email address and password.

你必须在控制器的登录功能中做这样的事情:

$response = Http::asForm()->post('http://passport-app.com/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => $request->email,
    'password' => $request->password,
    'scope' => '',
]);

然后,您将能够从您的 $response

中获得 access_tokenrefresh_token
$response->access_token;
$response->refresh_token;

如果您使用的是第八版Laravel。在用户模型中 将 Sanctum\HasApiTokens 调用替换为 Passport\HasApiTokens

替换以下内容

use Laravel\Sanctum\HasApiTokens;

来自

use Laravel\Passport\HasApiTokens;

当使用 auth()->user()->createToken('user') 时,它的 return 数据如下

{
    "status": true,
    "token": {
        "accessToken": {
            "name": "user",
            "abilities": [
                "*"
            ],
            "tokenable_id": 1,
            "tokenable_type": "App\Models\User",
            "updated_at": "2021-10-08T06:26:34.000000Z",
            "created_at": "2021-10-08T06:26:34.000000Z",
            "id": 11
        },
        "plainTextToken": "11|Gl99gx8sfNVV4wxhlEQ2NBl37aGz1RpFASLIRfDP"
    }
}

所以你可以使用 auth()->user()->createToken('user')->plainTextToken 你得到令牌。所以为你提供帮助。

我认为您必须在用户模型的顶部添加以下内容,并在 User class.

中添加 use HasApiTokens

use Laravel\Passport\HasApiTokens;


class User extends Authenticatable {
    use HasApiTokens, Notifiable;
}