2
votes

I'm sorry i'm newbie for API

I have a laravel project and i want to create API to connect my laravel database to mobile app, so i try to use jwt on my composer

"tymon/jwt-auth": "0.5.*"

after that i adding my route this code

Route::group(['prefix' => 'api'], function() {

    Route::post('login', 'Api\AuthController@login');

    Route::group(['middleware' => ['jwt.auth', 'jwt.refresh']], function() {
        Route::post('logout', 'Api\AuthController@logout');

        Route::get('test', function(){
            return response()->json(['foo'=>'bar']);
        });
    });
});

And this is my login function on controller

public function login(Request $request) {
    $credentials = $request->only('email', 'password');

    try {
        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // all good so return the token
    return response()->json(compact('token'));
}

After that i'm using POSTMAN to check the response of my API, i insert url localhost:8000/api/login

but i'm getting token error

TokenMismatchException in VerifyCsrfToken.php line 53

What must i do? where i must create the token?

1

1 Answers

4
votes

You're getting JWT tokens and CSRF tokens mixed up. This issue has nothing to do with JWT, despite the "token" term.

Laravel, by default, requires a _token value to be passed with every POST request to prevent CSRF attacks.

You can include this with your requests, or you can disable CSRF protection for your API by editing App\Http\Middleware\VerifyCsrfToken's $except value.