如何在Laravel和Vue.js中使用jwt-auth检查用户是否经过身份验证

时间:2018-02-12 10:48:22

标签: laravel rest api authentication vue.js

我使用Laravel 5.4创建了一个API,并在那里实现了JWT身份验证。现在,我从Vue.js项目访问我的API并在登录后获取令牌。但我不知道如何使用令牌来检查用户是否经过身份验证。什么是解决方法?

以下是Vue.js login()方法:

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);
            });
    }
}

这是

/**
 * 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
    ]);
}

顺便说一句,API正在http://localhost:8000/http://localhost:8080/上的Vue.js项目上运行

1 个答案:

答案 0 :(得分:0)

您可以在授权用户并获取令牌后在每个后续请求中包含令牌,在?token=<token>之后作为请求参数的请求中,您可以包含令牌的几个位置,在标题内在Authorization: Bearer {token}下以及如何从该令牌中获取Authenticated用户,您可以查看official docs,其中提供了有关如何使用的具体示例。

相关问题