[英]Can't get token and user data at the same time while using Vue.js and laravel/passport and GuzzleHttp
我无法同时获取用户数据和不记名令牌。 使用 vue 2.5 和 laravel 7.2.2
我正在使用 GuzzleHttp 向服务器发出请求以获取令牌。
为了通过我运行第二个php artisan serve --port 8006
命令来请求 go。
用户存在于数据库中 - 已验证。
我的身份验证控制器:
use App\User;
use App\Shop;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use \GuzzleHttp\Client;
use DB;
public function login(Request $request)
{
$user = User::where('email', $request->email)->get();
$client = new Client([
'base_uri' => 'http://127.0.0.1:8006',
'timeout' => 5
]);
try {
$response = $client->request('POST', 'oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => DB::table('oauth_clients')->where('id', 2)->first()->secret,
'username' => $request->email,
'password' => $request->password,
]
]);
$user->token = $response->getBody();
return $user;
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400 || $e->getCode() == 401) {
return response()->json(['message' => 'Грешно потребителко име или парола'], $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
回应是:
[
{
"id": 1,
"name": "Nelly",
"email": "n@n.com",
"email_verified_at": null,
"created_at": "2020-04-05T11:18:30.000000Z",
"updated_at": "2020-04-05T11:18:30.000000Z"
}
]
如果我使方法return $response->getBody()
我只得到不记名令牌。
如果我让方法return $user
我只得到用户
尝试使用 GuzzleHttp\Promise\Promise 如下:
public function login(Request $request)
{
$user = User::where('email', $request->email)->get();
$client = new Client([
'base_uri' => 'http://127.0.0.1:8006',
'timeout' => 5
]);
try {
$promise = $client->requestAsync('POST', 'oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => DB::table('oauth_clients')->where('id', 2)->first()->secret,
'username' => $request->email,
'password' => $request->password,
]
]);
$promise->then(
// $onFulfilled
function ($value) {
dd('The promise was fulfilled.');
},
// $onRejected
function ($reason) {
dd('The promise was rejected.');
}
);
dd('outside of the then');
}
}
每次尝试都会返回“当时之外”
所以基本上你是在向自己发送一个 http 请求来登录。你为什么不做一个正常的检查并手动创建访问令牌
我知道这不是大吃大喝,但我认为它可能会有所帮助
if (! Auth::attempt($request->only(['email', 'password']))) {
throw new \Exception('User not found');
}
/** @var User $user */
$user = Auth::user();
$token = $user->createToken('Token Name')->accessToken;;
dd($token);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.