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

不羁的心 提交于 2020-12-26 08:04:50

问题


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');


And then in the routes/api.php:-

Routes::get('products', 'ProductsController@index');


in the ProductsController's index method:

public function index () {

    if ( Auth::check() ) {
        $user = Auth::user();
        return $user->products;
    }
    // return 'You don't have any products right now!';
}

The index method will always return null even if the user is logged-in!
So how to authenticate the users in this case while using the API calls?


回答1:


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.




回答2:


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




回答3:


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");
    }



回答4:


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');
    }


来源:https://stackoverflow.com/questions/51133431/how-to-authcheck-user-on-laravel-with-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!