pppwwwa
pppwwwa

Reputation: 141

Laravel 5.2 api routes auth

I am developing a project with laravel 5.2.31. I want to build an api service, and want to user api_token to auth users. So here are my steps:

First, I create an api.php in app\Httpdirectory. And I modified App\Providers\RouteServiceProvider:

/**
 * Define the routes for the application.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function map(Router $router)
{
    $this->mapWebRoutes($router);
    //load api.php routes
    $this->mapApiRoutes($router);
    //
}

/**
 * Define the "web" routes for the application.
 *
 * These routes all receive session state, CSRF protection, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
protected function mapWebRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/routes.php');
    });
}

protected function mapApiRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware'=>'api',
    ], function ($router) {
        require app_path('Http/api.php');
    });
}

Second, I changed config/auth.php default guard to api.

Third, I add an api_token column into my users table.

Finally, I defined a route in api.php to test :

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

And I found a problem. If I passed api_token as a url parameter or a header parameter and the value is correct, like http://localhost/test?api_token=xxxxx,it works fine.But if no match value for api_token found in database, I will get a 404 page not found response not 422 response. Someone can tell me why?

Upvotes: 0

Views: 955

Answers (1)

Muhammad Nauman
Muhammad Nauman

Reputation: 1309

It might work if you try adding some conditions like

    If(isset($user)){
return $user;
}
return "not found";

May be it will solve your problem.

Upvotes: 0

Related Questions