M
M
Maria_Gavrilova2019-07-28 19:19:11
API
Maria_Gavrilova, 2019-07-28 19:19:11

How to create refresh_token in laravel passport?

Hello. I am writing a laravel passport based authentication api. Now the login method code looks like this -

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string|min:6'
        ]);

        $credentials = request(['email', 'password']);

        if (!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);

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

        $token->save();

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

I would like to create also a refresh_token in this method and issue both an access_token and a refresh_token to the user here. Access_token is valid for 1 day. On the trail. day, when logging in, the user will now again have to enter an email and password. And if I also issued a refresh_token here, which is valid for two weeks, then when the user logs in the next day, if he receives an authorization error, he would apply a second time already with a refresh token and log in without entering any passwords. I have clients both on the web and on android and ios.
The documentation says that you need to get some kind of Authorization Code through user redirects. A simpler way is not to create a refresh_token? Just when a user enters an email and password for the first time? Is it as easy as I create an access token? Tell me please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Sokharev, 2019-07-29
@Maria_Gavrilova

1. By default, personal tokens are issued for a period of 1 year. (do I need to worry about expiration time?)
2. Personal tokens are more of a "hack" that allows you to bypass the standard OAuth flow 2. It is usually used to simplify API access, or personal experiments.
3. The correct way to do what you (I assume) want is to request a token for a password grant

use GuzzleHttp\Psr7\ServerRequest as GuzzleRequest;
use GuzzleHttp\Psr7\Response as GuzzleResponse;
use League\OAuth2\Server\AuthorizationServer;
use Illuminate\Http\Response;
use Illuminate\Http\Request;


$server = app(AuthorizationServer::class);

$psrReponse = $server->respondToAccessTokenRequest((new GuzzleRequest('POST', ''))->withParsedBody([
    'grant_type'    => 'password',
    'client_id'     => '2' // Или какой клиент у вас там за гранты паролей отвечает,
    'client_secret' => '***',
    'username'      => '[email protected]',
    'password'      => 'my-very-strong-password',
    'scope'         => '',
]), new GuzzleResponse());
// Можно сразу запросить на вход \Psr\Http\Message\ServerRequestInterface - лара умеет такое инжектить
// Я накидал его руками - для наглядности
// Это могут быть любые psr7 совместимые объекты Request и Response, не только Guzzle. 
// Например Zend\Diactoros (его ижектит лара) тоже подойдет.

// Ну а здесь уже конвертируем ответ в ларовский
// Ответ будет содержать token_type, access_token, expires_in и refresh_token 
// expires_in содержит время жизни токена в секундах
// Например, по умолчанию для одного года это будет 60*60*24*366 = 31622400
return new Response(
    $psrReponse ->getBody(),
    $psrReponse ->getStatusCode(),
    $psrReponse ->getHeaders()
 );

Error handling is not covered here, as I assume this scenario is outside the scope of the OAuth specification, and error responses are free to fall short of it. I will leave this to your discretion.

E
Evgenii Borovoi, 2020-06-22
@EugeneOne77

In theory , here is the solution , but there is an older version of the passport, you need to cut it into your own.
If suddenly someone knows a simpler solution, please write.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question