簡體   English   中英

獲取 API 重定向無法按我的預期工作

[英]Fetch API redirect doesn't work as i intended

你好,堆棧溢出者。 我正在使用 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。

但不回到本地主機。 但是,如果我將 authUrl 直接粘貼到瀏覽器中,它會按預期工作。

我在里面做錯了什么反應?

對不起,如果我不清楚或令人困惑。 如果我遺漏了任何重要的東西,請問我會提供! 如果有人可以嘗試幫助我,將不勝感激! 提前致謝!

所以你在這里的問題,看起來你沒有正確傳遞變量,你不能只在 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",
});

OAuth2 authentication_code 流程大致如下:

  1. 您將用戶發送到授權 url。
  2. 用戶使用表單登錄
  3. 用戶被重定向回來。

如果用戶已經登錄並且有 cookies,則可以跳過 2。

這個過程永遠不會與 fetch 一起工作,因為它的設計目的是不這樣做。 即使在您手動 go 時重定向對您有效,這只是因為直接轉到 url 的安全性 model 與使用 fetch 不同。

所以你不能用 fetch 做到這一點。 相反,使用document.location將用戶發送到此 url 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM