Support the ongoing development of Laravel.io →
Authentication Security Laravel
Last updated 2 years ago.
0

Hello, you can check the API documentation for Laravel.

https://laravel.com/docs/5.8/api-authentication

Your users table should have this field for the api_token:

    $table->string('api_token', 80)->after('password')
                    ->unique()
                    ->nullable()
                    ->default(null);

Migrate the table

    php artisan:migrate

You can make a random api token with this attribute when creating the user:

    'api_token' => Str::random(60),

And dont forget to add:

    use Illuminate\Support\Facades\Hash;

at the top of the controller.

If you want your token to be hashed you need to change the config/auth.php file like this:

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => true,
    ],

You need to make a controller for generating the api_tokens and inserting them into the db.

    class ApiTokenController extends Controller
    {
        /**
        * Update the authenticated user's API token.
        *
        * @param  \Illuminate\Http\Request  $request
        * @return array
        */
        public function update(Request $request)
        {
            $token = Str::random(60);

            $request->user()->forceFill([
                'api_token' => hash('sha256', $token),
            ])->save();

            return ['token' => $token];
        }
    }

In this file you can create, update, refresh, etc. the token. As you can see the update method here is for 'user()', but it can be for whatever you want, like 'customers'.

In your routes/api.php add this:

    use Illuminate\Http\Request;

    Route::middleware('auth:api')->get('/user', function(Request $request) {
        return $request->user();
    })

And thats it. Check out how you can pass tokens in request here:

https://laravel.com/docs/5.8/api-authentication#passing-tokens-in-requests

This is for laravel 5.8 version. Hope this helps.

Regards. Daniel

Last updated 5 years ago.

sangrialdrete, manojibcarockers liked this reply

2

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.