本篇内容主要讲解“laravel passport与手机短信登录结合方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“laravel passport与手机短信登录结合方法是什么”吧!
准备步骤
laravel passport 环境
怎么安装 怎么使用 看文档就行 这边就记录下和手机短信的坑 和 如何与 passport 结合
坑一
easy-sms 包 对接腾讯云 请用 1.3 版本 2.0 版本 会一致报错发不出去 我反复测试了好几次 简直是坑死我了 并且 code 如果含有字母 他会提示我的签名有问题 实名 diss 下腾讯云的接口 简直是 无语死了
坑二
判断验证码匹配上,创建一个用户,那么怎么给他 token 呢,百度了一堆方法,什么杂七杂八的都有,什么都试过了 要不只支持 laravel5 点几 要不版本怎么样 要不然怎么样的 简直了
if ($innerVerificationCode==$verificationCode) { //验证码成功成功,判断是由在数据库中有此手机用户,有立即给他token 没有 创建后给他token $user=User::query()->where('phone_number', $phoneNumber)->first(); if (!$user) { $user = new User(); $user->name = $phoneNumber; $user->phone_number= $phoneNumber; $user->login_type=User::USER_LOGIN_TYPE_PHONE; $user->password = bcrypt('12345678'); $user->save(); } return $this->getToken($user, 'id');}// 原本一直在纠结如何不用账号密码直接给他 access_token 但是种种原因不是失败了吗 那就 api 请求下public function getToken($user, $type) { $http = new \GuzzleHttp\Client(); $response = $http->post(config('app.url').'/api/fund/oauth/token', [ 'form_params' => [ 'grant_type' => 'password', 'username' => $user->$type,//用户可以直接登录的用户名,配置后也可以是邮箱,5.8版本,这个默认是注册后的邮箱 'password' => '12345678',//用户名对应的密码 'scope' => '*', ], ]); return json_decode($response->getBody(), false); }
access_token 接口的代码如下:
<?phpnamespace App\Http\Controllers\Api;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Hash;use Psr\Http\Message\ServerRequestInterface;use \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;use Validator;class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTokenController{ public function issueToken(ServerRequestInterface $rawRequest) { //获取传入参数 $request = collect($rawRequest->getParsedBody()); $validator = Validator::make($request->all(), [ 'username' => 'required', 'password' => 'required', ])->validate(); $checkUser = \App\Models\User::where("id", $request->get("username"))->first(); if (!Hash::check($request->get("password"), $checkUser->password)) { throw new UnauthorizedHttpException('Unauthenticated', "login failed,username error or password error"); } $oauthClient = DB::table('oauth_clients')->where("password_client", 1)->first(); if (empty($oauthClient)) { throw new \ErrorException('can not get oauth client information'); } //获取其他参数 $addRequest = [ 'grant_type' => $request->get("grant_type", "password"), 'client_id' => $request->get("client_id", $oauthClient->id), 'client_secret' => $request->get("client_secret", $oauthClient->secret), 'scope' => $request->get("scope", "*"), ]; //重写传入参数 $newRawRequest = $rawRequest->withParsedBody(array_merge($request->all(), $addRequest)); return parent::issueToken($newRawRequest); } public function revokeToken() { if(Auth::user()){ $tokenId = Auth::user()->token()->id; $tokenRepository = app('Laravel\Passport\TokenRepository'); $tokenRepository->revokeAccessToken($tokenId); } return response('', 204); }}
给自己记录下 这个文章的文笔不好,随便记录下 现在时间忙
找到了另一种 更好的
<?phpnamespace App\Traits;//这里请引用自己的User Modeluse App\Models\Users\User;use DateTime;use GuzzleHttp\Psr7\Response;use Illuminate\Events\Dispatcher;use Laravel\Passport\Bridge\AccessToken;use Laravel\Passport\Bridge\AccessTokenRepository;use Laravel\Passport\Bridge\Client;use Laravel\Passport\Bridge\RefreshTokenRepository;use Laravel\Passport\Bridge\Scope;use Laravel\Passport\Passport;use Laravel\Passport\TokenRepository;use League\OAuth3\Server\CryptKey;use League\OAuth3\Server\Entities\AccessTokenEntityInterface;use League\OAuth3\Server\Exception\OAuthServerException;use League\OAuth3\Server\Exception\UniqueTokenIdentifierConstraintViolationException;use League\OAuth3\Server\ResponseTypes\BearerTokenResponse;trait PassportToken{ private function generateUniqueIdentifier($length = 40) { try { return bin2hex(random_bytes($length)); // @codeCoverageIgnoreStart } catch (\TypeError $e) { throw OAuthServerException::serverError('An unexpected error has occurred'); } catch (\Error $e) { throw OAuthServerException::serverError('An unexpected error has occurred'); } catch (\Exception $e) { // If you get this message, the CSPRNG failed hard. throw OAuthServerException::serverError('Could not generate a random string'); } // @codeCoverageIgnoreEnd } private function issueRefreshToken(AccessTokenEntityInterface $accessToken) { $maxGenerationAttempts = 10; $refreshTokenRepository = app(RefreshTokenRepository::class); $refreshToken = $refreshTokenRepository->getNewRefreshToken(); $refreshToken->setExpiryDateTime((new \DateTimeImmutable())->add(Passport::refreshTokensExpireIn())); $refreshToken->setAccessToken($accessToken); while ($maxGenerationAttempts-- > 0) { $refreshToken->setIdentifier($this->generateUniqueIdentifier()); try { $refreshTokenRepository->persistNewRefreshToken($refreshToken); return $refreshToken; } catch (UniqueTokenIdentifierConstraintViolationException $e) { if ($maxGenerationAttempts === 0) { throw $e; } } } } protected function createPassportTokenByUser(User $user, $clientId) { $accessTokenRepository = new AccessTokenRepository(new TokenRepository(), new Dispatcher()); $accessToken = $accessTokenRepository->getNewToken(new Client($clientId, null, null), [new Scope("*")], $user->id); $accessToken->setIdentifier($this->generateUniqueIdentifier()); $accessToken->setClient(new Client($clientId, null, null)); $accessToken->setExpiryDateTime((new \DateTimeImmutable())->add(Passport::tokensExpireIn())); $accessTokenRepository->persistNewAccessToken($accessToken); $refreshToken = $this->issueRefreshToken($accessToken); return [ 'access_token' => $accessToken, 'refresh_token' => $refreshToken, ]; } protected function sendBearerTokenResponse($accessToken, $refreshToken) { $response = new BearerTokenResponse(); $response->setAccessToken($accessToken); $response->setRefreshToken($refreshToken); $privateKey = new CryptKey('file://'.Passport::keyPath('oauth-private.key'),null,false); $accessToken->setPrivateKey($privateKey); $response->setPrivateKey($privateKey); $response->setEncryptionKey(app('encrypter')->getKey()); return $response->generateHttpResponse(new Response); } protected function getBearerTokenByUser(User $user, $clientId, $output = true) { $passportToken = $this->createPassportTokenByUser($user, $clientId); $bearerToken = $this->sendBearerTokenResponse($passportToken['access_token'], $passportToken['refresh_token']); if (! $output) { $bearerToken = json_decode($bearerToken->getBody()->__toString(), true); } return $bearerToken; }} $user=User::find(2); $token = $this->getBearerTokenByUser($user,6,false); return $token;
到此,相信大家对“laravel passport与手机短信登录结合方法是什么”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!