D
D
denop2019-09-19 22:50:43
Yii
denop, 2019-09-19 22:50:43

Where to store access token for API?

Greetings!
Implemented an API for pulling up (previous) form data when entering a page.
But I ran into several issues:
1. Authorization : Bearer is not displayed in Headers (maybe I'm looking in the wrong place. And should I?)
2. Where is it better to store access token for Vue.js? (set in Cookies, but can't retrieve them from httpOnly)
"If the cookie is set to httpOnly, then document.cookie doesn't see it, so the cookie is protected."
Advise how to be?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vfreelance, 2019-09-20
@vfreelancer

from the Internet:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // assume your access token is stored in local storage 
    // (it should really be somewhere more secure but I digress for simplicity)
    let token = localStorage.getItem('access_token')
    if (token) {
       config.headers['Authorization'] = `Bearer ${token}`
    }
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

and further:
To give a better answer to this thread, I did the following:

In my layouts app file I added:

<script>
    window.App = {!! json_encode([
        'apiToken' => Auth::user()->api_token,
    ]) !!};
</script>
    

and in my bootstrap.js I added:

axios.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest',
  'Authorization': 'Bearer ' + App.apiToken,
};

With this I always send the api_token with the logged in user when ever I make a request with Axios. Probably not the best way to go about it, and one should probably use Passport for this.

I
Igor, 2019-09-20
@IgorPI

localStorage
Cookies

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question