Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hcphoon01's avatar

Authentication for public API

I'm making a public API to allow third party websites to interact with my app, I was wondering what the best way to manage authentication would be. I'm currently looking into using Laravel Passport but I'm slightly confused by how the workflow should work.

Should I create clients for my users to then request their own tokens with or should I just have one client that I use to request tokens with and give the tokens out to the users.

I would quite like to use Laravel Passport as that integrates OAuth2 which is a very well known standard for authentication, but from reading the Passport documentation, it does not seem written with the intent of creating a public API as all the client creation 'methods' are through running artisan commands, not through controller methods.

What I am currently looking in to is letting users create an OAuth client by writing a controller that uses the same sort of code included in the php artisan passport:client command but is in a controller so it can be done from a frontend webpage. This would then give the user a client ID and secret which they could then use to follow the standard OAuth flow by requesting an access token with it. I'm not sure how correct this is or if this is a bit too indepth for a quite basic API but this is what I am thinking.

0 likes
1 reply
bobbybouwmann's avatar

Well, Oauth is exactly what you need here ;)

Laravel Passport comes by default with some frontend components which do exactly what you want. The user can login, and they can create their own access tokens in there. You can steal the code from those components to set it up using controller code instead of the commands. All the classes are available, you just need to know where to look.

Oauth2 in this case, can be used in two different ways. With a single access token (the above way) or you can use a full fletched client/secret and access token with refresh token way. This is all supported by Laravel Passport out of the box but you need to set it up yourself for the biggest part. Again, you need to know where to look.

If you have a misunderstanding of how OAuth works, I recommend you to read this: https://oauth2.thephpleague.com/authorization-server/which-grant/ Laravel Passport is built on this package.

The Laravel Passport documentation also shows some glimpse of how you can use these more advanced Oauth2 approaches: https://laravel.com/docs/8.x/passport#code-grant-pkce

However, the documentation assumes that you use the build-in components that come with the package. If you don't, you have to create those components yourself.

3 likes

Please or to participate in this conversation.