首页 文章

使用ember-cli-simple-auth的多个登录路由

提问于
浏览
2

我试图通过ember-cli-simple-auth使用身份验证来配置一个基本的ember-cli应用程序,并希望拥有一个专用的'guest'登录页面和一个不同的'admin'登录页面(授权给不同的 serverTokenEnpoint ) .

我有'guest'页面工作,即如果用户尝试浏览到受保护的路由(页面),那么它们将被重定向到默认的 /login 路由并可以登录确定 .

我可以't figure out is how to have a user that browse'到 /admin/xyz 路由,然后他们被重定向(使用 /admin/login ,然后将对不同的 serverTokenEnpoint 进行身份验证,默认为 .

谁能指出我正确的方向来实现上述目标?

谢谢 .

示例受保护的“guest”路由文件如下所示:

文件: /app/routes/protected.js

import Ember from 'ember';

import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin);

环境配置包含:

文件: /app/config/environment.js

ENV['simple-auth'] = {
    authorizer: 'simple-auth-authorizer:oauth2-bearer',
    store: 'simple-auth-session-store:local-storage',
    crossOriginWhitelist: ['http://www.domain.com/token',
                         'http://www.domain.com'
   ]
};

我甚至尝试覆盖我的 /app/routes/admin.js 文件中的默认 authenticationRoute ,如下所示,但不起作用:

import Ember from 'ember';

import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin,{
    authenticationRoute: 'admin.login'
});

因此,为了简化Marco的建议之后的过程,我现在有:

注意:此刻这不起作用.. @marcoow你有什么想法我哪里出错?

这是使用ember-cli和以下firebug输出:

AuthenticatorBase A (unknown mixin)  ***<- IS this expected????***
CustomAuthenticator B (unknown mixin)
DEBUG: -------------------------------
DEBUG: Ember                       : 1.7.0
DEBUG: Ember Data                  : 1.0.0-beta.9
DEBUG: Handlebars                  : 1.3.0
DEBUG: jQuery                      : 1.11.1
DEBUG: Ember Simple Auth           : 0.6.4
DEBUG: Ember Simple Auth OAuth 2.0 : 0.6.4
DEBUG: -------------------------------

如果我把我的手动覆盖代码放回去看看之前的答案它会工作,但由于我想对不同的URL使用相同的oauth2身份验证,我喜欢只能用自定义身份验证器覆盖 TokenEndpoint 的想法 .

file: app/initializers/simple-auth-admin.js

import AuthenticatorBase from 'simple-auth-oauth2/authenticators/oauth2';
var CustomAuthenticator = AuthenticatorBase.extend({
    serverTokenEndpoint:            AppchatENV['simple-auth-admin'].serverTokenEndpoint,
    serverTokenRevokationEndpoint:  AppchatENV['simple-auth-admin'].serverRevokationTokenEndpoint,
    refreshAccessTokens:            AppchatENV['simple-auth-admin'].refreshAccessTokens
});
console.log("AuthenticatorBase A ",AuthenticatorBase);
console.log("CustomAuthenticator B ",CustomAuthenticator);

export default {
    name:   'simple-auth-admin',
    before: 'simple-auth',
    initialize: function(container) {
        container.register('simple-auth-authenticator:admin', CustomAuthenticator);
    }
};

但是上面显示的是“AuthenticatorBase A(未知mixin)”的错误

然后在 file: app/controllers/admin/login.js

