获取 API 重定向无法按我的预期工作



大家好!我正在使用battle.net api构建一个小应用程序。

我正在尝试使用Oauth与fetch api对api进行身份验证,但它似乎没有做我想要的!

这是我的代码' ' '

const authUrl =
"https://eu.battle.net/oauth/authorize?client_id=clientid&scope=wow.profile&state=state&redirect_uri=https://localhost:3000/&response_type=code";
fetch(authUrl, {
method:"GET"
redirect: "follow",
mode: "no-cors",
});

,它应该重定向到这里https://localhost:3000/?code="code"&state="state"代码为实际的验证码。

但是当我尝试调用那个端点时,它不会重定向我回来。从开发人员控制台,我可以看到它实际上在这里做一个调用https://eu.battle.net/oauth/authorize?client_id=clientid&scope=wow.profile&state=state&redirect_uri=https://localhost:3000/&response_type=code,给出状态302。然后重定向到这个url:

https://eu.battle.net/login/en/?ref=https://eu.battle.net/oauth/authorize?client_id%3clientId%26scope%3Dwow.profile%26state%3Dsdagdf324asdas%26redirect_uri%3Dhttps://localhost:3000%26response_type%3Dcode&app=oauth给出状态200。

但不返回到localhost。但是如果我直接将authUrl粘贴到浏览器中,它就会像预期的那样工作。

我在反应里面做错了什么?

抱歉,如果我是不清楚或混淆。如果我遗漏了任何重要的东西,只要问我,我会提供的!如果有人能试着帮助我,我将不胜感激!提前感谢!

OAuth2 authentication_code流程大致如下:

  1. 将用户发送到授权url。
  2. 用户使用表单
  3. 登录
  4. 用户被重定向回。

如果用户已经登录并且存在cookie,则可以跳过2。

这个进程将永远不会与fetch一起工作,因为它的设计不是这样的。即使重定向在您手动转到url时有效,这只是因为直接转到url的安全模型与使用fetch不同。

所以你不能在fetch中这样做。相反,使用document.location将用户发送到此url。

所以你的问题在这里,看起来你没有正确地传递变量,你不能只是在javascript字符串之间包含变量,你需要使用带反引号的字符串插值。

像这样:

`https://eu.battle.net/oauth/authorize?client_id=${clientid}&scope=wow.profile&state=${state}&redirect_uri=https://localhost:3000/&response_type=code`;
fetch(authUrl, {
method:"GET"
redirect: "follow",
mode: "no-cors",
});

或者,您可以使用字符串连接。

const authUrl =
"https://eu.battle.net/oauth/authorize?client_id=" + clientid + "&scope=wow.profile&state=" + state + "&redirect_uri=https://localhost:3000/&response_type=code";
fetch(authUrl, {
method:"GET"
redirect: "follow",
mode: "no-cors",
});

最新更新