問題描述
import request from 'superagent';
const self = this;
request
.post('https://github.com/login/oauth/access_token')
.set('Content-Type', 'multipart/form-data')
.query({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
callback: 'http://127.0.0.1:3000/callback',
code,
state,
})
.end((err, res) => {
const token = res.body.access_token;
console.log(token);
self.setToken(token);
});
上面的代碼會給我這樣的錯誤
The code above will give me an error like this
XMLHttpRequest 無法加載https://github.com/login/oauth/access_token?client_id=112asdecf3805fdada12&…127.0.0.1%3A3000%2Fcallback&code=434ebd7bb98d9809bf6e&state=HelloWorld1234.請求中不存在Access-Control-Allow-Origin"標(biāo)頭資源.因此,不允許使用來源 'http://127.0.0.1:3000'訪問.
XMLHttpRequest cannot load https://github.com/login/oauth/access_token?client_id=112asdecf3805fdada12&…127.0.0.1%3A3000%2Fcallback&code=434ebd7bb98d9809bf6e&state=HelloWorld1234. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.
我不知道為什么即使我已經(jīng)使用 github 注冊了 oauth 應(yīng)用程序并且回調(diào) url 是 http://127.0.0.1:3000/callback
I have no idea why even though I've registered the oauth application with github and callback url is http://127.0.0.1:3000/callback
推薦答案
雖然所有實際的 GitHub API 端點通過發(fā)送正確的響應(yīng)頭來支持 CORS,它是 一個已知的問題 用于創(chuàng)建 OAuth 訪問令牌的 https://github.com/login/oauth/access_token
端點不支持來自 Web 應(yīng)用程序的 CORS 請求.
While all the actual GitHub API endpoints support CORS by sending the right response headers, it is a known issue that the https://github.com/login/oauth/access_token
endpoint for creating an OAuth access token does not support CORS requests from Web applications.
這種情況的非常具體的解決方法是使用 https://github.com/prose/gatekeeper:
The very specific workaround for this case is to use https://github.com/prose/gatekeeper:
Gatekeeper:使客戶端應(yīng)用程序能夠與 GitHub 共舞 OAuth.
由于一些與安全相關(guān)的限制,Github 阻止您在僅客戶端應(yīng)用程序上實施 OAuth Web 應(yīng)用程序流程.
Because of some security-related limitations, Github prevents you from implementing the OAuth Web Application Flow on a client-side only application.
這真是太糟糕了.因此,我們構(gòu)建了 Gatekeeper,這是您使其工作所需的缺失部分.
This is a real bummer. So we built Gatekeeper, which is the missing piece you need in order to make it work.
一般的解決方法是:使用開放的反向代理,例如 https://cors-anywhere.herokuapp.com/
The general workaround is: Use an open reverse proxy like https://cors-anywhere.herokuapp.com/
var req = new XMLHttpRequest();
req.open('POST',
'https://cors-anywhere.herokuapp.com/https://github.com/login/oauth/access_token',
true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send('code=' + encodeURIComponent(location.query.code) +
'&client_id=foo' +
'&client_secret=bar');
...
另請參閱 如何在任何地方使用 Cors 進(jìn)行反向代理和添加 CORS 標(biāo)頭.
這篇關(guān)于github oauth 上的 cors 問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!