axios Codeigniter 4 restful API在使用授权承载令牌时返回cors错误

lawou6xi  于 2023-02-22  发布在  iOS
关注(0)|答案(1)|浏览(132)

在前端,我使用react并通过axios发送请求

import axios from "axios";

import { getToken } from "./auth";

const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
});

api.interceptors.request.use((config) => {
  const token = getToken();

  if (token && config && config?.headers) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});

export default api;

在后端,我使用的是codeigniter 4。但是当在请求中添加授权承载令牌时,返回cors错误。
Access to XMLHttpRequest at 'http://localhost:8080/v1/user' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class Cors implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $origin = base_api();

        header("Access-Control-Allow-Origin: {$origin}");
        header("Access-Control-Allow-Headers: X-API-KEY, Origin,X-Requested-With, Content-Type, Accept, Access-Control-Requested-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PATCH, PUT, DELETE");

        $method = $_SERVER['REQUEST_METHOD'];

        if($method == "OPTIONS") {
            die();
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        //
    }
}

有没有人遇到过类似的错误?
我到处寻找解决办法,但没有找到。

xhv8bpkk

xhv8bpkk1#

我刚刚在React with马克西米利安Schwarzmüller的udemy课程中学习了身份验证,我认为你只需要从客户端分离令牌并检查如下.我不知道如何通过php实现,但希望js实现能帮助你.

function checkAuthMiddleware(req, res, next) {
      if (req.method === 'OPTIONS') {
        return next();
      }
      if (!req.headers.authorization) {
        console.log('NOT AUTH. AUTH HEADER MISSING.');
        return next(new NotAuthError('Not authenticated.'));
      }
      const authFragments = req.headers.authorization.split(' ');
    
      if (authFragments.length !== 2) {
        console.log('NOT AUTH. AUTH HEADER INVALID.');
        return next(new NotAuthError('Not authenticated.'));
      }
      const authToken = authFragments[1];
      try {
        const validatedToken = validateJSONToken(authToken);
        req.token = validatedToken;
      } catch (error) {
        console.log('NOT AUTH. TOKEN INVALID.');
        return next(new NotAuthError('Not authenticated.'));
      }
      next();
    }

相关问题