Skip to content
Advertisement

Laravel vapor “This action is unauthorized” with file upload

I have set up Laravel Vapor with my RESTFull app using Sanctum and now I’m trying to simply upload a file. I’m making a request POST /vapor/signed-storage-url and I’m getting:

{
    "message": "This action is unauthorized.",
    ...
}

I have created the UserPolicy as described in the docs:

class UserPolicy 
{
    /**
     * Determine whether the user can upload files.
     *
     * @param User $user
     * @return bool
     */
    public function uploadFiles(User $user): bool
    {
        return true;
    }
}

But I keep getting This action is unauthorized.

Advertisement

Answer

The key piece of information here is that I’m using Sanctum to authenticate my users in my app. Laravel’s Vapor uses by default the web middleware

From the docs I wasn’t able to find a way to publish Vapor’s configuration.

If we look at the routes configuration we will have:

    /**
     * Ensure that Vapor's internal routes are defined.
     *
     * @return void
     */
    public function ensureRoutesAreDefined()
    {
        if ($this->app->routesAreCached()) {
            return;
        }

        if (config('vapor.signed_storage.enabled', true)) {
            Route::post(
                config('vapor.signed_storage.url', '/vapor/signed-storage-url'),
                ContractsSignedStorageUrlController::class.'@store'
            )->middleware(config('vapor.middleware', 'web'));
        }
    }

Vapor is getting the vapor.middleware environment to tell which middleware will be applied to /vapor/signed-storage-url route. Since I’m using Sanctum I just had to manually publish Vapor’s configuration by creating a vapor.php in my config folder:

- config
-- app.php
-- filesystem.php
-- vapor.php 👈

Now in this file you can define your middleware to be set to auth:sanctum:

<?php

return [
    // Most of these variables are not necessary as the default from Vapor's 
    // core library is okay for most cases but I will leave here you need to use any of them
    'redirect_to_root' => true,

    'redirect_robots_txt' => true,

    'serve_assets' => [],

    'middleware' => 'auth:sanctum' 👈
];

Now Vapor will start to use the auth:sanctum middleware to authenticate the request to POST /vapor/signed-storage-url

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement