0👍
Laravel Passport has a built in way of allowing you to consume your own API with a Javascript application. It provides a simple middleware which you can add to your web
middleware group (which you’ll find in App\Http\Kernel
):
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Laravel will check to see if you have a logged in user (via the standard cookie/session guard) and if so it will generate JWT for you and store it in a cookie. It will also check for this cookie’s presence and validate it when you make requests to your API so you no longer need to pass an access token.
One thing to note however, is that you will need to ensure that you continue to pass your CSRF tokens with your requests (assuming you have CSRF protection turned on). If you’re using Axios with Vue, you can make sure this happens very easily with the following:
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
};
With this approach you don’t need to worry about access tokens at all or expose a client_id
and secret
to the client.
0👍
I faced the same problem and found an interesting solution.
You can add a custom endpoint on the backend and make the request from there.
All you have to do is to:
First, create a route in the api.php file Route::post('/login', 'AuthController@login');
Then, create the AuthController and login function associated with that route php artisan make:controller AuthController
Finally, install Guzzle, the HTTP client that will allow you to make a request from PHP composer require guzzlehttp/guzzle
and make the request from the login function
public function login(Request $request)
{
$http = new \GuzzleHttp\Client;
try {
$response = $http->post('http://example.test/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'your_client_secret',
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if($e->getCode() == 400)
{
return response()->json('Invalid Request, Please enter email or password.', $e->getCode());
}
else if($e->getCode() == 401)
{
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
Now, the vue.js front end app juste needs to send a post request to http://example.test/login
with the username and password to get back the access_token
without knowing the client_secret
since it is abstracted to the backend.
Here is the video that explains it and implements it really well.
And a presentation about some theory and how you can store and send the token from the vue.js app once you retrieve the token.
Hope this helps.