Laravel Passport Password Grant Tokens: own mobile app - laravel

so my mobile app would be the client, i generated a client_id and a client_secret for it.
users who uses the mobile app have to login using their username/password.
Where should i store the client_id and client_secret? is it ok to expose them and simply place them hardcoded in the app?

It is definitely not the secure way of hardcoding them and just placing them in an app.
Actually its not that straight forward. I assume you created the client from artisan or from the pre-built Vue components. In either case there is more that you have to do in order so safely consume the oauth2 api without exposing any potential security vulnerabilities in your app.
Assuming your mobile users would register from the mobile, you would need to create user and oAuth2 client from your mobile API that you will expose for your clients( mobile apps ) to consume. For this you have to do the following:
After installing laravel passport perform the following artisan command
php artisan migrate
This will create the necessary tables to store oauth clients, their tokens and other related important information at db level. After this you would need to change client_id data type to VARCHAR(255) so as to store username as client_id instead of storing numeric client_ids.
Now go to your models and create a model for oauth_clients table so that you can create client pragmatically from the code while creating users.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class oAuthClient extends Model
{
protected $table = 'oauth_clients';
}
This will create a model class for you through which you can store oauth clients in the db while registering them in your app.
Route::post('/register-user', function () {
$email= \Illuminate\Support\Facades\Input::get('email');
$password=\Illuminate\Support\Facades\Input::get('password');
$user = new \App\User(array(
'name' =>\Illuminate\Support\Facades\Input::get('name'),
'email' => \Illuminate\Support\Facades\Input::get('email'),
'password' => bcrypt(\Illuminate\Support\Facades\Input::get('password')),
));
$user->save();
$oauth_client=new \App\oAuthClient();
$oauth_client->user_id=$user->id;
$oauth_client->id=$email;
$oauth_client->name=$user->name;
$oauth_client->secret=base64_encode(hash_hmac('sha256',$password, 'secret', true));
$oauth_client->password_client=1;
$oauth_client->personal_access_client=0;
$oauth_client->redirect='';
$oauth_client->revoked=0;
$oauth_client->save();
return [
'message' => 'user successfully created.'
];
});
This will generate an entry in user table and oauth_clients table which will be used by laravel passport to generate respective access_tokens for the user.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:
grant_type : 'password'
client_id : '<email with which the user is registered>'
client_secret : '<generate the client secret from the mobile app>'
username : '<email with which the user is registered>'
password : '<password entered by the user>'
scope : '<leave empty as default>'
5.The above will give you a response, if everything is correct, similar to :
{
"token_type": "Bearer",
"expires_in": 3155673600,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3In0.eyJhdWQiOiJzaHVqYWhtQGdtYWlsLmNvbSIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3IiwiaWF0IjoxNDc4MTQ1NjMyLCJuYmYiOjE0NzgxNDU2MzIsImV4cCI6NDYzMzgxOTIzMiwic3ViIjoiMSIsInNjb3BlcyI6W119.dj3g9b2AdPCK-im5uab-01SP71S7AR96R0FQTKKoaZV7M5ID1pSXDlmZw96o5Bd_Xsy0nUqFsPNRQsLvYaOuHZsP8v9mOVirBXLIBvPcBc6lDRdNXvRidNqeh4JHhJu9a5VzNlJPm3joBYSco4wYzNHs2BPSxXuuD3o63nKRHhuUHB-HwjVxj2GDwzEYXdZmf2ZXOGRJ99DlWGDvWx8xQgMQtd1E9Xk_Rs6Iu8tycjBpKBaC24AKxMI6T8DpelnFmUbMcz-pRsgCWCF_hxv6FpXav3jr1CLhhT58_udBvXjQAXEbtHeB7W_oaMcaqezHdAeOWDcnqREZHsnXHtKt0JpymcTWBkS2cg7sJzy6P9mOGgQ8B4gb8wt44_kHTeWnokk4yPFRZojkHLVZb8YL6hZxLlzgV1jCHUxXoHNe1VKlHArdlV8LAts9pqARZkyBRfwQ8oiTL-2m16FQ_qGg-9vI0Suv7d6_W126afI3LxqDBi8AyqpQzZX1FWmuJLV0QiNM0nzTyokzz7w1ilJP2PxIeUzMRlVaJyA395zq2HjbFEenCkd7bAmTGrgEkyWM6XEq1P7qIC_Ne_pLNAV6DLXUpg9bUWEHhHPXIDYKHS-c3N9fPDt8UVvGI8n0rPMieTN92NsYZ_6OqLNpcm6TrhMNZ9eg5EC0IPySrrv62jE",
"refresh_token": "BbwRuDnVfm7tRQk7qSYByFbQKK+shYPDinYA9+q5c/ovIE1xETyWitvq6PU8AHnI5FWb06Nl2BVoBwCHCUmFaeRXQQgYY/i5vIDEQ/TJYFLVPRHDc7CKILF0kMakWKDk7wJdl5J6k5mN38th4pAAZOubiRoZ+2npLC7OSZd5Mq8LCBayzqtyy/QA5MY9ywCgb1PErzrGQhzB3mNhKj7U51ZnYT3nS5nCH7iJkCjaKvd/Hwsx2M6pXnpY45xlDVeTOjZxxaOF/e0+VT2FP2+TZMDRfrSMLBEkpbyX0M/VxunriRJPXTUvl3PW0sVOEa3J7+fbce0XWAKz7PNs3+hcdzD2Av2VHYF7/bJwcDCO77ky0G4JlHjqC0HnnGP2UWI5qR+tCSBga7+M1P3ESjcTCV6G6H+7f8SOSv9FECcJ8J5WUrU+EHrZ95bDtPc9scE4P3OEQaYchlC9GHk2ZoGo5oMJI6YACuRfbGQJNBjdjxvLIrAMrB6DNGDMbH6UZodkpZgQjGVuoCWgFEfLqegHbp34CjwL5ZFJGohV+E87KxedXE6aEseywyjmGLGZwAekjsjNwuxqD2QMb05sg9VkiUPMsvn45K9iCLS5clEKOTwkd+JuWw2IU80pA24aXN64RvOJX5VKMN6CPluJVLdjHeFL55SB7nlDjp15WhoMU1A="
}
You can use these token safely from your client apps ( mobile apps ).
Hope it helps!.

Related

How to implement ForgotPasswordController in SPA application with Laravel/Sanctum?

I'm using Laravel 7.x and sanctum. Logins are working and I would like to create a Forgot Password option from my SPA application.
I'm struggling with the basics as most of the examples in the documentation rely on the auth scaffolding. So far I've managed to get the following:
I have a controller class called ForgotPasswordController with a method called reset that receives the email to be reset via POST.
I've created a object: $user = User::where('email', $email)->get()->first();
At this point I'm too unfamiliar with the architecture to know where to go next, whether it's the Password facade, I see some additional classes in the Illuminat\Auth\Password namespace. My goal is to create an expiring token, email it to the user via the default email config (I know how to send the email / design the template) and then be able to make the webservice call that will allow the password to be resolved.
Here's what I think I know...
I've set CanResetPassword trait on my user models, which I believe are necessary to support the native methods for password reset
I believe the goal is to create a reset token keyed against the user email that expires after a period of time, then send that token appended to a url in an email (I don't know the architectural implications surrounding the generation of the token beyond the table row)
There's a Password facade with a sendResetLink method - but this
method can't work for spa applications because the base url of the
client app will be different, so I'm assuming something native will have to be re-written. In fact, calling this method will return an error of Route [password.reset] not defined.
I'm assuming I will need the password Facade, if so, what is the method to generate the token? Should I just email the link with the token appended or are there other architectural considerations to support the token expiration?
Apologies if my questions are flawed, I'm unclear on the architecture so I'm making assumptions.
Have you tried Laravel authentication? All authentication requirements have been moved to a package called laravel/ui.
By installing that package you can use Laravel authentication. It will take care of your registration, login, and forgot password processes.
This package will create some controllers for all those processes and those you need for forgot password are
ForgotPasswordController: will generate and send reset password links.
ResetPasswordController: will reset the password by getting user's email, new password, and reset password token.
But if you don't want to use the official Laravel package you should take these steps:
Show a "Request reset password form" to the user.
Validate the provided email by the user.
Generate a random reset password token and store it at DB (Need a table with at least two fields: email and token).
Send that token to the user(It's better if you send it as a URL parameter in the reset password link).
When the user navigated to the reset password page, ask for email again and validate the token by checking your DB table and matching the email and token.
Reset the password to whatever the user wants at this point.
Update: I use this piece of code for generating random tokens:
$email = 'user#email.com';
$token = \Illuminate\Support\Str::random(10);
while(\DB::table('reset_password_tokens')->where('token', $token)->exists()) {
$token = \Illuminate\Support\Str::random(10);
}
\DB::table('reset_password_tokens')->insert(compact('email', 'token'));

Issue understanding Laravel 6.0 Passport with Password Grant Tokens flow

I'm having issues understanding the whole process of authenticating a client to consume my API built on Laravel. Some things just don't click for me right now.
I'm trying to implement an API and an OAuth server both on Laravel. The API will be consumed by a native mobile app that is trusted. The flow that makes more sense to me is "Password grand token" as described in the Laravel's Passport docs: https://laravel.com/docs/7.x/passport#password-grant-tokens
As i understand the implementation:
User installs my mobile app.
Upon installation, he's prompted with the "enter username/password" to continue to use the app
Upon hitting submit, i make a POST request to my Laravel oAuth server implementation on "/oauth/token" with "grant_type", "client_id", "username", "password", "scope". I'm leaving out the "client_secret" because i understand that it's not a good idea to store the secret on the client device.
The server then checks the already created( `php artisan passport:client --password` ) "client_id", "username", "password" and "response_type"
If all matches, it generates a token, and responds with "acces_token" & "refresh_token"
I can make now make calls to my API's endpoints "/api/whatever/method_name"
My issue is at point 4. I can only issue the access token if the user already exists in my database, but i'm assuming it's the first time the user uses my app. postman_response
Do i also need an "authentification" step, in witch the user sends username/password and the OAuth server prompts the "authorize app" to use your data, and at this point to save the user in the database and only then proceed?
Usually you have an register route, that is without authorization else you have no entry into the application. Imagine your routes file.
Route::middleware('auth:api')->group(function () {
Route::post('/todos', 'TodoController#index');
});
// Without auth
Route::post('/register', 'RegisterController#register');
For hiding credentials, it is often easier to do a proxy approach, so you backend can hold client_id and client_secret, since it will always be the same (unless you are building an oauth server).
Route::post('/login', 'LoginController#login');
Which will receive username and password, internally call oauth/token and add client_id and client_secret in the process and return the token. To save some calls through the signup, you can do the same approach after you have registered, get the oauth token, with the credentials you have at registrering and return the token imediatly.
I would recommend the following:
In log in method, check if user exists.
If exists, do log him in.
else, first register him up, and then log him in
lastly, return access token

Laravel Passport - Authenticate using postman

I have setup Passport in Laravel 5 and am creating a token when a user registers by using this..
$user->createToken('My Token')->accessToken;
When I create a new user then I can see an entry in the oauth_access_tokens table that looks like this, I have shortened the id for display...
id | user_id | client_id | name | scopes | revoked
-----------------------------------------------------------
765765 | 193 | 1 | My Token | [] | 0
The API route I want to allow access to is protected, now I am trying to allow access by passing the following headers in Postman...
Authorization | Bearer 765765
Accept | application/json
But this is returning a response of unauthenticated, where am I going wrong?
Laravel Passport uses oAuth2. It's not as simple as generating a user token and being able to use it to authenticate. oAuth2 requires another step, which is called a token exchange.
You will have seen the oAuth2 process in action when you log into a website with Facebook. You click the login with Facebook button and you are sent to Facebook and you are presented with a dialog where you're asked to confirm or deny an app access to your account (Usually, specific parts of your account, a.k.a scopes).
That website will have it's own client account with Facebook and will have its own client ID and client secret. When you click that button, the website sends you to Facebook in order to gain your permission and an authorization code from Facebook. The website passes its client ID, requested permissions (scopes), a randomly generated session state (So it can verify later) and a URL to redirect to Facebook where you are shown the dialog.
When you accept, Facebook generates what is called an authorization code and sends you back on your way to the website (The redirect URL specified) along with the sessions state (So the website is able to verify the request) and the authorization code.
The website, on its back end will then ask Facebook to exchange your authorization code for an access token and will provide its client ID and client secret so Facebook is able to verify its authenticity. Facebook then responds with an access token and an expiry time.
Now, the website is able to access your account using the access token to be able to grab the requested information (Such as your email address for login).
It's also possible to do skip a lot of this process and not require the user to have to follow the whole redirection flow. To do this, (In Passport at least), you will need a password grant client. This is usually what you would do if you are using oAuth2 to authenticate an API.
The process here would be to generate a password grant client:
php artisan passport:client --password
In your database, the you will find in the oauth_clients table, a password grant client with a client ID and secret. You would need to give this to whoever is consuming your API (Such as a mobile/cellphone app).
Now when your user wants to log in, the consumer of your API (In this case Postman) would need to provide the user's credentials (username/password) as well as the client ID and secret for your password grant client. It's also necessary to tell Passport that you want to authorize via password grant.
The example given in the docs looks like this:
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'taylor#laravel.com',
'password' => 'my-password',
'scope' => '',
],
]);
When successful, Passport will return a 200 response and will return some JSON containing an access token and a refresh token. You use the access token to access the user's account and you use the refresh token to get a new access token (without requiring the user to log in again).
It is this access token that you need to provide as the Bearer in your Authorization header.

OAuth2 password grant confusion

I have read below article and it is just awesome. Everything from that article is clear however I have one major doubt.
https://stormpath.com/blog/the-ultimate-guide-to-mobile-api-security
The article author said that in 'OAuth2 password grant' while logging into the mobile application, just need to send email and password in order to get the access token from the API server, but I have read at many places that you also need to send client_id and client_secret in that request. I'm going to build my API using Laravel:
https://laravel.com/docs/master/passport#password-grant-tokens
Here you can see it forces me to send client_id and client_secret in that request.
I'm really confused about this. If I have to send client_id and client_secret in that request, first I need to get it from the authorization server by creating a client on it. So at which event, I should create that client? When a user tries to log in from the mobile application? I just need to know the exact flow.
Any help would be appreciated.
Thanks
A client gets created for the developers who need to integrate with the OAuth2 server. It has nothing to do with the specific users' login flow.
ex. I want to integrate with Facebook login; I create a client on Facebook and incorporate that into my service, its Facebooks way of knowing who my service is.
So, a user logs in through your application; your application then sends that username and password to a backend server. The backend server then adds the client_id and secret so the OAuth server can verify the authenticity of the request.
So in your case, a user logs into your mobile application, you send that login request (username and password, with SSL) to your backend server. Your backend server then forwards that request to the OAuth2 service looking like the request below.
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'user#email.com',
'password' => 'user-password',
'scope' => '',
],
This directly returns an access_token and a refresh token that you can safely store in your mobile application.
I create the grant client in a migration called ConfigurePassport and set the key i want the app to use. You do not need a client per user.
public function up()
{
/*
* This command will create the encryption keys needed to generate secure access tokens.
* In addition, the command will create "personal access" and "password grant"
* clients which will be used to generate access tokens
*/
Artisan::call( 'passport:install', array('-n' => true) );
// Set Password Grant Client secret to known key
DB::table( 'oauth_clients' )->where( 'password_client', 1 )->update(
['secret' => env( 'GRANT_CLIENT_SECRET', 'dfhsdfhbtg545fdf45yedh5f5blahblah' )]
);
}
The above migration runs the artisan command passport:install as per the documentation to install the client. https://laravel.com/docs/master/passport#password-grant-tokens
Now your mobile app can request a token like so: the unique per user params are username and password.
You can find the client id in the oauth_clients table where password_client is true. It will likely be 2.
$http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'dfhsdfhbtg545fdf45yedh5f5blahblah',
'username' => 'taylor#laravel.com',
'password' => 'my-password',
'scope' => '',
],
]);
There are two different concepts:
Client: is the piece of software that's intended to communicate with your server. Usually, you will have 3 main clients which are your iOS, Android and web apps.
User: Which is the end-user that will interact with one of your clients, then the client will be communicating with the Oauth server on behalf.
So you will need to generate a client_id & client_secrete only one time. Then you can use these keys to be the authorized middle-man between your Oauth Server & the end-users.
In the case of Password Grant, The client_key & secrete_key are used to obtain the access_token for every user of each client you have.
Once the client obtains the access_token of a particular user (usually upon logging-in), the client will not need to send the client_key & secrete_key anymore, only the access_token.
However, if that user's access_token has expired, you will have to use those keys to exchange a new access_token with the refresh_token you already received from the login process.

