PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] How to send authentication header to laravel sanctum with axios

 April 18, 2022     authentication, axios, javascript, laravel, laravel-sanctum     No comments   

Issue

Hi I was working with laravel sanctum (laravel 9) and I wanted to use a token to access a route group that required authentication. I however use a distributed application architecture with laravel as back-end framework and an independent client. I wanted to access the following route group :

Route::group(['middleware' => ['auth:sanctum']], function() {
  Route::get('/templates', [TemplateController::class, 'index']);
});
On the client side I use axios to send http-requests. The client was already in possession of a token I tried sending it with the get request :

import axios from "axios"
const basePath = "http://localhost:8000/api/"
const token = localStorage.getItem('test_token')
const headers = {headers :{ Authorization: `Bearer ${token}` }};
axios.get(basePath+'templates',headers)
  .then(resp => {console.log(resp)})
This approach was based on the following post : How to send authorization header with axios

This however resulted in a status 401 with the following default unauthorized error :

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Does anyone know how to send a token to laravel sanctum so the middleware can detect it? Thanks in advance.


Solution

Hi I found the answer all I needed to do is add an accept property in the headers like this :

const headers = {headers :
                  { Authorization: `Bearer ${token}`,
                    Accept :'application/json', 
                  }
                 };



Answered By - Jip Helsen
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing