| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- /**
- * 内部API AUTH中间件.
- */
- namespace Modules\InnerApi\Middlewares;
- use App\Exceptions\InnerApiException;
- use Closure;
- use Illuminate\Support\Str;
- class InnerApiAuthMiddleware
- {
- /**
- * 排除认证的路由.
- * @var string[]
- */
- protected $except = [
- ];
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- if (!$this->shouldPassThrough($request)) {
- $xToken = $request->header('X-TOKEN', '');
- $tokenSecret = env('INNERT_API_TOKEN_SECRET', Str::random(6));
- if ($xToken !== $tokenSecret) {
- throw new InnerApiException('认证错误', 403);
- }
- }
- return $next($request);
- }
- /**
- * 获取排除项.
- * @return array
- */
- public function getExcept()
- {
- return $this->except;
- }
- /**
- * Determine if the request has a URI that should pass through CSRF verification.
- *
- * @param \Illuminate\Http\Request $request
- * @return bool
- */
- protected function shouldPassThrough($request)
- {
- foreach ($this->getExcept() as $except) {
- if ($except !== '/') {
- $except = trim($except, '/');
- }
- if ($request->is($except)) {
- return true;
- }
- }
- return false;
- }
- }
|