简体   繁体   中英

Nuxt3 + Laravel sanctum

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 => {
    
})

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 On this link on Laravel Documentation

Also, ensure you have

Accept: Application/json

As part of your headers as well.

If you do not send that token in your headers, your requests will give you an error "Unauthenticated".

Below is an example of what I send to the API

在 Postman 中发送到 API 的标头

And for Authorization, select the option of Bearer Token

在 Postman 中选择 Bearer Token

Hope this helps.

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: 'joe@gmail.com'})
  "mode": "cors",
  "credentials": "include"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM