Search code examples
phplaravelapiaxiosmiddleware

Routes going through api.php returning unauthorised whereas the same route going through web.php works


I have a page which enables users to create 'folders'. I'm using the function below to getAll folders belonging to each user, so when a user logs in they should see all of their folders but not the folders of other users.

/**
 * Retrieve all user folders
 *
 * @return Response
 */
public function getAll()
{
    // notes associated to folder included
    return Folder::where('user_id', Auth::user()->id)->get();
}

This is what the vue page used to load all folders looks like:

<template>
    <v-app id="inspire">
        <v-card v-for="folder in folders" :key="folder.id">
            <v-card-text>
                Name: {{ folder.name }}
            </v-card-text>
        </v-card>
    </v-app>
</template>

<script>
import { mapState } from "vuex";

export default {
    computed: {
        ...mapState(['folders'])
    },

    mounted() {
        this.$store.dispatch('getAllFolders');
    }
};
</script>

This is what the getAllFolders method looks like:

getAllFolders() {
    apiClient.get(window.routes['folders.getAll'])
    .then(function(response){
        console.log(response)
    })
    .catch(function(error){
        console.error(error);
    });
},

Adding the route to web.php works and allows for each user to see their relevant folders:

Route::get('folders/get-all', 'FolderController@getAll')->name('folders.getAll');

However adding it to api.php leads to unauthorised errors:

  Route::middleware(['auth:api'])->group(function () {     
      Route::get('folders/get-all', 'FolderController@getAll')->name('folders.getAll');
      Route::apiResource('folders', FolderController::class);
});

enter image description here

What might I be doing wrong?


Solution

  • Api routes are stateless, they are designed for requests coming from 3rd parties and will require an auth token, which you can generate using a package like Laravel Sanctum.

    See: https://laravel.com/docs/8.x/sanctum#api-token-authentication

    If you are doing ajax requests from your own front end then this is adding unneeded complexity. Stick to web.php, which does not apply the api middleware, and add your own prefex so you can tell apart your html and ajax end points. Ie '/data/user_folders'.