Ember Simple Auth supports all Ember.js versions starting with 3.0.Node 12 is required
Ember Simple Auth is a lightweight library for implementing authentication/authorization with Ember.js applications. It hasminimal requirements with respect to application structure, routes etc. Withits pluggable strategies it can support all kinds of authentication andauthorization mechanisms.
Basic Information
Usage
Core Feature Guides
Other Guides
Other Resources
Ember Simple Auth consists of 3 main building blocks - the session, asession store and authenticators.
The session service is the main interface to the library. It providesmethods for authenticating and invalidating the session as well as forsetting and reading session data.
The session store persists the session state so that it survives a pagereload. It also synchronizes the session state across multiple tabs or windowsof the application so that e.g. a logout in one tab or window also results in alogout in all other tabs or windows of the application.
Authenticators authenticate the session. An application can leveragemultiple authenticators to support multiple ways of authentication such assending credentials to the application's own backend server, Facebook, githubetc.
Ember Simple Auth comes with atest appthat implements a complete auth solution including authentication againstthe application's own server as well as Facebook, authorization of Ember Datarequests and error handling. Check out that test app for reference. Tostart it, run
git clone https://github.com/simplabs/ember-simple-auth.git
cd ember-simple-auth/packages/test-app
yarn install && ember serve
and go to http://localhost:4200.
Installing the library is as easy as:
ember install ember-simple-auth
The 3.0 release of ember-simple-auth removes previously deprecated code,introducing some breaking changes, but thankfully there is anupgrade guide.
Once the library is installed, the session service can be injected whereverneeded in the application. In order to display login/logout buttons dependingon the current session state, inject the service into the respective controlleror component and query itsisAuthenticated
propertyin the template:
// app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default class ApplicationController extends Controller {
@service session;
…
}
In the invalidateSession
action call thesession service's invalidate
methodto invalidate the session and log the user out:
// app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from "@ember/object";
export default class ApplicationController extends Controller {
@service session;
…
@action
invalidateSession() {
this.session.invalidate();
}
}
For authenticating the session, the session service provides theauthenticate
methodthat takes the name of the authenticator to use as well as other argumentsdepending on specific authenticator used. To define an authenticator, add anew file in app/authenticators
and extend one of the authenticators thelibrary comes with, e.g.:
// app/authenticators/oauth2.js
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default class OAuth2Authenticator extends OAuth2PasswordGrant {}
With that authenticator and a login form like
the session can be authenticated with thesession service's authenticate
method:
// app/controllers/login.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from "@ember/object";
import { tracked } from "@glimmer/tracking";
export default class LoginController extends Controller {
@tracked errorMessage;
@service session;
@action
async authenticate(e) {
e.preventDefault();
let { identification, password } = this;
try {
await this.session.authenticate('authenticator:oauth2', identification, password);
} catch(error) {
this.errorMessage = error.error || error;
}
if (this.session.isAuthenticated) {
// What to do with all this success?
}
}
@action
updateIdentification(e) {
this.identification = e.target.value;
}
@action
updatePassword(e) {
this.password = e.target.value;
}
}
To make a route in the application accessible only when the session isauthenticated, call the session service'srequireAuthentication
method in the respective route's beforeModel
method:
// app/routes/authenticated.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class AuthenticatedRoute extends Route {
@service session;
beforeModel(transition) {
this.session.requireAuthentication(transition, 'login');
}
}
This will make the route (and all of its subroutes) transition to the login
route if the session is not authenticated. Add the login
route in the routerlike this:
// app/router.js
Router.map(function() {
this.route('login');
});
It is recommended to nest all of an application's routes that require thesession to be authenticated under a common parent route:
// app/router.js
Router.map(function() {
this.route('login');
this.route('authenticated', { path: '' }, function() {
// all routes that require the session to be authenticated
});
});
To prevent a route from being accessed when the session is authenticated (whichmakes sense for login and registration routes for example), call the sessionservice'sprohibitAuthentication
method in the respective route's beforeModel
method:
// app/routes/login.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class LoginRoute extends Route {
@service session;
beforeModel(transition) {
this.get('session').prohibitAuthentication('index');
}
}
The session service also provides thehandleAuthentication
andhandleInvalidation
methods for handling authentication and invalidation of the session (whichnot only happens when the user submits the login form or clicks the logoutbutton but also when the session is authenticated or invalidated in another tabor window of the application). The handleAuthentication
method willtransition to a configurable route while the handleInvalidation
method willreload the page to clear all potentially sensitive data from memory. In orderto customize those behaviours, these methods can be overridden when theapplication defines its own session service that extends the one provided byEmber Simple Auth.
To add authorization information to requests, you can use the session serviceto check if the session is authenticated and accessauthentication/authorization data, e.g. a token:
// app/adapters/application.js
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default class ApplicationAdapter extends JSONAPIAdapter {
@service session;
@computed('session.{data.authenticated.access_token,isAuthenticated}')
get headers() {
let headers = {};
if (this.session.isAuthenticated) {
// OAuth 2
headers['Authorization'] = `Bearer ${this.session.data.authenticated.access_token}`;
}
return headers;
}
}
The session service is the main interface to the library. It defines theauthenticate
, invalidate
and authorize
methods as well as the sessionevents as shown above.
It also provides theisAuthenticated
as well as thedata
properties. The latter can be used to get and set the session data. While thespecial authenticated
section in the session data contains the data that wasacquired by the authenticator when it authenticated the session and isread-only, all other session data can be written and will also remain in thesession after it is invalidated. It can be used to store all kinds of clientside data that needs to be persisted and synchronized across tabs and windows,e.g.:
this.session.set('data.locale', 'de');
Authenticators implement the concrete steps necessary to authenticate thesession. An application can leverage several authenticators for differentkinds of authentication mechanisms (e.g. the application's own backend server,external authentication providers like Facebook etc.) while the session is onlyever authenticated with one authenticator at a time. The authenticator to useis chosen when authentication is triggered via the name it is registered within the Ember container:
this.session.authenticate('authenticator:some');
Ember Simple Auth comes with 4 authenticators:
OAuth2PasswordGrantAuthenticator
: an OAuth 2.0 authenticator that implements the "Resource Owner Password Credentials Grant Type"OAuth2ImplicitGrantAuthenticator
: an OAuth 2.0 authenticator that implements the "Implicit Grant Type"DeviseAuthenticator
: an authenticator compatible with the popular Ruby on Rails authentication plugin deviseToriiAuthenticator
: an authenticator that wraps the torii libraryTo use any of these authenticators in an application, define a newauthenticator in app/authenticators
, extend if from the Ember Simple Authauthenticator
// app/authenticators/oauth2.js
import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default class OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator {}
and invoke the session service's authenticate
method with the respectivename, specifying more arguments as needed by the authenticator:
this.session.authenticate('authenticator:some', data);
Authenticators are easily customized by setting the respective properties,e.g.:
// app/authenticators/oauth2.js
import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default class OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator {
serverTokenEndpoint = '/custom/endpoint';
}
Besides extending one of the predefined authenticators, an application can alsoimplement fully custom authenticators. In order to do that, extend theabstract base authenticatorthat Ember Simple Auth comes with and override theauthenticate
,restore
and (optionally)invalidate
methods:
// app/authenticators/custom.js
import Base from 'ember-simple-auth/authenticators/base';
export default class CustomAuthenticator extends Base {
restore(data) {
…
}
authenticate(options) {
…
}
invalidate(data) {
…
}
}
Ember Simple Auth persists the session state via a session store so itsurvives page reloads. There is only one store per application that can bedefined in app/session-stores/application.js
:
// app/session-stores/application.js
import Cookie from 'ember-simple-auth/session-stores/cookie';
export default class ApplicationSessionStore extends Cookie {}
If the application does not define a session store, the adaptive store whichuses localStorage
if that is available or a cookie if it is not, will be usedby default. To customize the adaptive store, define a custom store inapp/session-stores/application.js
that extends it and overrides theproperties to customize.
Ember Simple Auth comes with 4 stores:
The adaptive storestores its data in the browser's localStorage
if that is available or in acookie if it is not; this is the default store.
localStorage
StoreThe localStorage
storestores its data in the browser's localStorage
. This is used by the adaptivestore if localStorage
is available.
The Cookie storestores its data in a cookie. This is used by the adaptive store iflocalStorage
is not available. This store must be used when theapplication usesFastBoot.
sessionStorage
StoreThe sessionStorage
storestores its data in the browser's sessionStorage
. See the Web Storage docs for details onsessionStorage
and localStorage
. caniusehas up-to-date information on browser support of sessionStorage
and localStorage
.
The ephemeral storestores its data in memory and thus is not actually persistent. This store ismainly useful for testing. Also the ephemeral store cannot keep multiple tabsor windows in sync as tabs/windows cannot share memory.
The session store is easily customized by setting the respective properties,e.g.:
// app/session-stores/application.js
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';
export default class ApplicationSessionStore extends AdaptiveStore {
cookieName = 'my-apps-session-cookie';
}
Besides using one of the predefined session stores, an application can alsoimplement fully custom stores. In order to do that, extend theabstract base session storethat Ember Simple Auth comes with and implement thepersist
,restore
andclear
methods:
// app/session-stores/application.js
import Base from 'ember-simple-auth/session-stores/base';
export default class ApplicationSessionStore extends Base {
persist() {
…
}
restore() {
…
}
}
Ember Simple Auth works with FastBoot out of the box as long as the Cookiesession store is being used. In order to enable the cookie store, define it asthe application store:
// app/session-stores/application.js
import CookieStore from 'ember-simple-auth/session-stores/cookie';
export default class ApplicationSessionStore extends CookieStore {}
If you are using theOAuth2PasswordGrantAuthenticator
,orDeviseAuthenticator
,you must add node-fetch
to your list of FastBoot whitelisted dependenciesin package.json
:
{
"fastbootDependencies": [
"node-fetch"
]
}
Ember Simple Auth works with engines out of the box. The host app and anyengine(s) share the same session
service so they can synchronize theauthentication status:
// my-engine/addon/routes/index.js
import Application from '@ember/application';
import loadInitializers from 'ember-load-initializers';
class App extends Application {
…
engines = {
'my-engine': {
dependencies: {
services: [
'session'
]
}
}
}
});
…
export default App;
The session can then be authenticated or invalidated from the host app or anyof the engines and the state will be synchronized via the service.
One thing to be aware of is that if the authentication route is outside of theengine (e.g. in the host app), it is necessary to use the specialtransitionToExternal
method in the engine to transition to it. That can bedone by passing a callback instead of a route name to the session service'srequireAuthentication
method in that case:
// my-engine/addon/routes/index.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class IndexRoute extends Route {
@service session;
beforeModel(transition) {
this.get('session').requireAuthentication(transition, () => this.transitionToExternal('login'));
},
}
Ember Simple Auth comes with a set of test helpers that can be used in acceptance tests.
Our helpers use the more modern testing syntaxand therefore require ember-cli-qunit
4.2.0 or greateror ember-qunit
3.2.0 or greater.
We provide the following helpers:
currentSession()
returns the current session.authenticateSession(sessionData)
authenticates the session asynchronously;the optional sessionData
argument can be used to mock the response of anauthentication request, to provide a specific authorization token or userdata.invalidateSession()
invalidates the session asynchronously.Which can be used as shown in the following example:
import { module, test } from 'qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { currentSession, authenticateSession, invalidateSession } from 'ember-simple-auth/test-support';
module('Acceptance | app test', function(hooks) {
setupApplicationTest(hooks);
test('/login redirects to index if user is alread logged in', async function(assert) {
await authenticateSession({
authToken: '12345',
otherData: 'some-data'
});
await visit('/login');
assert.equal(currentURL(), '/');
let sessionData = currentSession().get('data.authenticated');
assert.equal(sessionData.authToken, '12345');
assert.equal(sessionData.otherData, 'some-data');
});
test('/protected redirects to /login if user is not logged in', async function(assert) {
await invalidateSession();
await visit('/protected');
assert.equal(currentURL(), '/login');
});
});
If you're an ember-mocha
user, we can recommend to check out thisexample from the test suite of ember-simple-auth itself.
Ember Simple Auth is developed by and ©simplabs GmbH and contributors. It isreleased under theMIT License.
Ember Simple Auth is not an official part of Ember.js andis not maintained by the Ember.js Core Team.
Ember Simple Auth Token This is Ember addon is an extension to the Ember Simple Auth library that provides a basic token authenticator, a JSON Web Tokens token authenticator with automatic refresh cap
@zestia/ember-simple-infinite-scroller This Ember addon provides a simple component that fires an action whenever it is scrolled to the bottom.Allowing you to load more data. It is not coupled to Embe
To install Tengine, just follow these three steps: $ ./configure $ make # make install By default, it will be installed to /usr/local/nginx. You can use the '--prefix' option to specify the root dire
插入 // 单条插入 User user=new User(); // 省略entity属性赋值... ... elasticsearchTemplate.save(user); // 批量插入 LinkedList<User> users= new LinkedList<User>(); // 省略entity属性赋值... ... elasticsearchTemplate.save(user
描述 (Description) 无需使用填充和颜色即可创建简单菜单。 .simple类包含在菜单中以创建一个简单的菜单栏。 例子 (Example) 以下示例演示了在Foundation中使用简单样式 - <!DOCTYPE html> <html> <head> <title>Foundation Template</title> <meta name = "vi
辅助 mpvue 快速开发 Page 级小程序页面的工具,所以也需要有一定的小程序开发经验。 mpvue QuickStart 只支持项目级应用开发,对 Page 级和自定义组件 Component 级小程序页面开发场景缺少支持,而 simple 刚好来填补这部分需求,用以支持 mpvue 和原生小程序(或者其他方式小程序)的混用。 工具用法 command line # install by g