import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';
export default Ember.Controller.extend(LoginControllerMixin, {
    authenticator: 'simple-auth-authenticator:admin'
}

对于配置......

file: config/environment.js

ENV['simple-auth-admin'] = {
    serverTokenEndpoint: "http://www.domain.com/admintoken",
    serverTokenRevokationEndpoint: "http://www.domain.com/admintoken/revoke",
    refreshAccessTokens: true
  };

编辑:

所以通过设置:在文件中: app/initializers/simple-auth-admin.js

import AuthenticatorBase from 'simple-auth-oauth2/authenticators/oauth2';
var CustomAuthenticator = AuthenticatorBase.extend({
    serverTokenEndpoint:            MyappENV['simple-auth-admin'].serverTokenEndpoint,
    serverTokenRevokationEndpoint:  MyappENV['simple-auth-admin'].serverRevokationTokenEndpoint,
    refreshAccessTokens:            MyappENV['simple-auth-admin'].refreshAccessTokens
});

console.log("AuthenticatorBase.serverTokenEndpoint =",AuthenticatorBase.serverTokenEndpoint);
console.log("CustomAuthenticator.serverTokenEndpoint =",CustomAuthenticator.serverTokenEndpoint);
console.log("MyappENV['simple-auth-admin'].serverTokenEndpoint =  ",MyappENV['simple-auth-admin'].serverTokenEndpoint);

export default {
    name:   'simple-auth-admin',
    before: 'simple-auth',
    initialize: function(container) {
        container.register('simple-auth-authenticator:admin', CustomAuthenticator);
        console.log("[at container.register] CustomAuthenticator.serverTokenEndpoint =  ",CustomAuthenticator.create().get('serverTokenEndpoint'));

    }
};

我得到的输出:

AuthenticatorBase.serverTokenEndpoint = undefined
CustomAuthenticator.serverTokenEndpoint = undefined
MyappENV['simple-auth-admin'].serverTokenEndpoint =  http://www.domain.com/oauth2/admintoken
[at container.register] CustomAuthenticator.serverTokenEndpoint = http://www.domain.com/oauth2/admintoken

我是否误解了AuthenticatorBase.extend()正在做什么?我以为它会允许你覆盖一些变量或函数?

EDIT 2:

file: app/controllers/admin/login.js

import Ember from 'ember';
var $ = Ember.$;
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';
export default Ember.Controller.extend(LoginControllerMixin, {
    authenticator: 'simple-auth-authenticator:admin',
    init: function(){
        console.log('INIT LOGIN CONTROLLER', this.get('session'));
        this._super();
    },
    actions: {
        authenticate: function() { // (data)
            console.log("LoginController clicked");
            $('#nameBtn').ladda().ladda('start');
            console.log(this.get('session'));

            console.log('this.authenticator = ', this.authenticator);
            var _this = this;
            this._super().then(null, function(data) {
                console.log('LOGIN GOT BACK: ', data);
                $('#nameBtn').ladda().ladda('stop');
                    if(data.error !== undefined && data.error !== "") {
                    _this.set('data', {error: data.error});
                }
            });
        }
    }
});

这导致ajax到 www.domain.com/token 而不是预期 www.domain.com/admintoken

3 回答

  • 1

    好的,经过大量的循环编码和反复试验并得到了很多帮助:

    https://github.com/simplabs/ember-simple-auth/blob/master/examples/6-custom-server.html

    这就是我实现我想要的......

    1)将enpoints设置为环境文件中的变量(simple-auth-admin是我为管理员身份验证者选择的名称)

    档案: /app/config/environment.js

    ENV['simple-auth-admin'] = {
        serverTokenEndpoint: "http://www.domain.com/admintoken",
        serverTokenRevokationEndpoint: "http://www.domain.com/admintoken/revoke",
        refreshAccessTokens: true
    };
    

    2)在初始化程序中创建实际身份验证器作为覆盖注意:在这种情况下,实际上并未使用CustomAuthorizer并确保将AppNameENV替换为您的应用程序名称,因此如果您的应用程序被称为 bob ,则它将是 BobENV .

    档案: /app/initializers/simple-auth-admin.js

    import Ember from 'ember';
    import AuthenticatorBase from 'simple-auth/authenticators/base';
    import AuthorizerBase from 'simple-auth/authorizers/base';
    
    var CustomAuthorizer = AuthorizerBase.extend({
    authorize: function(jqXHR, requestOptions) {
        if (this.get('session.isAuthenticated') && !Ember.isEmpty(this.get('session.token'))) {
            jqXHR.setRequestHeader('Authorization', 'Token: ' + this.get('session.token'));
        }
    }
    });
    
    var CustomAuthenticator = AuthenticatorBase.extend({
    tokenEndpoint: window.AppNameENV['simple-auth-admin'].serverTokenEndpoint,
    tokenRevokationEndpoint: window.AppNameENV['simple-auth-admin'].serverRevokationTokenEndpoint,
    refreshAccessTokens: window.AppNameENV['simple-auth-admin'].refreshAccessTokens,
    init: function(){
        console.log("CUSOTMM AUTH INIT ",window.AppNameENV['simple-auth-admin'].serverTokenEndpoint);
        this._super();
    },
    restore: function(data) {
        console.log('AdminAuth - restore');
        return new Ember.RSVP.Promise(function(resolve, reject) {
            if (!Ember.isEmpty(data.token)) {
                resolve(data);
            } else {
                reject();
            }
        });
    },
    authenticate: function(credentials) {
        console.log('AdminAuth - authenticate',credentials);
        var _this = this;
        return new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                url: _this.tokenEndpoint,
                type: 'POST',
                data: JSON.stringify({ grant_type: 'password', username: credentials.identification, password: credentials.password, session: { identification: credentials.identification, password: credentials.password } }),
                        contentType: 'application/json'
                    }).then(function(response) {
                        Ember.run(function() {
                            resolve({ token: response.access_token });
                        });
                    }, function(xhr, status, error) {
                        var response = JSON.parse(xhr.responseText);
                        Ember.run(function() {
                            reject(response.error);
                        });
                    });
            });
        },
        invalidate: function() {
            console.log('AdminAuth - invalidate');
            var _this = this;
            return new Ember.RSVP.Promise(function(resolve) {
                Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
                resolve();
                })
            });
        }
    });
    
    export default {
        name:   'simple-auth-admin',
        before: 'simple-auth',
        initialize: function(container) {
            console.log("OVERRIDES : ", window.AppNameENV['simple-auth-admin']);
            container.register('simple-auth-authenticator:admin', CustomAuthenticator);
            container.register('simple-auth-authorizer:admin', CustomAuthorizer);
        }
    };
    

    3)我为任何受保护的页面设置了管理/登录的重定向路由(此示例适用于 /admin/dashboard

    档案: /app/routes/admin/dashboard.js

    import Ember from 'ember';
    import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
    
    export default Ember.Route.extend(AuthenticatedRouteMixin,{
        authenticationRoute: 'admin.login',
        actions: {
            authenticateSession: function() {
                this.transitionTo(this.authenticationRoute);
            }
        }
    });
    

    4)然后配置管理控制器以使用新的自定义验证器

    档案: /app/controllers/admin/login.js

    import Ember from 'ember';
    var $ = Ember.$;
    import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';
    //import Session from 'simple-auth/session';
    
    export default Ember.Controller.extend(LoginControllerMixin, {
        authenticator: 'simple-auth-authenticator:admin',
    });
    

    当我真正想做的事情是将/ admin / login的身份验证指向不同的serverendpoint时,所有这些似乎都有点沉重 . Marco,有没有一种方法可以覆盖这些变量,从而扩展 simple-auth-oauth2 授权器?

  • 0

    当然,你定义的路线是必要的 .

    由于管理区域的授权者和身份验证者似乎也是自定义的,因此这些也是必要的 . 如果你也使用普通的OAuth 2.0管理区域,你可以删除授权者并将验证者更改为

    import AuthenticatorBase from 'simple-auth-oauth2/authenticators/oauth2';
    
    var CustomAuthenticator = AuthenticatorBase.extend({
      serverTokenEndpoint:           'http://www.domain.com/admintoken',
      serverTokenRevokationEndpoint: 'http://www.domain.com/admintoken/revoke'
    });
    
  • 1

    每次Ember Simple Auth执行身份验证时(通常在用户访问经过身份验证的路由而未对会话进行身份验证时),它会调用ApplicationRouteMixin's authenticateSession action . 您拥有的最佳选择是覆盖它,并以某种方式决定是否从那里转换到管理员或访客登录页面 . 如果您有例如在 /admin 路由中您的管理页面命名空间,您还可以覆盖 AdminRoute 上的 authenticateSession 并从那里转换到管理员登录页面,而 ApplicationRoute 中的默认实现转换为访客登录页面 .

    对于身份验证器,最好使用默认的OAuth 2.0身份验证器及其 serverTokenEndpoint 来验证guest虚拟机,并将另一个身份验证器扩展为针对不同的 serverTokenEndpoint 验证管理员的身份验证器 .

相关问题