这里是recent ember-cli-simple-auth setup instructions from the author
您不必手动设置初始化程序。我可以验证作者的说明是否应该在您的控制器中为您提供 this.session。
复制author's instructions:
现在在 ember-cli 项目中安装 Ember Simple Auth 非常简单。您所要做的就是从 npm 安装 ember-cli 插件:
npm install --save-dev ember-cli-simple-auth
这会将 Ember Simple Auth 的 AMD 发行版安装到项目中,注册初始化程序,以便 Ember Simple Auth 自动设置自己并将自己作为依赖项添加到项目的 package.json。
您可以添加登录路由和登录/注销链接来验证它是否真的有效:
// app/router.js
…
Router.map(function() {
this.route('login');
});
…
// app/templates/application.hbs
…
{{#if session.isAuthenticated}}
<a {{ action 'invalidateSession' }}>Logout</a>
{{else}}
{{#link-to 'login'}}Login{{/link-to}}
{{/if}}
…
同样在项目的应用路由中实现ApplicationRouteMixin:
// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin);
设置身份验证
要真正让用户选择登录,我们需要为 Ember Simple Auth 添加一个身份验证包。假设您有一个运行在 http://localhost:3000 的 OAuth 2.0 兼容服务器。要使用它,请安装 OAuth 2.0 扩展库,这与从 npm 安装包一样简单:
npm install --save-dev ember-cli-simple-auth-oauth2
与 ember-cli-simple-auth 包一样,它会自行设置,因此无需执行任何其他操作即可使用 OAuth 2.0 功能。
OAuth 2.0 身份验证机制需要一个登录表单,所以让我们创建它:
// app/templates/login.hbs
<form {{action 'authenticate' on='submit'}}>
<label for="identification">Login</label>
{{input id='identification' placeholder='Enter Login' value=identification}}
<label for="password">Password</label>
{{input id='password' placeholder='Enter Password' type='password' value=password}}
<button type="submit">Login</button>
</form>
然后在登录控制器中实现 LoginControllerMixin 并使其使用 OAuth 2.0 身份验证器来执行实际的身份验证:
// app/controllers/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:oauth2-password-grant'
});
由于 OAuth 2.0 身份验证器默认使用相同的域和端口将身份验证请求发送到从中加载 Ember.js,因此您需要将其配置为使用 http://localhost:3000:
// config/environment.js
if (environment === 'development') {
…
ENV['simple-auth-oauth2'] = {
serverTokenEndpoint: 'http://localhost:3000/token'
}
…
由于 ember-cli 将所有配置添加到全局 ENV 变量(例如,在本例中为 MyAuthAppENV),Ember Simple Auth 无法使用,因为它不知道它的名称,您需要将其复制到 window.ENV 以便 Ember Simple Auth可以使用:
// app/initializers/simple-auth-config.js
export default {
name: 'simple-auth-config',
before: 'simple-auth',
initialize: function() {
window.ENV = MyAuthAppENV;
}
};
Ember Simple Auth 很棒!