自定义中间件Laravel不支持api路由

时间:2018-05-06 03:11:32

标签: php laravel

我有中间件调用用户,用于过滤数据库上我的用户表上的角色。这是我的中间件,名为user

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use UsersData;
class User
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check() && Auth::User()->role=='user'){
            return $next($request);
        }
        return redirect()->route('login')->with('danger',"You don't have an access");
    }
}

我已经在内核中注册了我的中间件

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'user' => \App\Http\Middleware\User::class,
        'ajax' => \App\Http\Middleware\Ajax::class,
    ];

以及api.php

的路线
Route::middleware('user')->group(function () {
        Route::post('province','ApiController@getcity')->name('api.getcity');
        Route::post('courier/getcost','ApiController@getCourierCost')->name('api.getcouriercost');
    });

更新config/auth.php这里是警卫

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

一切都适用于web.php路线,但此api.php无效?

如果你发表评论,我真的很感激!

2 个答案:

答案 0 :(得分:2)

在ajax请求中你不能像这样检查auth:

Auth::check();

因为在ajax中你没有任何会话。 当你发送第一个登录请求时,你必须为每个用户发送一个随机密钥,当登录成功时,将它保存在他的数据库的关键字段中,之后当你想发送请求时他必须发送密钥,而你将检查密钥与数据库中的密钥是否可以让他进入。

答案 1 :(得分:2)

我们为web(web.php)和API(api.php)分别设置路径文件的原因之一是因为它们使用不同的身份验证方法。第一个是通常的方式(Web Auth),第二个是API Auth已经由@Babak提及他/她的回答。

API身份验证是无状态的,需要在每个请求上使用令牌,该请求生成并记录在user_idforeign key的单独表中。没有用于验证API用户的登录页面,但您可以使用通常的登录页面让他们请求API Token并使用它来访问API。您可以使用各种方式检查API Token验证,例如request header Bearer,或将其包含在request body等。