0
votes

I am working on a project with laravel and lucadegasperi/oauth2-server-laravel with password grand type. Everything is working fine and all my API endpoints are protected by oauth2.

I only have one API that should always return a JSON data response but this response depends if the user is logged in or not. And since the Auth check is being handled in the Middleware "OAuthExceptionHandlerMiddleware", if the user is not logged in the request is stopped and do not reach my controller and i get the following response:

{
  "error": "invalid_request",
  "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."
}

What I am looking to achieve is to be able to handle the request inside my controller only for one API endpoint:

  • If the user is not logged in, return the normal response + other data and not the "Invalid Request" response.
  • If the user is logged in return the normal response.

Thank you for any help on how to achieve the above.

2

2 Answers

0
votes

You can add exceptions to your middleware to remove your auth rule.

Something like

$this->middleware('auth', ['except' => array('getActivate', 'getLogin')]);

see Laracasts

0
votes

To authenticate inside the controller and not in the Middleware, I ended up up doing the following:

use League\OAuth2\Server\Entity\AccessTokenEntity;
use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use Illuminate\Http\Request;

class ProductController extends Controller {

    public function __construct(Request $request) {
        $this->middleware('oauth', ['except' => ['index']]);
    }

    public function index(Request $request) {
        Authorizer::setRequest($request);
        $accessTokenString = Authorizer::getChecker()->determineAccessToken(true);
        $accessToken = Authorizer::getChecker()->getAccessTokenStorage()->get($accessTokenString);
        if ($accessToken instanceof AccessTokenEntity) {
            echo "logged In with user_id = " . $accessToken->getSession()->getOwnerId();
            //return public products + products related to user 
        }else{
            echo "not logged in";
            //return public products
        }
    }
}