401 错误 - 使用 fetch 找不到 JWT 令牌 [英] 401 error - JWT Token not found using fetch

查看:35
本文介绍了401 错误 - 使用 fetch 找不到 JWT 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,主要是 JavaScript.我正在将 react 用于托管在 localhost:3000 上的 web 应用程序,node.js 和 symfony 2.8 作为我的后端,托管在 localhost:80 和 apache 上,它公开了一个由 lexik 和 fos 用户保护的 api.在保护 api 之前,一切正常.保护 api 后,使用 fetch 时出现 401 错误,如下所示:

I am new to react, and mostly to javascript. I am using react for a web app hosted on localhost:3000 with node.js and symfony 2.8 for my back end, hosted on localhost:80 with apache, that exposes an api secured with lexik and fos user. Before securing the api, everything works fine. After securing the api, I get a 401 error when using fetch as follow:

let myToken = localStorage.getItem('auth_token') //token properly retrieved
let myHeaders = new Headers();
myHeaders.append("Authorization", myToken)
return fetch(
    pathToMyResource,
    {
        method: "post",
        headers: myHeaders
    }
).then(do stuff with the answer)

这使我在预检请求的答案的标题中出现以下错误:

This gives me the following error in the headers of the answer to the preflight request:

Request URL:http://127.0.0.1/edsa-food_app_symfony_2.8/api/site/1/get
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade

和回应:

{"code":401,"message":"JWT Token not found"}

我也检查过,只是因为我真的不明白这应该如何工作,

I also checked, just because I don't really understand how this is supposed to work, with

credentials: 'include'

mode: 'no-cors'

但并没有更成功.

当我使用来自 localhost:8000 的 php 构建并发送相同的请求时,它运行良好.我使用以下代码:

When I build and send this same request using php from localhost:8000, it works perfectly. I use the following code:

$url = pathToMyResource
$options = array(
    'http' => array(
        'header'  => "Authorization: Bearer $token"
        'method'  => 'POST',
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

如果我理解得很好,那不可能是 ​​找不到 Lexik JWT 令牌:任何 symfony 2.8 项目根目录下的默认 .htaccess 包括:

If I understand well it cannot be the apache error described in Lexik JWT Token not found: the default .htaccess at the root of any symfony 2.8 project includes:

RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

我检查并启用了 mod_rewrite.

I checked and mod_rewrite is enabled.

以下是 Chrome 中报告的标题:

Below are the headers as reported in Chrome:

**General**
Request URL:http://127.0.0.1/edsa-food_app_symfony_2.8/api/site/1/get
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade

**Response Headers**
view source
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:44
Content-Type:application/json
Date:Tue, 08 Aug 2017 01:05:20 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.18 (Win32) PHP/5.6.19
WWW-Authenticate:Bearer
X-Powered-By:PHP/5.6.19

**Request Headers**
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6,fr;q=0.4,zh-CN;q=0.2,zh;q=0.2,it;q=0.2
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:POST
Connection:keep-alive
Host:127.0.0.1
Origin:http://localhost:3000
Referer:http://localhost:3000/service-worker.js
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

对于 POST 请求本身:

And for the POST request itself:

**General**
Request URL:http://127.0.0.1/edsa-food_app_symfony_2.8/api/site/1/get
Referrer Policy:no-referrer-when-downgrade

**Request Headers**
Provisional headers are shown
authorization:Bearer eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhbnRvaW5lIiwiaWF0IjoxNTAyMTM4ODUwLCJleHAiOjE1MDIyMjUyNTB9.wpWZZLf5wWjrU0-eAQUR0XiDTvf1jRtiJuGIHoYm7Yo4lGhOn-_bYuJIdv71ZUiuYfaaMxOW4xzXN3JjB9KfrWmXD4jqI6CnHFYZISGlYvAGJayD_z8CMIEdvrMXrbb6_nEc0CaB68BOf7wqJyoNatFKlepwmCHevsRtTIbhc_GviQf_U_Fw30ShtogIJBLqmVD4ex-j0_9QbblAIqNhc8c0thEFYtN7FVepLehCzBNCTNL8l-mxYEFTrUYLKwSt4lRahgTsv4Ozhxl300xz7BbdQEr3ph2i4ssVcvokpEO2C07QicWSwXFx1Vx-2a6XbkoeorTz_P7WstBzinMdv0etlIz2VYN_oUmHaxDu9jlsu90nZlL2Ea7Ak7dSJaNYzmB11yga_OSiWMpzWTjaqP3MLJuS1O5keHMbliERgnBJM_rsMZ-mkVSM8j4t31L1QJCfP0RW-Vfj3biYR1uYNfXwbbdqmIpn6b39qOCY9l4F99dK6R-PKq5ZeBHEfy-OpN39NFmaMQQX5gYCQ3TzVdeou6-hjpqRnNl8dc0HYzAl3fbU102JMefZNvCsIdcI6WDCiyWZO9Viy-z9REAVF4Pr9bLFpc-Q6Lqdj32lt1-yy6i75IOavrPqRilhRh2z_V7rP_DqahrLhFSDPPVg_gcqb8n31_6q3wtyzx16aJ4
Origin:http://localhost:3000
Referer:http://localhost:3000/restaurant
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

我迷路了.

推荐答案

您需要配置您的后端,以便它以 200 或 204 响应预检.

You need to configure your backend so that it responds to the preflight with a 200 or 204.

您可以通过添加您的 Apache 配置来在 Apache 级别处理该问题:

You may be able to handle that at the Apache level by adding your your Apache config this:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

但如果这不能解决问题,那么您需要进一步挖掘并找出后端系统的哪个部分导致 OPTIONS 请求需要身份验证.

But if that doesn’t fix is then you gonna need to dig further and figure out what part of your backend system is causing authentication to be required for OPTIONS requests.

原因是因为这里发生的事情是这样的:

The reason is because what’s happening here is this:

  1. 您的代码告诉您的浏览器它想要发送带有 Authorization 标头的请求.
  2. 您的浏览器说,好的,带有 Authorization 标头的请求要求我执行 CORS 预检 OPTIONS 以确保服务器允许带有该标头的请求.
  3. 您的浏览器向服务器发送 OPTIONS 请求没有 Authorization 标头——因为 OPTIONS 的全部目的代码>检查是否可以发送.
  4. 服务器看到 OPTIONS 请求,但不是以表明它允许请求中的 Authorization 的方式响应它,而是用 401 拒绝它,因为它缺少那个标题.
  5. 对于 CORS 预检,您的浏览器期望得到 200 或 204 响应,但得到的是 401 响应.因此,您的浏览器会立即停止,不再尝试来自您的代码的 POST 请求.
  1. Your code tells your browser it wants to send a request with the Authorization header.
  2. Your browser says, OK, requests with the Authorization header require me to do a CORS preflight OPTIONS to make sure the server allows requests with that header.
  3. Your browser sends the OPTIONS request to the server without the Authorization header—because the whole purpose of the OPTIONS check is to see if it’s OK to send that.
  4. The server sees the OPTIONS request but instead of responding to it in a way that indicates it allows Authorization in requests, it rejects it with a 401 since it lacks that header.
  5. Your browser expects a 200 or 204 response for the CORS preflight but instead gets that 401 response. So your browser stops right there and never tries the POST request from your code.

这篇关于401 错误 - 使用 fetch 找不到 JWT 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