I'm trying to create my first REST API in Laravel using Passport. I'm used to adding in laravel/ui for all the auth functionality/password resets etc. but do I need to roll my own with Passport?
Has anyone released a boilerplate project for this kind of thing?
You don't need the laravel/ui package for passport.
Installing passport alone is already enough. If you follow all the installation steps it should work out of the box. However, creating a user is something you need to implement yourself. You can of course use the code from the laravel/ui package for that.
In general, you can use the same routes and simply add the api middleware instead of the web middleware and most stuff should already work. You just need to refactor them a bit to return a JSON response. I would personally build up those controllers myself.
@_chris You don’t really need a “boilerplate” as Passport is an OAuth server implementation. So if you follow the docs on installing Passport and create yourself a client, then you’ll be able to issue tokens to authenticate against your API.
Right, but I still need to create the 'register' and 'login' controller functions I think? I was just trying to figure out whether these were created as part of the Passport installation.
Might be nice to have that as an option with Passport. So doing something like Passport::install --auth would install an API controller with some register, login, password reset boilerplate. It could be the same as the laravel ui boilerplate but create a token and return the json I think?
@_chris You don’t “log in” to an OAuth-protected API. You ask your OAuth server for a token to authenticate requests.
As for registering, you would make a request to your API to create a user, which is pretty simple:
Route::post('users', 'UserController@store');
class UserController extends Controller
{
public function store(CreateUserRequest $request)
{
$user = User::create($request->validated());
return new UserResource($user);
}
}
@martinbean I understand your point, that you don't need boilerplate. But creating such an application for the first time can be challenging. I think the docs can do a better job in that, but the tutorials you can find everywhere are good enough as well.