joekenpat
joekenpat

Reputation: 387

Laravel: How to check user auth for API routes without middleware('auth:api')

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.

Upvotes: 2

Views: 2726

Answers (1)

joekenpat
joekenpat

Reputation: 387

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

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

Upvotes: 7

Related Questions