当前位置: 首页 > 软件库 > 程序开发 > >

ember-simple-auth-token

授权协议 MIT License
开发语言 JavaScript
所属分类 程序开发
软件类型 开源软件
地区 不详
投 递 者 阳兴朝
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

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

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
  • 做了这么长时间的web开发,从JAVA EE中的jsf,spring,hibernate框架,到spring web MVC,到用php框架thinkPHP,到现在的nodejs,我自己的看法是越来越喜欢干净整洁的web层,之前用jsf开发做view层的时候,用的primefaces做的界面显示,虽然primefaces的确提供了很大的便利,可以让开发人员专注于业务逻辑开发,这样其实就省去了前端开

  • 使用json web token[转] 由来 做了这么长时间的web开发,从JAVA EE中的jsf,spring,hibernate框架,到spring web MVC,到用php框架thinkPHP,到现在的nodejs,我自己的看法是越来越喜欢干净整洁的web层,之前用jsf开发做view层的时候,用的primefaces做的界面显示,虽然primefaces的确提供了很大的便利,可以让开发

  • 来龙去脉 诸如Ember,Angular,Backbone之类的前端框架类库正随着更加精细的Web应用而日益壮大。正因如此,服务器端的组建也正正在从传统的任务中解脱,转而变的更像API。API使得传统的前端和后端的概念解耦。开发者可以脱离前端,独立的开发后端,在测试上获得更大的便利。这种途径也使得一个移动应用和网页应用可以使用相同的后端。 当使用一个API时,其中一个挑战就是认证(authenti

 相关资料
  • Ember Simple Auth API docs Ember Simple Auth supports all Ember.js versions starting with 3.0.Node 12 is required Ember Simple Auth Ember Simple Auth is a lightweight library for implementing authenti

  • @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

  • 这快把我逼疯了...一切都应该是正确的,我总是得到未经授权的错误在我的API路由! Api.php路由: }); 注册控制器: 数据库: 请求: 接受应用/json设置为: 我也尝试使用jQuery来请求一个查询参数api_key但它也不起作用!! 我搜索了很多,但无法解决这个问题。我有另一个新的应用程序与Laravel和auth,它的作品完美,但这个项目是旧的,我最近更新到Laravel 7,我

  • simple 是一个支持中文和拼音的 sqlite3 fts5 拓展。它完整提供了 微信移动端的全文检索多音字问题解决方案 一文中的方案四,非常简单和高效地支持中文及拼音的搜索。 实现相关介绍:https://www.wangfenjin.com/posts/simple-tokenizer/ 在此基础上,还支持通过 cppjieba 实现更精准的词组匹配,介绍文章见 https://www.wa

  • AUTH password 通过设置配置文件中 requirepass 项的值(使用命令 CONFIG SET requirepass password ),可以使用密码来保护 Redis 服务器。 如果开启了密码保护的话,在每次连接 Redis 服务器之后,就要使用 AUTH 命令解锁,解锁之后才能使用其他 Redis 命令。 如果 AUTH 命令给定的密码 password 和配置文件中的密码

  • 用户认证 // 判断当前用户是否已认证(是否已登录) Auth::check(); // 获取当前的认证用户 Auth::user(); // 获取当前的认证用户的 ID(未登录情况下会报错) Auth::id(); // 通过给定的信息来尝试对用户进行认证(成功后会自动启动会话) Auth::attempt(['email' => $email, 'password' => $password]