Retrieving User Data with an Access Token in a Laravel Passport Client
You have successfully configured the OAuth2 authorization code flow between your server.app and client.app. The logic on your callback route is sound: you exchange the authorization code for an access_token using Guzzle. However, there is a critical misunderstanding in the premise of your question regarding what that token represents and how to use it.
The redirect URI you observedâhttp://client.app/callback?code=access_tokenâis misleading if interpreted literally as the token itself being returned directly in the query string without an exchange. In a standard OAuth2 flow, the code parameter is a one-time-use credential that must be exchanged for tokens (including the access_token). Once you have executed your POST request to /oauth/token, you now possess a valid JWT-style access token inside your application's memory or variables.
To retrieve user data, such as an email address, you do not send this new token back to the OAuth endpoint (/oauth/token). Instead, you must use it to authenticate API requests against your protected resource routes. In Laravel Passport, these are typically defined in routes/api.php.
You can define a route like /api/user that protects itself with the Bearer token middleware. Here is how you should structure that route on your server:
// routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
The auth:api middleware is the key here. It inspects the incoming HTTP request headers for an Authorization field containing the Bearer <your_access_token>. If the token matches a valid, unexpired passport token associated with a user account on your server, the middleware attaches that user's model instance to the request, allowing you to return $request->user(), which includes the email.
To make this work from your client.app, you need to update your Guzzle configuration to include the header in every subsequent API call. Your current callback route exchanges the code for the token but does not store it or use it immediately. You should modify that logic slightly to persist the token and then hit the protected endpoint.
Here is a refined approach using Guzzle:
use GuzzleHttp\Client;
Route::get('callback', function (Request $request) {
$client = new Client();
// Step 1: Exchange the authorization code for an access token
$tokenResponse = $client->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => config('services.passport.client_id'), // Ideally load this from env
'client_secret' => config('services.passport.secret'),
'redirect_uri' => 'http://client.app/callback',
'code' => $request->code,
],
]);
$tokens = json_decode((string) $tokenResponse->getBody(), true);
$accessToken = $tokens['access_token'];
// Step 2: Use the access token to fetch user data
$headers = [
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
];
$userData = $client->get('http://server.app/api/user', [
'headers' => $headers,
]);
return json_decode((string) $userData->getBody(), true);
});
Critical Trade-offs and Pitfalls
There are two significant issues to address immediately. First, your original client code hardcodes client_secret and an integer client_id. In a real-world scenario, you should never hardcode secrets in source control. Instead, load the client_secret from environment variables (e.g., .env) on your client application. Furthermore, if your client app is a public web application, storing the client_secret on the client side poses a security risk because anyone can inspect the network traffic or the code to steal it. Ideally, the client should only hold the client_id, and the secret should remain exclusively on the server or be handled via a secure proxy if you are building a Single Page Application (SPA).
Secondly, access tokens have an expiration time (expires_in). The token you receive from the /oauth/token endpoint is temporary. If you try to use it after its expiration window, the auth:api middleware on the server will reject the request with a 401 Unauthorized error. You must handle token refresh logic using the refresh_token provided in the initial exchange response if your application needs to maintain long-term sessions.
Finally, ensure that your client_id is correctly registered in the Laravel Passport database (oauth_clients table) and that the redirect_uri matches exactly what was registered during client creation, including the trailing slash or lack thereof. Any mismatch will result in an invalid grant error during the initial token exchange.