User registration for API/SPA

I am creating an API and a separate front-end app that will consume said API. In my particular case I'm using Laravel Passport for my API and some VueJS for my frontend app.
In order for a user to create an account, a user must POST to a route (/oauth/token) on the API which, requires a client_secret to be passed (https://laravel.com/docs/5.3/passport#password-grant-tokens).
The only options I see are:
Having the client_secret sent as a header from my frontend app. However, putting this token out in the open doesn't seem smart.
Don't require the client_secret at all. This doesn't seem much better than option 1.
Have a dynamic page on my frontend app that can securely store the client_secret and then send it to the API. While this is obviously the most secure, it seems to partially defeat the purpose of a fully static frontend (SPA).
What's the best practice for this type of approach? I've searched for how this is dealt with in general with an API and SPA, but I haven't found anything that points me in the right direction.
From my point of view, the Laravel Passport component seems to implement the OAuth2 Framework Protocol incorrectly.
The client_id and client_secret parameters are not part of the grant type.
For the Resource Owner Password Credentials grant type, the required parameters are username and password (see RFC6749 section 4.3.2).
client_id and client_secret are used to authenticate a confidential client that sends its credentials through the body parameters (see RFC6749 section 2.3.1). The Laravel Passport component should allow other client authentication schemes (especially the HTTP Basic Authentication Scheme). The RFC6749 also indicates that
Including the client credentials in the request-body using the two
parameters is NOT RECOMMENDED and SHOULD be limited to clients unable
to directly utilize the HTTP Basic authentication scheme
The OpenID Connect Core specification lists some of those schemes in its section 9. The RFC6749 does not indicates how public clients (e.g. SPA) should authenticate against the token endpoint. They are supposed to use the Implicit grant type which does not require a client authentication.
Anyway, a solution could be to use a kind of proxy. This proxy has to be installed on a server. It will receive all requests from the SPA (without client secret), add the client secret and transmit the modified request to the Laravel Passport endpoint. Then the response is sent to the SPA. This way the SPA never exposes the client secret.
I came across the same problem, and I didn't find much more documentation on the problem.
So here is what I did, that seems working great so far, you'll tell me if you see anything wrong.
For my apps, I'll be using password grant clients that I create on the fly for each "client" of my app. By client I mean browser, or mobile app, or anything.
Each browser, checks at startup if they have any client_id and client_secret into localStorage (or cookies, or anything). Then, if they don't, they call an endpoint of your API that will create a password grant client and return the information to the browser.
The browser will then be able to login the user using this new client information and his credentials.
Here is the controller I use to create a password grant client:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Http\Request;
use Laravel\Passport\ClientRepository;
class AuthController extends Controller
{
protected $hasher;
protected $clients;
public function __construct (Hasher $hasher, ClientRepository $clients)
{
$this->hasher = $hasher;
$this->clients = $clients;
}
public function makeClient (Request $request)
{
$client = $this->clients->create(null,$request->header('User-Agent','Unknown Device'), '', false, true);
return $client->makeVisible('secret');
}
}
As you can see, as the name for the client, I try to store the User-Agent of the browser. So I can potentially display a page to my user with all his clients and giving him the right to revoke some clients like:
"Google Chrome, New York". You can also store the client IP or anything in there that will help you identify more precisely the client type of device...
The simpler way would be to take care of the user registration with the Laravel app running Passport itself (and not with the frontend Vuejs app via API).
Once the user is registered and logged in, you can use Passport's CreateFreshApiToken middleware to add a token to the user's cookie while loading up your frontend app. No more problem with client_secret.
See https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript and https://mattstauffer.co/blog/introducing-laravel-passport#super-powered-access-to-the-api-for-frontend-views
Also oauth/token doesn't create a user I believe? It is supposed to deliver a token (for password grant client) or an authorization code (authorization code grant client).

Resources