Jef*_*les 3 ruby-on-rails github-api oauth-2.0 ember.js torii
我正试图在Torii中使用github-oauth2提供程序,但我很难理解我应该如何设置一些回调.我将跟踪我正在使用的代码,以及我对它的理解,并希望这可以帮助确定我出错的地方.
首先,在我的行动中,我正在调用torii的open方法,就像它在文档中所说的那样:
this.get('torii').open('github-oauth2').then((data) => {
this.transitionTo('dashboard')
})
Run Code Online (Sandbox Code Playgroud)
当然,我在我的设置中有以下设置config/environment.js:
var ENV = {
torii: {
// a 'session' property will be injected on routes and controllers
sessionServiceName: 'session',
providers: {
'github-oauth2': {
apiKey: 'my key',
redirectUri: 'http://127.0.0.1:3000/github_auth'
}
}
},
}
Run Code Online (Sandbox Code Playgroud)
redirectUri用于我的Rails服务器.我在我的github应用程序上有相同的redirectUri设置,所以它们匹配.
这是我在服务器上的内容.这可能就是问题所在.我会在最后得到症状.
def github
client_id = 'my id'
client_secret = 'my secret'
code = params[:code]
@result = HTTParty.post("https://github.com/login/oauth/access_token?client_id=#{client_id}&client_secret=#{client_secret}&code=#{code}")
@access_token = @result.parsed_response.split('&')[0].split('=')[1]
render json: {access_token: @access_token}
end
Run Code Online (Sandbox Code Playgroud)
所以我发布到github的access_token端点,就像我应该的那样,我得到一个带有访问令牌的结果.然后我将该访问令牌打包为json.
结果是torii弹出窗口转到rails页面:
不幸的是,我所希望的是torii弹出窗口消失,给我的应用程序access_token,并让代码继续前进并执行我的then块中的代码.
我哪里错了?
非常感谢Kevin Pfefferle,他帮助我解决了这个问题,并将代码分享给了他的应用程序(gitzoom),他已经实现了一个解决方案.
所以第一个修复是清除我的redirectUri,并将其设置在github上localhost:4200.这使得应用程序重定向,因此它是重定向到的Ember应用程序.
第二个修复是创建自定义torii提供程序
//app/torii-providers/github.js
import Ember from 'ember';
import GitHubOauth2Provider from 'torii/providers/github-oauth2';
export default GitHubOauth2Provider.extend({
ajax: Ember.inject.service(),
fetch(data) {
return data;
},
open() {
return this._super().then((toriiData) => {
const authCode = toriiData.authorizationCode;
const serverUrl = `/github_auth?code=${authCode}`;
return this.get('ajax').request(serverUrl)
.then((data) => {
toriiData.accessToken = data.token;
return toriiData;
});
});
}
});
Run Code Online (Sandbox Code Playgroud)
不知道为什么这then会触发,但then我之前没有使用过.无论如何,它抓取数据并返回它,然后我正在使用的承诺才能正确获取数据.
this.get('torii').open('github-oauth2').then((data) => {
//do signon stuff with the data here
this.transitionTo('dashboard')
})
Run Code Online (Sandbox Code Playgroud)
我们去了!希望这有助于其他陷入困境的人们.