简体   繁体   中英

Laravel 5.3 and API authentication using api_token

I have followed the steps of this tutorial in order to setup API authentication in Laravel 5.3 using the auth:api middleware.

Everything is working as expected apart from I am finding that in order to successfully access my API, I only need to provide an API token for any user in my users table rather than the token linked to the user currently logged in.

Is this expected behaviour because this middleware is stateless? I am using AdLdap2 to authenticate users but I can't see what I could be doing wrong especially as I have followed the steps in the tutorial above.

I have also had a look at TokenGuard which deals with API token validation but can't see any logic that ensures the token matches that of the user logged in.

Any help is much appreciated.

I think the authentication works like expected. The only thing auth:api does is making sure you are authenticated to access the protected routes. If you want to protect a specific route to only one user you could use Gates

So if you have a route to access a user like below and you want the user that's logged in to only access herself you can add a gate.

routes/web.php

Route::get('/user/{id}', function ($id) {
    $userYourTryingToView = User::find($id);

    if (Gate::allows('get-user', $userYourTryingToView)) {
        // The user is allowed to access herself, return the user.
        return response()->json($userYourTryingToView);
    }

    // User is not authenticated to view some other user.
    return response('Unauthenticated', 403);
});

And in your app/Providers/AuthServiceProvider.php

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('get-user', function ($authenticatedUser, $userYourTryingToView) {
        return $authenticatedUser->id == $userYourTryingToView->user_id;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM