Well, I solved my problem. Didn't send the api_token for the get request I was making :) Doh...
Laravel, Vue, API and authentication?
Hi guys!
I'm building a SPA with Laravel, Vue, Vue router and Vuex and I just got to authentication which is a bit weird to understand. I've already watch Jeffrey's video about authentication through API token and I got that setup nicely, but it's not entirely what i'm looking for.
Eg. I fetch a collection (Building model) which has a relation to users (User model) through a pivot table (user_buildings).
/**
* Retrieve all of the users who have been awarded the current achievement.
*
* @return \Illuminate\Database\Elequent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(User::class, 'user_buildings')->withTimestamps();
}
All fine! However, when I switched to using authentication through API and API token, I can't seem to fetch the logged in user on another model with Auth::user() (or auth()->user() for that matter). I know this has something to do with the calls from the API routes and so on, but how do I do this exactly? Do I really need to implement JWT and more in my application or is there an easier way?
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.
Please let me know if this is a crazy bad idea and if saving the api_token in localStorage would be a better idea? :)
Please or to participate in this conversation.