如何在没有用户名和密码的情况下生成access_token

时间:2019-06-09 15:57:10

标签: laravel-5 laravel-passport laravel-5.8

我正在尝试使用Passport创建API。如果用户尝试登录或使用Socialite进行注册,则找到该用户而不是生成access_token,然后使用URL参数中的access_token重定向到前端。

我尝试注册并登录,而不是使用用户电子邮件和默认密码生成access_token,这不适合安全性。

try {
    $serviceUser = Socialite::driver($service)->stateless()->user();
} catch (\Exception $e) {
    return redirect(config('app.client_url').'/auth/social-callback?error=Unable to login using '.$service.'. Please try again'.'&origin=login');
}

$email = $serviceUser->getEmail();
$name = $serviceUser->getName();
$user = $this->getExistingUser($serviceUser, $email, $service);
$newUser = false;
if (!$user) {
    $newUser = true;
    $user = new User;
    $user->name = $name;
    $user->email = $email;
    $user->username = Str::random(10);
    if ($service === 'facebook') {
        $user->image = $serviceUser->avatar;
    }
    $user->verify = true;
    $user->save();
}
if ($this->needsToCreateSocial($user, $service)) {
    Social::create([
        'user_id' => $user->id,
        'social_id' => $serviceUser->getId(),
        'service' => $service
    ]);
}

$http = new Client;

$response = $http->post(config('app.url').'/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => '2',
        'client_secret' => 'oBKWxgF2fDvrxwA05ciapwy4JYKaHxzhGzr6D24X',
        'username' => $email,
        'password' => 'gebdandi',
        'scope' => '',
    ],
]);

$body = json_decode((string) $response->getBody(), true);

$accessToken = $body['access_token'];

return redirect(config('app.client_url').'/social-callback?token='.$accessToken.'&origin='.($newUser ? 'register' : 'login'));

我在文档中找不到任何解决方案。

1 个答案:

答案 0 :(得分:0)

阅读所有文档后,我在此documentation

中找到了解决方案

我确实喜欢这个

像这样编辑authserviceprovider

public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
        Passport::personalAccessClientId(1);
        Passport::tokensExpireIn(now()->addDays(15));
        Passport::refreshTokensExpireIn(now()->addDays(30));
    }

在控制器中添加了这样的代码

$accessToken = $user->createToken('access_token')->accessToken;

感谢laravel Team提供了很好的文档