Giter Site home page Giter Site logo

uysim / ember-simple-auth-token Goto Github PK

View Code? Open in Web Editor NEW

This project forked from fenichelar/ember-simple-auth-token

0.0 2.0 0.0 1.89 MB

Ember Simple Auth extension that is compatible with token-based authentication like JWT.

Home Page: https://jpadilla.github.io/ember-simple-auth-token/

License: MIT License

JavaScript 96.48% HTML 3.48% CSS 0.04%

ember-simple-auth-token's Introduction

Ember Simple Auth Token

travis-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 and the JWT authenticator, buffer must be added to your fastbootDependencies.

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.get('session').authenticate(authenticator, credentials);
    }
  }
});

JSON Web Token Authenticator

The JSON Web Token authenticator will decode the token and look for the expiration time found. 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.

Authorizer Mixin

In order to send the token with all API requests made to the server, the token authorizer mixin should be used:

// 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);

The mixin will add the header to each API request:

Authorization: Bearer <token>

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
};

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 to send refresh request before token expiration
};

Token Authenticator

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.