0

I am using laravel passport for authentication in my laravel and vue.js ecommerce project.

After successful login, I want to redirect user to his/her dashboard.

Here is the vue dashboard page:

<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>

Everytime I login to different user accounts, I have to set the value of authToken manually copy and pasting from Postman. I want to set this token automatically when a user logs in. How can I do this ?

Here is my api controller:

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'=>[]
            ]);
           
        }
        
    }

Updates:

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>

Picture:

enter image description here

What should I write to import api.js ?

import $api from ./../api.js or anything else ?

1 Answer 1

1

Well, you can store your token in LocalStorage. And whenever you request just get it from the local storage and pass it to the request header.

If you are using Axios then you can use interceptors and just intercept your every request and pass token in the header.

Step 1.

Create a file called api.js or you can call it whatever you want.

Step 2.

Create an Axios instance in the api.js file.

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;

Step 3: Where ever you are using Axios use this exported instance so in your component you would do like this:

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

Here you can see, we are using the $api Axios instance which we created in the api.js file instead of Axios direct.

Add also don't forget to store your token in your local storage when you getting that.

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

I hope this will give you an idea.

This way, Token will be sent with every request automatically, if it exists in the localStorage.

UPDATE:

<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>
Sign up to request clarification or add additional context in comments.

14 Comments

where is the local storage located ? What is local storage ?
Local storage is located in every browser.
Its difficult to understand. How can I call the api directly without using api.js ?
you will have to import it in component. import $api from 'your api.js file path here' Then use.
I have updated my post. Please check if its correct.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.