Reputation:
I have correctly set it up for users with personal access tokens, but would like to protect ALL api routes. Reading the documentation it sounds like Client Credentials Grant Tokens is what I need. I have a Client ID and Client Secret in my .env
file; I have added the client
middleware using \Laravel\Passport\Http\Middleware\CheckClientCredentials::class
and have applied this to some api routes.
I am using Vue and axios.
How do I go about getting and setting the token I need to access these protected api routes?
Upvotes: 4
Views: 2481
Reputation: 441
The Laravel docs are realy not clear about "Consuming your own API". I also Googled for days and even subscribed to Laracasts. Not helpfull. I got it working now, this is a dump from my notes.
Step 1 - install Passport
composer require laravel/passport
php artisan migrate
php artisan passport:install
Step 2 - edit /app/User.php
use HasApiTokens,Notifiable
Step 3 - edit /app/Providers/AuthServiceProvider.php
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
Step 4 - edit /config/auth.php
enter code 'api' => [
'driver' => 'passport',
'provider' => 'users',
],
Step 5 - Frontend Quickstart
php artisan vendor:publish --tag=passport-components
Step 6 - edit /resources/assets/js/app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component(
'passport-clients',
require('./components/passport/Clients.vue')
);
Vue.component(
'passport-authorized-clients',
require('./components/passport/AuthorizedClients.vue')
);
Vue.component(
'passport-personal-access-tokens',
require('./components/passport/PersonalAccessTokens.vue')
);
const app = new Vue({
el: '#app'
});
Step 7 - authentication routes and views scaffold
php artisan make:auth
Step 8 - edit /app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
Step 9 - edit /routes/web.php (this answers your question)
// Authorization routes Laravel Passport
Auth::routes();
// Landing page
Route::get('/', function () { return view('welcome');});
// Auth protected routes
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('home', 'HomeController@index')->name('home');
Route::get('example', function(){ return view('example'); });
}
//(stolen from /vendor/laravel/passport/src/RouteRegistrar.php - forAuthorization method)
Step 10 - compile assets
npm i -g npm
npm install
npm run dev
Step 11 - nothing. You don't have to do anything on the VueJS and Axios side.
You can just do:
axios.get('URL_XYZ')
.then(response => {
console.log(response.data);
});
Laravel docs:
When using this method of authentication, the default Laravel JavaScript scaffolding instructs Axios to always send the X-CSRF-TOKEN and X-Requested-With headers.
Sources:
https://laravel.com/docs/5.5/passport
https://www.itechempires.com/2017/09/laravel-5-5-api-user-authentication-passport-package/
Upvotes: 3