【问题标题】:How to get auth token automatically in laravel and vue?如何在 laravel 和 vue 中自动获取身份验证令牌?
【发布时间】:2021-10-28 04:21:24
【问题描述】:

我在我的 laravel 和 vue.js 电子商务项目中使用 laravel 护照进行身份验证。

成功登录后,我想将用户重定向到他/她的仪表板。

这里是 vue 仪表板页面:

<template>
  <div class="content-center">
    <h1>Dashboard my account</h1>
    <p>
        {{userData.name}}
    </p>
  </div>
</template>
<script>
import Axios from "axios";
export default {
  data() {
    return {
      userData: "",
      authToken: ""
    }
  },
  async beforeMount() {
    let res = await Axios.get("http://localhost:8000/api/user-details", {
      headers: {
        Authorization: "Bearer " + this.authToken, 
        Accept: 'application/json'
      },
       
    });
     this.userData = res.data;
     
    //  let token = await Axios.get("http://localhost:8000/api/user-login")
    //   this.authToken = res.data.data.auth_token
    //let res = await Axios.get("http://localhost:8000/api/user-details");
    
  },
};
</script>

每次登录不同的用户帐户时,我都必须从 Postman 手动复制和粘贴设置 authToken 的值。我想在用户登录时自动设置此令牌。我该怎么做?

这是我的 api 控制器:

class AuthApiController extends Controller
{
    public function userDetails(){
        return auth()->user();
    }
    public function login(Request $request){
            
        $user = User::where('email',$request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'success'=>false,
                'data'=>[],
                'message'=>'Login failed',
                'errors'=>[]
            ]);
        }else{
            return response()->json([
                'success'=>true,
                'data'=>['user'=> $user, 'auth_token' =>  $user->createToken('AuthToken')->accessToken],
                'message'=>'Login success',
                'errors'=>[]
            ]);
           
        }
        
    }

更新:

dashboard.vue

<template>
  <div class="content-center">
    <h1>Dashboard my account</h1>
    <p>
        {{userData.name}}
    </p>
  </div>
</template>
<script>
import Axios from "axios";
export default {
  data() {
    return {
      userData: "",
      authToken: ""
    }
  },
  async beforeMount() {
    let res = await Axios.get("http://localhost:8000/api/user-details", {
      headers: {
        Authorization: "Bearer " + this.authToken, 
        Accept: 'application/json'
      },
       
    });
     this.userData = res.data;
     
     let token = await $api.get("http://localhost:8000/api/user-login")
      this.authToken = res.data.data.auth_token
    
    
  },
};
</script>

图片:

enter image description here

我应该写什么来导入 api.js ?

从 ./../api.js 导入 $api ?

【问题讨论】:

    标签: laravel vue.js laravel-vue


    【解决方案1】:

    好吧,您可以将令牌存储在 LocalStorage 中。每当您请求时,只需从本地存储中获取它并将其传递给请求标头。

    如果您使用的是 Axios,那么您可以使用 interceptors 并拦截您的每个请求并在标头中传递令牌。

    第 1 步。

    创建一个名为api.js 的文件,或者您可以随意命名。

    第 2 步。

    api.js文件中创建一个Axios实例。

    import axios from 'axios';
    
    // Put your backend url here
    export const API_URL = `http://localhost:5000/api`
    
    const $api = axios.create({
        withCredentials: true,
        baseURL: API_URL
    })
    
    $api.interceptors.request.use((config) => {
        config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
        return config;
    })
    
    
    export default $api;
    

    第 3 步:无论您在哪里使用 Axios,都使用这个导出的实例,所以在您的组件中您可以这样做:

    const userdata = await $api.get("http://localhost:8000/api/user-details");
    

    在这里您可以看到,我们使用的是在api.js 文件中创建的$api Axios 实例,而不是直接使用Axios

    添加也不要忘记在获得令牌时将令牌存储在本地存储中。

    localStorage.setItem('token', "Your token goes here...");
    

    我希望这会给你一个想法。

    这样,如果本地存储中存在Token,每个请求都会自动发送Token。

    更新:

    <template>
      <div class="content-center">
        <h1>Dashboard my account</h1>
        <p>
            {{userData.name}}
        </p>
      </div>
    </template>
    <script>
    // import Axios from "axios";
       import $api from 'put relative path of your api.js file'
    
    export default {
      data() {
        return {
          userData: "",
          authToken: ""
        }
      },
      async beforeMount() {
        let res = await $api.get("/user-details");
         this.userData = res.data;
         
         let res = await $api.get("/user-login")
          localStorage.setItem('token', res.data.data.auth_token);        
      },
    };
    </script>
    

    【讨论】:

    • 本地存储在哪里?什么是本地存储?
    • 本地存储位于每个浏览器中。
    • 很难理解。如何不使用 api.js 直接调用 api?
    • 你必须在组件中导入它。 import $api from 'your api.js file path here' 然后使用。
    • 我更新了我的帖子。请检查是否正确。
    猜你喜欢
    • 2018-03-25
    • 2019-03-05
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2022-09-28
    • 2022-03-03
    相关资源
    最近更新 更多