在my previous question about ember-simple-auth and torii之后,我使用他们的Facebook帐户成功验证了我的用户 .
但目前,torii的提供商facebook-oauth2正在从Facebook返回授权码;当承诺解决时,我将此授权代码发送到我的后端,在那里我执行针对Facebook的请求以获取用户的ID和电子邮件:然后我在我的后端验证用户,生成特定的访问令牌并发送回我的ember应用程序 .
客户代码:
// app/controllers/login.js
import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';
export
default Ember.Controller.extend(LoginControllerMixin, {
// This authenticator for a simple login/password authentication.
authenticator: 'simple-auth-authenticator:oauth2-password-grant',
actions: {
// This method for login with Facebook.
authenticateWithFacebook: function() {
var _this = this;
this.get('session').authenticate(
'simple-auth-authenticator:torii',
"facebook-oauth2"
).then(
function() {
var authCode = _this.get('session.authorizationCode');
Ember.$.ajax({
type: "POST",
url: window.ENV.host + "/facebook/auth.json",
data: JSON.stringify({
auth_code: authCode
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// TODO : manage access_token and save it to the session
},
failure: function(errMsg) {
// TODO : manage error
}
});
},
function(error) {
alert('There was an error when trying to sign you in: ' + error);
}
);
}
}
});
问题是:当authenticate的promise解析后,ember-simple-auth的会话被标记为已验证,然后app会重定向到特定的已验证路由 . 但在这种情况下,当我的后端返回“真正的”access_token时,应该对会话进行身份验证 .
有没有办法用ember-simple-auth-torii管理这个工作流程,还是应该编写自己的身份验证器?
3 回答
正如Beerlington建议的那样,我终于编写了自己的身份验证器 . 但是我也给了我的用户一种使用登录/密码进行身份验证的方法,所以我覆盖了ember-simple-auth-oauth2身份验证器,仅更改了“authenticate”方法并使用了ember-simple-auth-torii .
现在我可以使用Torii从用户的Facebook帐户获取授权代码,将此代码发送到我的后端,验证用户身份并生成一个访问令牌,该令牌将由ember-simple-auth管理,如oauth2令牌 .
这是代码:
我的后端在Rails中,并使用Doorkeeper来管理access_token和Devise . 我重写了Doorkeeper :: TokensController以传递带有令牌的user_id并管理facebook的授权码(如果有的话)(该代码应该被重构):
这是我在初始化程序doorkeeper.rb中使用的代码,用于验证用户身份
我花了几天时间试图弄清楚如何使它与torii一起工作,最后放弃了我自己的身份验证器 . 这是来自torii和ember-simple-auth的代码的混合,因此它不是最干净的,并且可能无法处理所有边缘情况 . 它基本上扩展了ember-simple-auth oauth2身份验证器,并添加了自定义代码以将访问令牌传递给API .
应用程序/ LIB / Facebook的authenticator.js
我用过这个: