4

我有一种情况,我希望能够根据 URL 中的确认令牌参数自动登录用户。在我的路线中,我向服务器发出 AJAX 请求以验证令牌并发送回用于登录的相同序列化 Oauth2 JSON。

是否可以使用此令牌登录用户?

首先,用户转到如下 URL:

http://example.com/users/confirmation?confirmation_token=eisz6LMzmck55xHuqopF

接下来,我的路由向服务器发送一个 AJAX 请求,该服务器使用 Oauth2 令牌进行回复。

这是我当前尝试使用身份验证器来恢复它的实现。尽管在控制台中看到“我应该登录”,但它不起作用。我怀疑这是因为它不知道恢复会话。查看会话文档,我看到了一种手动身份验证的公共方法,但没有从 oauth 令牌恢复的方法。

import Ember from 'ember';
import ajax from 'ic-ajax';

export default Ember.Route.extend({
  model: function(params) {
    var path = MyApp.API_NAMESPACE + '/confirmation?confirmation_token=' + params.confirmation_token;
    var authenticator = this.container.lookup('simple-auth-authenticator:oauth2-password-grant');

    return ajax(path).then(function(response) {
      return authenticator.restore(response).then(function() {
        console.log('I should be logged in');
      });
    }).catch(function(request) {
      console.log(request);
    });
  }
});
4

1 回答 1

0

我通过创建一个基本上继承自 oauth2 身份验证器的自定义身份验证器解决了这个问题,只覆盖了该authenticate方法。

首先,我在以下位置创建了身份验证器app/lib/confirmation-authenticator.js

import OAuth2Authenticator from 'simple-auth-oauth2/authenticators/oauth2';
import ajax from 'ic-ajax';

export default OAuth2Authenticator.extend({
  authenticate: function(token) {
    var path = MyApp.API_NAMESPACE + '/confirmation?confirmation_token=' + token;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      ajax(path).then(function(response) {
        resolve(response);
      }).catch(function(request) {
        reject(request.textStatus);
      });
    });
  }
});

然后在我的初始化程序中注册身份验证器app/initializers/authentication

import ConfirmationAuthenticator from 'my-app/lib/confirmation-authenticator';

export default {
  name: 'authentication',
  before: 'simple-auth',

  initialize: function(container) {
    container.register('simple-auth-authenticator:confirmation', ConfirmationAuthenticator);

    window.ENV = window.ENV || {};

    window.ENV['simple-auth'] = {
      authorizer: 'simple-auth-authorizer:oauth2-bearer',
    };

    window.ENV['simple-auth-oauth2'] = {
      serverTokenEndpoint: MyApp.API_NAMESPACE + '/oauth/token'
    };
  }
};

最后是我的路线app/routes/users/confirmation.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    var token = params.confirmation_token;

    return this.get('session').authenticate('simple-auth-authenticator:confirmation', token);
  }
});
于 2014-08-29T19:27:07.800 回答