我想对来自移动用户的API请求进行身份验证。
我关注了this
并在api_key
表的users
列中创建
我还创建了中间件:
public function handle($request, Closure $next)
{
$token = $request->bearerToken();
return $next($token);
}
我想要从bearer
获取header
令牌,并对照用户表对其进行检查。
如何实现?
答案 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');
希望这会有所帮助