Laravel承载令牌认证

时间:2019-11-06 12:49:29

标签: laravel

我想对来自移动用户的API请求进行身份验证。

我关注了this 并在api_key表的users列中创建

我还创建了中间件:

public function handle($request, Closure $next)
{
  $token = $request->bearerToken();
  return $next($token);
}

我想要从bearer获取header令牌,并对照用户表对其进行检查。

如何实现?

2 个答案:

答案 0 :(得分:1)

我建议使用laravel/passport,因为它更安全且更容易。 Click Here.

答案 1 :(得分:0)

这不是API身份验证的工作方式,只需将auth:api中间件附加到任何路由或一组路由中,无需定制中间件即可自动进行Bearer令牌检查

Route::get('url', 'controller@method')->middleware('auth:api');

但是要回答这个问题,这是您可以做的(仍然不推荐,但是可以使用)

<?php

namespace App\Http\Middleware;

use Closure;

class ApiAuthentication
{
    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        $user = \App\User::where('api_token', $token)->first();
        if ($user) {
            auth()->login($user);
            return $next($request);
        }
        return response([
            'message' => 'Unauthenticated'
        ], 403);
    }
}

App\Http\Kernel

中注册中间件
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    // Here for example
    'custom_auth' => \App\Http\Middleware\ApiAuthentication::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

并使用该中间件名称保护路由

Route::get('/', function () {
    // Return authenticated user model object serialized to json
    return auth()->user();
})->middleware('custom_auth');

结果

enter image description here

希望这会有所帮助