简体   繁体   中英

NotFoundHttpException while using api_token based authentication in laravel 5.2

I am doing project in laravel 5.2. For authentication, I am using API Token Authentication from Laravel 5.2. I have referred https://gistlog.co/JacobBennett/090369fbab0b31130b51 and my code looks like,

Routes.php

Route::post('login/','UserController@login');
 Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::get('/', function () {
        return "Hi";
    });
});

and in UserController.php I did simple login as follows,

    public function login(Request $request){
        $email = $request->input('email');
        $user = DB::table('users')->where('email',$email)->first();
        return $user->api_token;
    }

I am using postman and first I did login and it returns me the correct api_token from table but when I try to access urls within middleware then it throws an error page as,

Sorry, the page you are looking for could not be found.

1/1
NotFoundHttpException in RouteCollection.php line 161:

I tried, localhost:8888/ as well as

localhost:8888/api_token=6CnUsIKlmwHXYQNFAuhUTDweUe707gJU2nM2j1Kwjn80nFgmaJHGXuAdN3BX

But still it shows same error page.

Try to change your route / for this code in your Routes.php:

Route::post('login/','UserController@login');
Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::get('/', array('as'=>'api_login', 'uses' => 'UserController@api_login'));
});

And in your UserController.php add:

public function api_login(){
    return "Hi";
}

I use the Auth class, not an api and if i put the code in Routes.php it didn't work, but if I put the same code inside a Controller and in my Routes.php add the 'uses', it works.

I hope that it works for you too.

Good Luck!

如果它有助于任何人搜索这个问题,我遇到了同样的问题,经过几个小时的玩游戏意识到这是因为我的数据库中没有api_tokens,一旦我添加它很好,只是奇怪的行为,当api_token它给404无效。

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