1

I have created an API using Laravel 5.4 and in there I have implemented JWT authentication. Now, I'm accessing my API from Vue.js project and get the token after the login. But I don't know how to use the token for checking if user is authenticated or not. What's the workaround?

Here's the Vue.js login() method:

login() {
    if(this.credentials.login && this.credentials.password) {
        axios.post('http://localhost:8000/api/login', this.credentials)
            .then(response => {
                if(response.data.success) {                            
                    this.token = response.data.token;
                }
            })  
            .catch(error => {
                console.log(error);
            });
    }
}

Here's the

/**
 * API Login
 *
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function login(Request $request)
{
    $credentials = $request->only('login', 'password');

    $validator = Validator::make($credentials, [
        'login' => 'required|min:4',
        'password' => 'required|min:6'
    ]);

    if($validator->fails()) {
        $error = $validator->messages()->toJson();
        return response()->json([ 'success' => true, 'error' => $error ]);
    }

    try {
        if(!$token = JWTAuth::attempt($credentials)) {
            return response()->json([
                'success' => false,
                'error' => 'Неверные логин или пароль.'
            ], 401);
        }
    } catch (JWTException $e) {
        return response()->json([
            'success' => false,
            'error' => 'Не удалось создать токен.'
        ], 500);
    }

    return response()->json([
        'success' => true,
        'token' => $token
    ]);
}

By the way, API is running on http://localhost:8000/ and Vue.js project on http://localhost:8080/

1 Answers1

0

You can include the token in each subsequent request after you authorize the user and get the token, there is few places you can include the token, in a request after ?token=<token> as a request param, inside of a header under Authorization: Bearer {token} and how to get the Authenticated user from that token you can check on official docs which gives you a concrete example on how to.

Nikola Gavric
  • 3,507
  • 1
  • 8
  • 16
  • I know what to do with token in Laravel, but I don't know what to do with it in Vue. For instance: I have `/dashboard` route in my `routes.js` file which shows me a `Dashboard.vue` component. In it I have to check for the user authentication and if it is `false` redirtect it to `/login`. – Камилов Тимур Feb 12 '18 at 11:05
  • Store your `token` in a shared service or inside of `local storage` then make an `interceptor` (https://stackoverflow.com/questions/47946680/axios-interceptor-in-vue-2-js-using-vuex) in `Vue` and on each `Authorized call` append the token, if the token has `timed out` or is `invalid`, `JWT` will return a 401 response, and you can listen for that response and clear your `token` and redirect user back to `/login` page. – Nikola Gavric Feb 12 '18 at 11:09
  • Let me try it and I will give you my response later. Thank u anyway) – Камилов Тимур Feb 12 '18 at 11:12
  • P.S: Don't forget you are also returning `500` error code from your server, so it would be good if you handle that response too @КамиловТимур – Nikola Gavric Feb 12 '18 at 11:44