繁体   English   中英

如何从 URL 中删除访问令牌

[英]How to remove accesstoken from the URL

现在我正在从 url 获取访问令牌。 我在后端使用 GET 请求,它将 accesstoken 传递给 URL。 他们的关键问题是,在我成功登录后,访问令牌保留在 URL 中。 我不知道如何摆脱它。

function App() {
  // ( getSpotifyTokenFromUrl() ) That function is getting me the token from the url
  const params = getSpotifyTokenFromUrl();
  const token = params.access_token;

  return (
    <Router>
      <div className="app">
        {token ? 
          <Route path="hompage">
            <Homepage spotify={spotify}/>
          </Route>
        : <Home />}
      </div>
    </Router>
  )

我也尝试在index.js文件中这样做

ReactDOM.render(
  <Router>
    <App>
      <Route exact path="/hompage" component={Homepage} />
    </App>
  </Router>,
  document.getElementById('root'));

这是我的后端代码的一小部分,它将令牌传递给浏览器。 也许我必须再次重定向,但是如何呢?

res.redirect('http://localhost:3000/#' +
  querystring.stringify({
    access_token: access_token,
    refresh_token: refresh_token
  }));

我知道为时已晚,但也许答案会帮助其他人。 我在这个链接中找到了您的答案: https ://gist.github.com/DavidWells/ea3e43886534ff7c3efb6d389766e588 您可以像这样更改 App 功能:

function App() {
   const {location, history} = window;
   const {search} = location;
   const params = getSpotifyTokenFromUrl();
   var token = null;
   if (params !== null) {
     token = params.access_token;
     if (search && search.indexOf('access_token') !== -1 && history && 
         history.replaceState) {
         // remove access_token from url
         const cleanSearch = search.replace(/(\&|\?)access_token[^\&]*/g, 
         '').replace(/^&/, '?');
         // replace search params with clean params
         const cleanURL = location.toString().replace(search, cleanSearch)
         // use browser history API to clean the params
         history.replaceState({}, '', cleanURL)
         }
       }
   return (
     <Router>
      <div className="app">
       {token ? 
        <Route path="hompage">
          <Homepage spotify={spotify}/>
        </Route>
        : <Home />}
     </div>
    </Router>
    )     
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM