All Projects → fenichelar → ember-simple-auth-token

fenichelar / ember-simple-auth-token

Licence: MIT License
Ember Simple Auth extension that is compatible with token-based authentication like JWT.

Programming Languages

javascript
184084 projects - #8 most used programming language
HTML
75241 projects

Projects that are alternatives of or similar to ember-simple-auth-token

ember-do-forms
ember-do-forms handles the icky parts of forms that you don't want to, and leaves the rest to you.
Stars: ✭ 18 (-94.94%)
Mutual labels:  ember, ember-addon
ember-cli-daterangepicker
Just a simple component to use bootstrap-daterangepicker.
Stars: ✭ 32 (-91.01%)
Mutual labels:  ember, ember-addon
ember-google-analytics-embed
An Ember Addon for adding analytics visualizations using the Google Analytics Embed API.
Stars: ✭ 26 (-92.7%)
Mutual labels:  ember, ember-addon
ember-google-charts
Google's Material charts made easy for Ember apps - http://sir-dunxalot.github.io/ember-google-charts/
Stars: ✭ 31 (-91.29%)
Mutual labels:  ember, ember-addon
ember-fsm
[Maintenance Mode] A promise-aware finite state machine implementation for Ember
Stars: ✭ 37 (-89.61%)
Mutual labels:  ember, ember-addon
ember-shadow-dom
Write templates for your components inside of a Shadow DOM root.
Stars: ✭ 26 (-92.7%)
Mutual labels:  ember, ember-addon
ember-luxon
🕐 🌐 [deprecated] Addon thats brings Luxon to Ember applications.
Stars: ✭ 20 (-94.38%)
Mutual labels:  ember, ember-addon
ember-useragent
An Ember addon for Fastboot-enabled UserAgent parsing via UAParser.js.
Stars: ✭ 34 (-90.45%)
Mutual labels:  ember, ember-addon
ember-uikit
The ember implementation of UIkit
Stars: ✭ 24 (-93.26%)
Mutual labels:  ember, ember-addon
ember-bootstrap-power-select
Integrate ember-power-select into your ember-bootstrap forms
Stars: ✭ 37 (-89.61%)
Mutual labels:  ember, ember-addon
ember-named-yields
Named Yields for Ember Components
Stars: ✭ 17 (-95.22%)
Mutual labels:  ember, ember-addon
els-addon-typed-templates
Ember templates linting / autocomplete, based on Typescript language server
Stars: ✭ 27 (-92.42%)
Mutual labels:  ember, ember-addon
ember-cli-ifa
Ember CLI addon for injecting fingerprinted asset map file into Ember app
Stars: ✭ 54 (-84.83%)
Mutual labels:  ember, ember-addon
ember-query-params
Ember service for your query params
Stars: ✭ 44 (-87.64%)
Mutual labels:  ember, ember-addon
ember-ref-bucket
This is list of handy ember primitives, created to simplify class-based dom workflow
Stars: ✭ 31 (-91.29%)
Mutual labels:  ember, ember-addon
ember-autoresize-modifier
Autoresize Element Modifier for Ember.js
Stars: ✭ 15 (-95.79%)
Mutual labels:  ember, ember-addon
ember-event-helpers
Complimentary event template helpers to the {{on}} modifier
Stars: ✭ 33 (-90.73%)
Mutual labels:  ember, ember-addon
ember-cli-yadda
Write cucumber specs for ember-cli applications
Stars: ✭ 41 (-88.48%)
Mutual labels:  ember, ember-addon
ember-custom-actions
Custom API actions for Ember applications
Stars: ✭ 73 (-79.49%)
Mutual labels:  ember, ember-addon
ember-changeset-conditional-validations
Conditional validations for ember-changeset-validations
Stars: ✭ 26 (-92.7%)
Mutual labels:  ember, ember-addon

Ember Simple Auth Token

github-actions-image ember-observer-image npm-image

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 capability, and an authorizer mixin. You can find more about why JSON Web Tokens are so awesome in this article.

Because user's credentials and tokens are exchanged between the Ember.js app and the server, you must use HTTPS for this connection!

Demo

A demo is available here.

Installation

Ember Simple Auth Token can be installed with Ember CLI by running:

ember install ember-simple-auth-token

If using FastBoot, ember-fetch must be installed as a direct dependency and node-fetch must be added to your fastbootDependencies. If using FastBoot and the JWT authenticator, node-fetch and buffer must be added to you fastbootDependencies.

ember-simple-auth-token will automatically install a compatible version of ember-simple-auth. If you want to manually install ember-simple-auth, you must ensure to install a version that is supported by ember-simple-auth-token.

Setup

Authenticator

In order to use the token authenticator or the JSON Web Token authenticator, the application should have a route for login. In most cases, the login route will display a form with a username and password field. On form submit, the authenticate action will be called on the session:

// app/router.js
Router.map(function() {
  this.route('login');
});
{{! app/templates/login.hbs }}
<form {{action 'authenticate' on='submit'}}>
  <label for="username">Login</label>
  {{input id='username' placeholder='Enter Login' value=username}}
  <label for="password">Password</label>
  {{input id='password' placeholder='Enter Password' type='password' value=password}}
  <button type="submit">Login</button>
</form>
// app/controllers/login.js
import Controller from '@ember/controller';
import { inject } from '@ember/service';

