沙滩星空的博客沙滩星空的博客

laravel授权中间件的使用

创建自定义API接口异常类

vim app/Exceptions/ExceptionApi.php

<?php
namespace App\Exceptions;
use Exception;

class ExceptionApi extends Exception
{
    protected $apiCode=400;

    public function __construct($message = "", $code = 400)
    {
        $this->apiCode = $code;
        parent::__construct($message, 200);
    }

    public function render(){
        return response()->json(['msg' => $this->message,'code'=>$this->apiCode,'data'=>null], 200);
    }
}

忽略异常日志报告

vim app/Exceptions/Handler.php
    protected $dontReport = [ExceptionApi::class];

添加用户授权令牌字段

Laravel 自带的 users 数据表, 新增 api_token 字段

设置中间件路由

vim routes.php
Route::group(['middleware'=>'auth:api'], function (){
    Route::get('/user', function () {
        // return 'ok';
        return new Response('hello TikBall');
    });
});

请求添加 api_token 参数

http://your_site.com/api/user?api_token=123458

默认情况下,请求参数api_token的值,会和users用户数据表的api_token字段值对比,相同则授权通过。

修改授权验证逻辑

# app/Http/Kernel.php
......
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
......
];
......


# app/Exceptions/ExceptionApi.php
......
use App\Exceptions\ExceptionApi;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{

    public function handle($request, Closure $next, ...$guards)
    {
     $token = $request->input('api_token');
     $user = User::query()->where(['api_token'=>hash('sha256', $token)])->first();
        if (empty($guards)) {
            $guards = [null];
        }

        foreach ($guards as $guard) {
//            if($this->auth->guard($guard)->guest()){
//                throw new ExceptionApi(' auth access refuse');
//            }

            if ($this->auth->guard($guard)->check()) {
                $this->auth->shouldUse($guard);
            }

        }

        return $next($request);
    }
}

Laravel 使用 JWT 实现 API Auth, 打造用户授权接口 https://learnku.com/articles/6216/laravel-uses-jwt-to-implement-api-auth-to-build-user-authorization-interfaces
未经允许不得转载:沙滩星空的博客 » laravel授权中间件的使用

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址