Home > Back-end >  Nuxt3 Laravel sanctum
Nuxt3 Laravel sanctum

Time:01-29

How can I get data from api when backend is secured by laravel sanctum?

when I use useFetch I do not get any data.

const {data: cat} = await useFetch('/api/categories')

Laravel docs told to use axios but in nuxt3 axios module not working. Can someone help?

I was try use useFetch with method get to get csrf cookie but it's doesn't work

const {data} = await useFetch('/sanctum/csrf-cookie', {method: 'get'}).then(Response => {
    
})

CodePudding user response:

To get data when using sanctum,

You are already getting the csrf token above by going to the route /sanctum/csrf-cookie.

However, that is not enough.

For every request that you want to make which is secured, you need to send a token that is generated using sanctum.

Usually, for an app, you would follow these steps

  1. Login user then generate a sanctum token using
$user->createToken('TokenName');
  1. Once token is generated, you can save this token using cookies on your application. Every time you make a subsequent request to your app, simply send the token along with your request headers as a Bearer Token. The header would be something like this
"Authorization": "Bearer "   TOKEN_VALUE;

All depends how you are sending the request.

More documentation is available Headers sent to API in Postman

And for Authorization, select the option of Bearer Token

Selecting Bearer Token in Postman

Hope this helps.

CodePudding user response:

The endpoint /sanctum/csrf-cookie does not return content in the body of the response, that's why you get HTTP 204 No Content, during this request Laravel Sanctum will set an XSRF-TOKEN cookie containing the current CSRF token, you have two ways to use the token: it can be passed via X-XSRF-TOKEN header from your requests, or from the original XSRF-TOKEN cookie.

https://laravel.com/docs/9.x/sanctum#csrf-protection

Here's an exemple using the XSRF-TOKEN cookie:

// the browser load the XSRF-TOKEN cookie
await fetch("https://myapi.com/sanctum/csrf-cookie", {
  "method": "GET",
  "mode": "cors",
  "credentials": "include"
});

// now the browser can send a POST request
await fetch("https://myapi.com/api/register", {
  "method": "POST",
  "body": JSON.stringfy({name: 'Joe': email: '[email protected]'})
  "mode": "cors",
  "credentials": "include"
});
  • Related