Hi all,
I'm using Password Grant Tokens for API.
I have a route /api/contact but I do not want it uses middleware auth:api, Because it public for anyone.
I want to check and retrieve user info if the accessToken correct otherwise returns null.
Tks !!!!!!
you can implement the same check that the middlewares do:
https://github.com/laravel/passport/blob/1.0/src/Http/Middleware/CheckClientCredentials.php#L42-L48
Just to expand on @bhosie's answer, you do in fact recreate that logic, but then to get the user id you have to call getAttribute() on the $psr variable. See below for a full example.
use League\OAuth2\Server\ResourceServer;
use Illuminate\Auth\AuthenticationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
...
public function __construct(ResourceServer $server)
{
$this->server = $server;
}
...
public function doSomething()
{
$psr = (new DiactorosFactory)->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
throw new AuthenticationException;
}
$user = User::find($psr->getAttribute('oauth_user_id'));
return $user;
}
Hope that handles your situation!
Closing for lack of activity, hope you got the help you needed :)
Just for the record. Using the new version, you ca go with auth('api')->user(). It'll return the authenticated user even if middleware is not specifically used.
I found myself in a situation where I had to extract the user from a Bearer token that had not and could not be passed in through the 'Authorization' header. You can use the following code to find the user associated with any given bearer token, and optionally to authorize them.
https://gist.github.com/infostreams/1b827a688c76250e7acb7626906469a8
Hope it helps someone.
Most helpful comment
Just for the record. Using the new version, you ca go with
auth('api')->user(). It'll return the authenticated user even if middleware is not specifically used.