How to Auth::check() user on Laravel with API calls

前端 未结 4 761
[愿得一人]
[愿得一人] 2021-01-21 07:54

I\'m using VueJS in my front-end, so I have this API call somewhere in the front-end code:

let products = axios.get(\'api/products\');


相关标签:
4条回答
  • 2021-01-21 08:04

    Are you sending auth token because when we write the API we need to deal with auth token and not with Auth::check(). You need to send auth token with user id at the time of api call and verify that details to proceed.

    0 讨论(0)
  • 2021-01-21 08:08

    Return the data via json and decode them in your frontend again. Maybe this helps?

    0 讨论(0)
  • You can check user Auth of API calls by this:

    At first add this use code in your Class:

    use Auth;
    

    Then add this code in your function:

        if (Auth::guard('api')->check())
        {
            logger(Auth::guard('api')->user()); // to get user
    
        }else{
            logger("User not authorized");
        }
    
    0 讨论(0)
  • 2021-01-21 08:20

    Make sure you're sending the CSRF token, somewhere in your bootstrap.js file, you should have something like this. Also make sure you have the csrf token somewhere in the meta tag

    let token = document.head.querySelector('meta[name="csrf-token"]');
    
        if (token) {
            window.axios.defaults.headers.common = {
                'X-CSRF-TOKEN': Laravel.csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            };
        } else {
            console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
        }
    
    0 讨论(0)
提交回复
热议问题