3
votes

First off, let me admit that I'm new to APIs, and right now I'm working on JWT with Laravel. I'm using tymon\jwt-auth (tymon/jwt-auth:dev-develop --prefer-source to be specific). I went through some tutorials and was able to generate JWT access token.

Here is my login code:

public function login() {
    $credentials = request(['email', 'password']);
    if (!$token = auth('api')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    return response()->json([
        'status' => 'success',
        'message' => 'Login successful',
        'data' => [
          'access_token' => $token,
        ],
    ]);
}

I also need to get refresh token along with the access token, and cannot find code that works in my case.

I tried adding these lines in the code:

$refresh_token = JWTAuth::refresh($token);

but the postman returns with this error:

A token is required in file /var/www/brochill-api/vendor/tymon/jwt-auth/src/JWT.php on line 331

I can also provide other configuration snippets I used if needed. Please help!

1
You can check it at here. stackoverflow.com/questions/41325250/…Saif
assuming you set it up correctly, you just call auth()->refresh() without passing anything as it's a protected endpoint and will parse the existing tokenahmad
@ahmad , in my case, auth()->refresh() didn't do the trick, after some trial and error, I added auth('api')->refresh($token) and that's generating the refresh token. So I can say the problem is solved. Thanks for your time :)Bhanu Prakash

1 Answers

2
votes

Let's start with creating a /refresh route:

Route::post('refresh', 'AuthController@refresh');

Now, in the AuthController,

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        //
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        //
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        //
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

The refresh() function refreshes the access token and invalidates the current one.

For more info on these, you can checkout the official documentation of tymon/jwt-auth, which can be found here.