Laravel api 授权与 api_token

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42569607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:27:30  来源:igfitidea点击:

Laravel api authorization with api_token

phplaravelapiroutestoken

提问by Mikethetechy

I am trying to create a Laravel API project. So I have this project with basic laravel's scaffolding set up. In my user migration I have added:

我正在尝试创建一个 Laravel API 项目。所以我有这个项目,基本 Laravel 的脚手架设置。在我的用户迁移中,我添加了:

$table->string('api_token', 60)->unique();

then in my User.php model i have added:

然后在我的 User.php 模型中我添加了:

 protected $fillable = [
    'name', 'email', 'password','api_token'
];

Then in my api.php i have made a test route:

然后在我的 api.php 中我做了一个测试路线:

Route::group(['middleware' => ['auth:api']], function(){

Route::group(['middleware' => ['auth:api']], function(){

Route::get('/test', 'ApiController@test');

});

in my Apicontroller:

在我的 Apicontroller 中:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiController extends Controller
{


public function test(Request $request){

return response()->json(['name' => 'test']);


}



}

so now i type this : with my api_token

所以现在我输入这个:用我的 api_token

localhost/project1/public/api/test?api_token='hsvdvhvsjhvasdvas8871238'

It's not giving me the json data, instead it's redirecting to the logged in home page

它没有给我 json 数据,而是重定向到登录的主页

采纳答案by Cong Chen

localhost/project1/public/index.php/api/test?api_token='hsvdvhvsjhvasdvas8871238'would help.

localhost/project1/public/index.php/api/test?api_token='hsvdvhvsjhvasdvas8871238'有助于。

If you want pretty urls, read the documentation: Pretty URLs

如果您想要漂亮的网址,请阅读文档:漂亮的网址

回答by tanay jha

You would not have to write your own API middleware and routes if you use Laravel 5.3 or higher version.

如果您使用 Laravel 5.3 或更高版本,则不必编写自己的 API 中间件和路由。

Moreover, you can use the in-built Passportpackage to manage the access token, using oAuth2.

此外,您可以使用内置的Passport包来管理访问令牌,使用 oAuth2。

$http = new GuzzleHttp\Client;

$response = $http->post($apiUrl.'oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => '2', //this can be generated when you setup Passport package or using artisan commands
        'client_secret' => 'xxxxxxxxx', //this can be generated when you setup Passport package or using artisan commands
        'username' => '[email protected]',
        'password' => 'test123',
        'scope' => '',
    ],
]);

$responseData = json_decode($response->getBody(), true);

$token = $responseData['access_token']; //Now I have the token so I can call any protected routes 

$response = $http->request('GET', $apiUrl.'api/v1/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$token,
    ],
]);

$responseData = json_decode($response->getBody(), true);
echo "Name of the user is: ".$responseData['name'];

回答by Peter Kao

For laravel 5.2
Middleware/ApiAuthenticate

对于 Laravel 5.2
中间件/ApiAuthenticate

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class ApiAuthenticate
{

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            return response()->json(['status'=>'error','message'=>'token mismatch']);;
        }
        return $next($request);
    }
}




内核.php添加

protected $routeMiddleware = [
    'autho'      => \App\Http\Middleware\ApiAuthenticate::class,
];




路由文件

    Route::group(['prefix'=>'api','middleware'=>'autho:api'], function(){
        Route::get('aaa','Api\AAAController@index');
    });