I’m using Laravel Framework version 5.3.9, fresh download nothing added on via composer(except "laravel/passport": "^1.0"
).
I did all the things suggested in the docs. Tables are created, routes are up, everything works fine. However I need passport for an API.
My routes look like so:
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/v1/users/register | api::users::register | AppHttpControllersApiV1SocialController@register | api,auth |
| | POST | oauth/authorize | | LaravelPassportHttpControllersApproveAuthorizationController@approve | web,auth |
| | GET|HEAD | oauth/authorize | | LaravelPassportHttpControllersAuthorizationController@authorize | web,auth |
| | DELETE | oauth/authorize | | LaravelPassportHttpControllersDenyAuthorizationController@deny | web,auth |
| | GET|HEAD | oauth/clients | | LaravelPassportHttpControllersClientController@forUser | web,auth |
| | POST | oauth/clients | | LaravelPassportHttpControllersClientController@store | web,auth |
| | PUT | oauth/clients/{client_id} | | LaravelPassportHttpControllersClientController@update | web,auth |
| | DELETE | oauth/clients/{client_id} | | LaravelPassportHttpControllersClientController@destroy | web,auth |
| | GET|HEAD | oauth/personal-access-tokens | | LaravelPassportHttpControllersPersonalAccessTokenController@forUser | web,auth |
| | POST | oauth/personal-access-tokens | | LaravelPassportHttpControllersPersonalAccessTokenController@store | web,auth |
| | DELETE | oauth/personal-access-tokens/{token_id} | | LaravelPassportHttpControllersPersonalAccessTokenController@destroy | web,auth |
| | GET|HEAD | oauth/scopes | | LaravelPassportHttpControllersScopeController@all | web,auth |
| | POST | oauth/token | | LaravelPassportHttpControllersAccessTokenController@issueToken | |
| | POST | oauth/token/refresh | | LaravelPassportHttpControllersTransientTokenController@refresh | web,auth |
| | GET|HEAD | oauth/tokens | | LaravelPassportHttpControllersAuthorizedAccessTokenController@forUser | web,auth |
| | DELETE | oauth/tokens/{token_id} | | LaravelPassportHttpControllersAuthorizedAccessTokenController@destroy | web,auth |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
All the web
routes are there, there are no api
related routes, since Passport doesn’t provide anything of that sort out of the box.
The API itself is intended to be used by a trusted client, it’s made for a mobile application that does require a login however, said login will bypass a few steps.
Once a user access the /register
route, the registration process itself is quite simple: access the user’s facebook account an grab a few fields – email, facebook id, name an profile picture and from that point onwards the users is considered registered. But the user will NOT login with facebook(this is a very important aspect). The consumer app will be issued a token and use that token to access various endpoints of the api(that require a token to use).
So it boils down to this. I need to issue an access token to the consumer app that access the API. The API itself will only have one client, that is the mobile app itself. Users that use the app are not considered clients of the API but clients of the mobile app itself.
So far Passport is a headache to work with when it comes to implementing API related stuff, either that or I can’t figure out how to make it work properly.
I’ve created a test client in the oauth_clients
table that looks like so:
I’m using Postman to access api/v1/users/register
route that has the auth
middleware with the following JSON application/json
{
"grant_type" : "authorization_code",
"client_id" : 5,
"client_secet": "y5dvPIOxQJOjYn7w2zzg4c6TRrphsrNFWbG4gAUL"
}
Which of course will result in a
{"error":"Unauthenticated."}
It makes perfect sense.
Out of pure curiosity I changed the /register
route to this:
Route::group([
'middleware' => [
],
], function ()
{
Route::group([
'prefix' => 'users',
'as' => 'users::',
], function ()
{
// Route::get('/register', ['as' => 'register', 'uses' => 'ApiV1SocialController@register',]);
Route::post('/register', ['as' => 'register', 'uses' => 'LaravelPassportHttpControllersAccessTokenController@issueToken',]);
});
});
With the same json
as before. That resulted in {"error":"invalid_client","message":"Client authentication failed"}
.
I’ve tracked down the function that, I think, handles the validateClient
part in vendor/league
oauth2-server/src/Grant/AbstractGrant`.
The $client
is null. Now this may or may not be related to Passport, since the documentation on it rather lacking and the thought of digging thru a monster of a package to track down the error that may be largely due to me not doing something right doesn’t strike me as a good idea, I’m out of options. To be perfectly honest I don’t even know what the problem is.
Really, at this point any sort pointing in the right direction is more than welcome.
The part in questions is
2
Answers
The problem with Laravel 5.3 passport is that unlike previous OAuth 2.0 Server for Laravel library offered by lucadegasperi, it has no API to make clients directly. So as if now the client can only be made through the front-end. FYI we wanted to use laravel passport solely for our mobile app so while creating and registering user we would have only EMAIL & Password and in some cases only Facebook UserID for facebook sign-in. So the following approach worked pretty well for our case and might differ for your scenario but may help you in the longer term to play around with laravel passport.
Note: Before following the below its assumed you have enabled Password Grant in your application.
So the way we solved it for our project on laravel 5.3 is as follows:
in the oauth_clients convert the id field into a normal field i.e. remove it as being primary key and make the data type as varchar so that we can store email address as client_ids as they are also unique for your system. Incase of Facebook login we store Facebook user IDs here in this column which again will be unique for each our client. Also for other tables like: oauth_access_tokens, oauth_auth_codes & oauth_personal_access_clients change client_id to VARCHAR(255) so that it can store email addresses or Facebook User IDs.
Now go to your models and create a model for oauth_clients table so that you can create client programmatically from the code while creating users.
Then in your api.php route file add the following route:
In the above code snippet, you have to note that to generate the oauth_client secret you have to use some strong formula of encryption that you feel comfortable using it with your application. Also, use the same technique to generate the secret key on your mobile app for the respective client/user.
Now you can use the standard POST API offered by laravel passport to request access token through password grant using “oauth/token” using the following parameters:
The above will give you a response, if everything is correct, similar to :
Its only a temporary solution till laravel supports an external API for applications which only has a mobile as the only possible interface for creating oAuth clients and user.
Hope it helps you!
Cheers.
Because the marked answer was noted as correct I feel it necessary to note some key points that many I think would agree with:
You almost NEVER want put server process logic of that kind within your routes directory. Especially when working to create an API with the intent to put it into production. It’s a dirty route to take and not entirely safe.
UNLESS it’s for things that are safe to process within your routes directory. Like, on a lesser scale, the base logic for sending a notification (SMS,email,push,slack) to staff members about a new letter/blog/memo being published as an example.
ALWAYS attempt to leverage and make use of as much of a framework’s features as possible before attempting to “hackishly” accomplish a task that may have been accomplished multiple times before.
Ensure that you’re doing the proper research about something that has been accomplished already. That way it makes it easier to simply reference a video or tutorial that shows how to properly do what someone is trying to do.
That being said, a good starting point would be to watch the following video that perfectly describes the basics of how to properly set up what you’re looking to set up:
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13
In many respects, the video tutorial is very well done and thorough from start to finish. Be sure to brush up on the different Grant_Types for OAuth2.0 as well so you’ll have a better understanding as to what specific type you/your application need based on your application’s position to consume the api:
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
In addition, be sure to USE laravel’s out-of-the-box features for login and register when creating or logging in users. The Controllers are built for you when you perform the following in your console:
Aside from that, if passport is some-what of a mystery, you can always pull in laravel/socialite package (https://github.com/laravel/socialite). It will allow you to “Log in with (Social Network Here)”. Provided that is the route you’re also aiming to go.
END NOTE: The piece I saw in your question that stuck out the most was how a person will register but will not login with facebook. Instead will have an access token to hit various API endpoints. So if I’m getting what you’re saying right, you’re aiming to use a user’s data from facebook when data is returned, the user is considered logged in and is to be issued an access token. SO:
Use socialite to send a “login with facebook” request to facebook. This will get the user’s data and leverage a bit of facebook’s process of authentication.
When a request is returned with user data within the body run it through a check to ensure that there is data (a simply if statement should be fine). Since facebook will have already authenticated that user and the sent credentials you should be good to go.
You can either fire off an internal proxy within your Login Controller (which is the cleaner and safer way to do it) or you can issue a JWT (Which is covered in the last 5 minutes of the video posted in this answer above).
Below is some example code to get you started.
AppHttpControllersAuthLoginController.php
The code above is used IN CASE you’re aiming to use the Password Grant type for authenticating clients through passport. However, I would seriously look at the tutorial video before jumping the gun on anything. It WILL help you out a lot with how to use laravel 5.3 with passport.