簡體   English   中英

如何在Laravel和Vue.js中使用jwt-auth檢查用戶是否已通過身份驗證

[英]How to check whether user is authenticated or not using jwt-auth in Laravel and 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/上運行,而Vue.js項目在http://localhost:8080/

在授權用戶並獲得令牌后,可以在每個后續請求中包含令牌,在?token=<token>的請求中,作為請求參數,可以包含令牌的地方很少,位於Authorization: Bearer {token}下的標頭中Authorization: Bearer {token}以及如何從該令牌獲取Authenticated用戶,您可以查看官方文檔 ,這為您提供了具體的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM