DEV Community

Uthman Ehsan
Uthman Ehsan

Posted on

405 Error Laravel Sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs.

Sanctum allows each user of your application to generate multiple API tokens for their account.

However it differs from JWT tokens where the user information is encoded in a string and passed onto server every time request is sent back to server.

Whereas sanctum is more like a stateful session with limited or life time expiration. One can set the expiration under

config/sanctum.php  
'expiration' => null
Enter fullscreen mode Exit fullscreen mode

One can guard or protect the the respective methods under guard configure that would need to send authentication token.

// Request the resource to get token 

Route::post('/users_new', [UserController::class, 'store']);

public users_new(){

   $user = User::create( $request->user_data );

   $token = $user->createToken('api-token')->plainTextToken;

   return response()->json([
               'token' => $token,
                'data' => $user,
            ], 200);
}
Enter fullscreen mode Exit fullscreen mode

In order to update the user data , it will have to pass the token along with request.

Route::middleware('auth:sanctum')->group(function () {
  // all the requests coming inside this middleware will have to pass the token.

//User
Route::post('/updateUser', [UserController::class, 'upgradeUser']);

});
Enter fullscreen mode Exit fullscreen mode

If above is executed , it might throw an 405 Authorization error because at this moment our webserver doesnot accepts
any header tokens . To achieve this we need to add below .**htaccess **file.

RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Enter fullscreen mode Exit fullscreen mode

(right after the RewriteBase) so our htaccess code
becomes

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
</IfModule>
Enter fullscreen mode Exit fullscreen mode

If we need to test above in PostMan , one must add the BearerToken as HeaderAuthorization as depicted in below diagram.

Image description

Happy Coding !

Top comments (0)