2
votes

how can i check if the current user accessing a method from a controller is authenticated, the API route in question is not guarded by any authentication middle, because the route is accessible to public and both guest users, i checked my request headers the Bearer token is being passed, am using a react router for my routes. and api driver is passport

public route:

Route::get('product/list', 'ProductController@index')

what've tried:

  1. Changed the default AUTH Guard to api.

  2. Tried Explicitly calling the Auth()->guard('api')->check() in the controller method.

    if (Auth()->guard('api')->check()) {
          return 'is_favourite';
    } else {
          return 'unauthenticated';
    }
  1. also called it like this Auth()->check()
    if (Auth()->check()) {
          return 'is_favourite';
    } else {
          return 'unauthenticated';
    }

Result:

Always 'unauthenticated'

Expected Results: result of is_favourite when a Bearer token is pass in the header, and 'unauthenticated' if no bearer token is supplied.

1
Auth::guard('api')->check() ? - gbalduzzi
Are you sure the Bearer token you are passing in the testing request is correct? - gbalduzzi
@gbalduzzi yes it is it is been used in other routes that has the middleware('auth:api') set directly - joekenpat

1 Answers

4
votes

I finaly got it to work, tried with this and it worked:

if (auth('api')->check()) {
      return 'is_favourite';
    } else {
      return 'unauthenticated';
    }