0

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?

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.