【问题标题】:Implicit OAuth doesn't redirect or provide call back url when using FetchAPI使用 FetchAPI 时,隐式 OAuth 不会重定向或提供回调 url
【发布时间】:2018-11-03 01:33:54
【问题描述】:

我正在使用 Fetch API 在我的组件中触发 implicit login flow for the Instagram API

但是,我的代码在其响应中返回了一个force_login URL(这是一个 200 状态)。

当我从这里更改我的代码时,我只会收到访问令牌:

  onLoginClick(){
    //https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
    var resource = instagramAPI+"?client_id="+this.props.clientId+"&redirect_uri="+this.props.redirect_uri+"&response_type="+this.props.type;
    fetch(resource)
    .then(function(data){
      console.log("fetched the data!")
      console.log(data.url);
      //window.location.href=data.url;
    })
    .catch(function(error){
      console.log(error);
    })
  }

…到这个:

  onLoginClick(){
    //https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
    var resource = instagramAPI+"?client_id="+this.props.clientId+"&redirect_uri="+this.props.redirect_uri+"&response_type="+this.props.type;
    fetch(resource)
    .then(function(data){
      console.log("fetched the data!")
      console.log(data.url);
      window.location.href=data.url;
    })
    .catch(function(error){
      console.log(error);
    })
  }

为什么我需要添加window.location.href=data.url; 行? 为什么我无法在 data.url 上运行 fetch 并将 URL 令牌填充到响应数据中?

【问题讨论】:

  • 您能否阐明预期行为与实际行为是什么? onLoginClick() 应该做什么?
  • 有一个点击按钮会触发onLoginClick(),它应该可以通过 Instagram API 并接收带有访问令牌的响应。它似乎仅在您制作window.location.href 时才有效。我希望让它返回类似于 AJAX 调用的正确响应,不需要重新加载整个页面。

标签: javascript reactjs oauth-2.0 instagram-api fetch-api


【解决方案1】:

原因是令牌不会在响应数据中,而是在返回的标头中。如果身份验证成功,Instagram 会在标头中发出重定向。此重定向中包含访问令牌。

当您使用 window.location.href 时,您是在告诉浏览器完成它的工作,它会转发到重定向并因此包含访问令牌。

如果您希望令牌不转发,请查看 data.headers。我没有使用JS来获取,所以我不确定标题的确切名称。可能是“重定向”。试试:

console.log(data.headers);

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2014-01-30
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多