Skip to content

Can't get api.auth middleware to work on jwt auth #597

@rawaludin

Description

@rawaludin

I was following this tutorial https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

So, I could get the token using this method:

<?php
....
class AuthenticateController extends Controller
{
   ...
    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            // verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }
}

(I don't know whats the best way to authenticate and get the token in Dingo/Api).

To protect the other method, I use this:

<?php
....

class AuthenticateController extends Controller
{
    public function __construct()
    {
       $this->middleware('api.auth', ['except' => ['authenticate']]);
    }

    public function index()
    {
        // Retrieve all the users in the database and return them
        $users = \App\User::all();
        return $users;
    }
   ....
}

Here is the route I use:

Route::group(['prefix' => 'api'], function()
{
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
});

And some of my configuration:

'auth' => [
        'basic' => function ($app) {
            return new Dingo\Api\Auth\Provider\Basic($app['auth']);
        },
        'basic' => function ($app) {
            return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
        }
    ],

So, I expect after logged in, I could access the index method. It works when I followed the tutorial. But, it always yield error when I used above configuration:

FatalErrorException in Auth.php line 50:
Call to a member function getAuthProviders() on null

Of course, I have sent the token:
screen shot 2015-08-21 at 3 07 35 pm

How to fix this? Is there something I done wrong?
As more info, I'm using:

$ php -v
PHP 5.6.2 (cli) (built: Oct 28 2014 00:01:08)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies

When developing, I use php artisan serve and access the web from localhost:8000. Thanks.. :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions