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

suli's avatar
Level 1

How to Login/Register from Client using API Token Authentication

Hello guys,

I am developing 2 applications (Client and API) both with Laravel and I have some basic questions about the architecture, before I dive to them here is an introduction:

Introduction

Every time Client needs information is going to connect to the API, even for Login and Register, since Client doesnt have any database. As far as I know I have 2 options: API Token Auth or Laravel Passport. I have chose API Token for its simplicity.

My problem here is that I cant understand the flow for this authentication processes. (login, register)

Questions

  • I would like to be able to login a user from clients app, send this request to the server instead of performing the auth process at the Clients app. (same with registry). How can I do it?
  • Which kind of participants are there? Guards, providers?
  • What is the workflow for the whole process? (i mean from the user clicking on the frontends button register) until he gets login after the registration, passing though the API.

I am reading the API Token Authentication In Laravel Docs but I find it kind of confusing.

Thank you in advance!

0 likes
8 replies
martinbean's avatar

@suli API tokens and Passport are pretty much the same thing when boiled down. Passport allows you to add OAuth to your application, in which your application will issue tokens that you can then use to make subsequent API requests. The "token" guard is just a simpler implementation where a token is stored with user records in your database, rather than issued via OAuth.

If you use the simple token approach, then you're going to need a registration endpoint that will create a user, generate an API token, and return that token to that user. The user will need to store it to then be able to perform any additional requests. If they lose that token, then there's no way to retrieve it (other than you going in the database, reading it, and sending it to the user, but you shouldn't be doing that).

With Passport, users can authenticate via OAuth. Again, you'll still need an endpoint to allow a user to register. After they've registered, they can use Passport to retrieve a token. There's the redirect flow where they're sent to a page in your application and asked if the app should have permission to use their account (similar to logging in with Facebook or Twitter). If the user accepts, they'll be sent back to the application with a code they can exchange for an access token. These tokens usually have a limited lifetime and issued in tandem with a refresh token that can be used to request a new, valid token when the current one expires.

1 like
suli's avatar
Level 1

Great general explanation! I think that's what I've been reading but with other less clear words, thank you.

And In a technical approach. I have just created the Client Laravel project, and run make:auth, do you know which changes I would need to do to overwrite the default authentication to make it call the API instead?

suli's avatar
Level 1

I read something about 'guards'.

jimkiarie8's avatar

You can use the client credentials grant tokens. First, you can use the command php artisan passport:client to create a client. After you get the client id and the client secret, you can use it in this code.

Route::get('/apilogin', function () { $query = http_build_query([ 'client_id' => env('API_CLIENT_ID'), // Replace with Client ID 'redirect_uri' => env('API_REDIRECT_URL'), 'response_type' => 'code', 'scope' => '' ]);

    return redirect(env('API_URL') . '/oauth/authorize?'.$query);
});

Route::get('/callback', function (Request $request) {
    $response = (new GuzzleHttp\Client)->post(env('API_URL') . '/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => env('API_CLIENT_ID'), // Replace with Client ID
            'client_secret' => env('API_CLIENT_KEY'), // Replace with client secret
            'redirect_uri' => env('API_REDIRECT_URL'),
            'code' => $request->code,
        ]
    ]);

    session()->put('token', json_decode((string) $response->getBody(), true));

    return redirect('/');
});

in the .env file you should add this.

API_CLIENT_KEY='The client secret' API_CLIENT_ID='Client id' API_REDIRECT_URL=http://127.0.0.1:8001/callback //Callback url API_URL=http://127.0.0.1:8000

This code should be in the client app route. Now when you redirect the client app to the url http://127.0.0.1:8000/apilogin you should be redirected to the server app login page where you will login to the app. After login the api will respond to your client app with a token which this code will store in session session()->put('token', json_decode((string) $response->getBody(), true));. To access the token you will use this: session()->get('token.access_token'); which will return the stored token.

This is the workflow: You create a client on your server app then use the client id and secret to login to the api. The api will respond with an access token and token expiry date. You will need to store the access token on your client app and use it whenever you want to access the server app.

1 like
jimkiarie8's avatar

I haven't used this method but I think it should work like this. After you add the api_token column and change config/auth.php you can put the register api route in you API outside API middleware in your server app. Then you can use guzzlehttp to send the data to the register URL from your client app.

public function register()
{
    $client = new GuzzleHttp\Client;
    $response = $client->request('POST', env('SERVER_URL') . '/api/register', [
        'headers' => [
            'Accept' => 'application/json',
        ],
        'form_params' => [
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(60),
        ],
    ]);
}

This form will be on your client-side but the data will be sent to the server app

Then store the data in your server app database. You can also store the api_token on your sessions and use it in your request which requires authentication. To check if a user is authenticated you can use Auth::guard('api')->check() which will return a boolean.

suli's avatar
Level 1

Well, good direction! thank you! :)

Now I've got the Laravel API project set up and thanks to Postman I can consume this API and register users.

How can I consume the API from another Laravel Client project now?

From the Larave Client project I've run 'php artisan make:auth' to get the basic authentication, but since it has no any database related I receive this error when I try to login from client:

SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) (SQL: select * from `users` where `email` = [email protected] limit 1)

So, how could I link this Client Login to the API Login so I can have a logged in user in the Client side?

Monta.ch's avatar

hello guys, i have an url returned with api with parametr token in postman and when i click on it i want to login user with that token in laravel thanks for answering

Please or to participate in this conversation.