简体   繁体   English

Laravel 不记名令牌认证

[英]Laravel bearer token authentication

I want to make authentication for API requests coming from mobile users.我想对来自移动用户的 API 请求进行身份验证。

I followed this and made api_key column inside users table.我遵循了这一点,并在users表中创建了api_key列。

I also created middleware:我还创建了中间件:

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

What I want is to get bearer token from header and check it against user table.我想要的是从header获取bearer令牌并对照用户表检查它。

How to achieve this?如何做到这一点?

Append the auth:api middleware to any route or group of routes and the Bearer token will be checked automatically for you without a custom middleware Append auth:api中间件到任何路由或路由组,并且将自动为您检查承载令牌,无需自定义中间件

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

But to answer the question, here's what you can do (still not recommended but works)但要回答这个问题,这是你可以做的(仍然不推荐但有效)

<?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);
    }
}

Register the middleware in App\Http\KernelApp\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,
];

And protect a route with that middleware name并使用该中间件名称保护路由

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

Result结果

在此处输入图像描述

I would recommend laravel/passport as it is much secure and easier.我会推荐laravel/passport ,因为它更安全、更容易。 Click Here.点击这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM