ms.dev
ms.dev

Reputation: 67

API with Lumen Framework authorize not work

I working a simple API with Lumen, But I encounter a problem. I want to delete the user if he is the user, but my authorize is not work.

For the login I use JWT token.

UserController.php

    /**
     * Delete user by user id.
     *
     * @param int $id
     *
     * @return mixed
     */
    public function delete($id)
    {
        $user = User::find($id);

        $this->authorize('delete', $user);

        $user->delete();

        return response()->json([
            'success'   =>  'User deleted with success'
        ], 200);
    }

UserPolicy.php

class UserPolicy
{

    public function delete(User $user, User $user_current)
    {
        return $user->id === $user_current->id;
    }

}

AuthServiceProvider.php

    public function boot()
    {
        Gate::policy(User::class, UserPolicy::class);

        $this->app['auth']->viaRequest('api', function ($request) {
            if ($request->header('Authorization')) {
                return User::where('api_token', $request->input('api_token'))->first();
            }
        });
    }

I I do not understand why it does not work.

Upvotes: 1

Views: 1370

Answers (1)

Mohammadreza Yektamaram
Mohammadreza Yektamaram

Reputation: 1514

Try using like below in your header:

Authorization : Bearer [TOKEN]

Update 1:

If you're in Apache, I guess this might help you as it works on mine:
Just add these lines on your .htaccess file:

RewriteEngine On  
RewriteCond %{HTTP:Authorization} ^(.*)  
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]  

Update 2:

Okay, Please change your AuthServiceProvider like below codes:

$this->app['auth']->viaRequest('api', function ($request) {
    $token = $request->bearerToken();

    if(!$token) {
        // Unauthorized response if token not there
        throw new Exception('token not provided');
    }
    .
    .
    .
}

Upvotes: 1

Related Questions