Github oauth回调URL在井号前添加了查询字符串

3

我正在尝试在Vue项目中实现Oauth(使用Github),当我的回调URL从Github被调用时,它会在URL的哈希之前附加查询字符串?code=something

例如,如果我在浏览器中加载https://myapp.com并单击我的登录链接<a href="https://github.com/login/oauth/authorize?scope=user:email&client_id=1234j1234jk&redirect_uri=https://myapp.com/#/something">Login</a>,将重定向到https://myapp.com/?code=asdfasdf#/something,这意味着this.$route.query为空。

作为Vue和Oauth的新手,我该如何解决这个问题,以便当我的回调被调用时,它会转到https://myapp.com/#/something?code=asdfadsf,以便this.$route.query包含代码?

2个回答

3

Github可能因为#而搞乱了事情。作为解决方法,您可以让Github重定向到另一个端点,比如www.yourhost.com/api/v1/redirect-to-home?code=ABCDE(其中没有#),然后在那里正确地重定向到https://myapp.com/#/something?code=ABCDE


我已经实现了这个,它似乎运行得很好。实际上比我预期的要好得多,因为当我被重定向到我的后端时,我使用代码调用github来获取access_token,然后将其重定向回UI。 - Catfish
@Catfish 是的,这对我来说似乎是“不那么hacky”的选项。它在程序流程中增加了一定的间接性,但它保持了一切简单和相对容易理解。 - Gabriel

1
Github 在这里做正确的事情,因为 OAuth 使用 url 的查询部分,而不会更改锚点。
你可以在启动过程中检测并手动调整 url,具体方法如下:
在主要的 bootstrap.js 文件(即你执行 new Vue 的文件)中,你可以手动检测这个锚点,并在 Vue 加载之前更新路径。
这可以通过从 bootstrap 文件检查 window.location,然后调用 window.location.href.replace 来替换 url 而不进行可见重定向来完成。
// getParameterByName from https://dev59.com/nHNA5IYBdhLWcg3wmfAa#901144 
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

const code = getParameterByName('code');
if(code) {
    const l = window.location;
    window.location.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname + '123#' + l.hash + '?code=' + code);
}

其他人在Vue.js应用程序中处理github oauth的方式是这样的吗?看起来有点hacky。 - Catfish
大多数人使用Vue Router的“history”模式,虽然它需要一些特殊的服务器端配置来处理路径,但你可以通过https://myapp.com/something?code=asdfadsf访问你的应用程序,并以此方式访问this.$route.query。我假设你没有使用历史模式是有原因的。 - Ferrybig
没有特别的原因我没有使用历史模式。我是Vue的新手,不知道这个功能。而且我也不想为此调整我的服务器配置。我希望这个问题可以在应用程序层面解决。 - Catfish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接