export default Controller.extend({
  session: inject('session'),

  actions: {
    authenticate: function() {
      const credentials = this.getProperties('username', 'password');
      const authenticator = 'authenticator:token'; // or 'authenticator:jwt'

      this.session.authenticate(authenticator, credentials);
    }
  }
});

JSON Web Token Authenticator

The JSON Web Token authenticator will decode the token and look for the expiration time. The difference in the current time and the token expiration time is calculated. The refreshLeeway is subtracted from this value to determine when the automatic token refresh request should be made.

// config/environment.js
ENV['ember-simple-auth-token'] = {
  refreshAccessTokens: true,
  refreshLeeway: 300 // refresh 5 minutes (300 seconds) before expiration
};

The refreshLeeway can be specified to send the requests before the token expires to account for clock skew. Some libraries like PyJWT, ruby-jwt, and node-jsonwebtoken also support specifying a clock tolerance when verifying the token.

Sample JSON Web Token:

const encodedToken = eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImpvaG4iLCJleHAiOjk4MzQzMjM0fQ.FKuPdB7vmkRfR2fqaWEyltlgOt57lYQ2vC_vFXtlMMJfpCMMq0BEoXEC6rLC5ygORcKHprupi06Zmx0D8nChPQ;
const decodedHeader = {
  'alg': 'HS512',
  'typ': 'JWT'
};
const decodedPayload = {
  'username': 'john',
  'exp': 98343234 // <ISO-8601> UTC seconds
};

To debug JSON Web Token issues, see jwt.

The JSON Web Token authenticator supports both separate access tokens and refresh tokens. By specifying the tokenPropertyName and the refreshTokenPropertyName to the same value, the same token will be used for both access and refresh requests. For more information about refresh tokens, see this blog.

Adapter

In order to send the token with all API requests made to the server, set the headers object in the adapter:

// app/adapters/application.js
import DS from 'ember-data';
import { inject } from '@ember/service';
import { computed } from '@ember/object';

export default DS.JSONAPIAdapter.extend({
  session: inject('session'),

  headers: computed('session.isAuthenticated', 'session.data.authenticated.token', function() {
    if (this.session.isAuthenticated) {
      return {
        Authorization: `Bearer ${this.session.data.authenticated.token}`,
      };
    } else {
      return {};
    }
  }),

  handleResponse(status) {
    if (status === 401 && this.session.isAuthenticated) {
      this.session.invalidate();
    }
    return this._super(...arguments);
  },
});

Mixins

Although no longer recommended, the token-adapter mixin or token-authorizer mixin can be used in order to send the token with all API requests made to the server. When using ember-simple-auth >= 3.0.0, use the token-adapter mixin. When using ember-simple-auth < 3.0.0, use the token-authorizer mixin. The mixin will add the header to each API request:

Authorization: Bearer <token>

Adapter Mixin

// app/adapters/application.js
import DS from 'ember-data';
import TokenAdapterMixin from 'ember-simple-auth-token/mixins/token-adapter';

export default DS.JSONAPIAdapter.extend(TokenAdapterMixin);

Authorizer Mixin

// app/adapters/application.js
import DS from 'ember-data';
import TokenAuthorizerMixin from 'ember-simple-auth-token/mixins/token-authorizer';

export default DS.JSONAPIAdapter.extend(TokenAuthorizerMixin);

Customization Options

Token Authenticator

// config/environment.js
ENV['ember-simple-auth-token'] = {
  serverTokenEndpoint: '/api/token-auth/', // Server endpoint to send authenticate request
  tokenPropertyName: 'token', // Key in server response that contains the access token
  headers: {} // Headers to add to the authenticate request
};

JSON Web Token Authenticator

In addition to all the customization options available to the token authenticator:

// config/environment.js
ENV['ember-simple-auth-token'] = {
  tokenDataPropertyName: 'tokenData', // Key in session to store token data
  refreshAccessTokens: true, // Enables access token refreshing
  tokenExpirationInvalidateSession: true, // Enables session invalidation on token expiration
  serverTokenRefreshEndpoint: '/api/token-refresh/', // Server endpoint to send refresh request
  refreshTokenPropertyName: 'refresh_token', // Key in server response that contains the refresh token
  tokenExpireName: 'exp', // Field containing token expiration
  refreshLeeway: 0, // Amount of time in seconds to send refresh request before token expiration
  tokenRefreshInvalidateSessionResponseCodes: [401, 403], // Array of response codes that cause an immediate session invalidation if received when attempting to refresh the token
  refreshAccessTokenRetryAttempts: 0, // Number of token retry attempts to make
  refreshAccessTokenRetryTimeout: 1000, // Amount of time in milliseconds to wait between token refresh retry attempts
  tokenRefreshFailInvalidateSession: false // Enables session invalidation if all token refresh retry requests fail
};

Mixins

In addition to tokenPropertyName from the authenticator:

// config/environment.js
ENV['ember-simple-auth-token'] = {
  authorizationHeaderName: 'Authorization', // Header name added to each API request
  authorizationPrefix: 'Bearer ', // Prefix added to each API request
};

Testing Configuration

For acceptance testing, token refresh must be disabled to allow the test to exit. Therefore, the following configuration should be set:

// config/environment.js
ENV['ember-simple-auth-token'] = {
  refreshAccessTokens: false,
  tokenExpirationInvalidateSession: false,
};

Upgrade Notes

  • getResponseData, getAuthenticateData, config.identificationField, and config.passwordField have been removed since version 4.0.0
  • config.timeFactor has been removed since version 2.1.0
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].