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

ember-cognito

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

ember-cognito

An authenticator and library for using ember-simple-auth and AWS Amplify/Cognito

Maintainer Needed!

Ember Cognito is an Ember Addon that integratesember-simple-authwith AWS Amplify andAWS Cognito User Pools.

ember-simple-auth is a lightweight library for implementing authentication/authorizationin Ember.js. AWS Amplify is a client framework, developed by Amazon, which uses AmazonCognito as a managed authentication system for mobile and web apps on Amazon Web Services.

ember-cognito implements an ember-simple-auth custom authenticator that can be usedin an AWS Amplify application, or any Ember application, to authenticate witha Cognito User Pool.

Installation

Install as a standard Ember Addon:

  • ember install ember-cognito

Configure

In your config/environment.js file:

var ENV = {
  // ..
  cognito: {
    poolId: '<your Cognito User Pool ID>',
    clientId: '<your Cognito App Client ID>',
  }
};

Note that the Cognito JavaScript SDK requires that your App be created without aClient Secret.

Optional Configuration

You can specify these optional configuration options to the above configuration hash:

  • autoRefreshSession. Cognito access tokens are only valid for an hour. By default,this addon will refresh expired sessions on application startup.Setting autoRefreshSession to true will enable a timer that will automaticallyrefresh the Cognito session when it expires.

  • authenticationFlowType. The authentication flow type that should be used.Default value: USER_SRP_AUTHAllowed values: USER_SRP_AUTH | USER_PASSWORD_AUTHMore details - Auth Flow

Usage

Cognito Authenticator

The Cognito Authenticator authenticates an ember-simple-auth session withAmplify/Cognito:

import Component from '@ember/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';

export default class LoginComponent extends Component {
  @service session;
  
  @action
  async authenticate() {
    const { username, password } = this;
    const credentials = { username, password };
    try {
      await this.session.authenticate('authenticator:cognito', credentials);
    } catch (error) {
      this.set('errorMessage', error.message || error);
    }
  }
}

Integrating with an Ember Data Adapter

The Cognito Authenticator will put the Cognito ID token in the access_token property in the session'sauthenticated data. This means integrating with ember-simple-auth'sEmber Data Adapter Mixinrequires no special configuration.

Cognito Service

The addon provides a cognito service that provides some helpers to access theAmplify auth object. The service provides access to the following Amplify/auth methods:

  • signUp(username, password, attributes, validationData)
  • confirmSignUp(username, code, options)
  • resendSignUp(username)
  • forgotPassword(username)
  • forgotPasswordSubmit(username, code, newPassword)

It also provides a helper to quickly access the current user's Cognito ID token:

  • getIdToken()

Cognito User

The Cognito service allows you to access the currently authenticated CognitoUserobject, along with the following helper methods:

  • changePassword(oldPassword, newPassword)
  • deleteAttributes(attributeList)
  • deleteUser()
  • getSession()
  • getUserAttributes()
  • getUserAttributesHash()
  • signOut()
  • updateAttributes()
  • verifyAttribute()
  • getGroups()

If you use a current-user service using theember-simple-auth guide,you can use the Cognito User to fetch user attributes:

import Service from '@ember/service';
import { inject as service } from '@ember/service';
import { readOnly } from '@ember/object/computed';

export default class CurrentUserService extends Service {
  @service session;
  @service cognito;
  @readOnly('cognito.user') cognitoUser;
  @readOnly('cognitoUser.username') username;
  
  async load() {
    if (this.session.isAuthenticated) {
      const userAttributes = await this.cognitoUser.getUserAttributes();
      userAttributes.forEach((attr) => {
        this.set(attr.getName(), attr.getValue());
      });
    }
  }
}

You can see examples of usages of these API methods in thefull-featured dummy app.

Advanced Configuration

If you don't want to specify the Pool ID and Client ID in the Ember environment, youcan override the CognitoService in your own app and provide the configuration there.

// app/services/cognito.js
import BaseCognitoService from 'ember-cognito/services/cognito';

export default class CognitoService extends BaseCognitoService {
  poolId = '<my pool ID>';
  clientId = '<my client ID>;
}

In this case, you can have the properties be computed or retrieved through some dynamicmechanism.

Testing

ember-cognito provides some helpers and utilities that make it easier to work withCognito in tests.

mockCognitoUser

In acceptance tests, you can use ember-simple-auth's authenticateSession to create auser, but you may also need to mock user attributes on the Cognito service. You can dothis using mockCognitoUser:

import { authenticateSession } from 'ember-simple-auth/test-support';
import { mockCognitoUser } from 'ember-cognito/test-support';

module('Acceptance | authenticated route', function(hooks) {
  test('authenticated route', async function(assert) {
    await authenticateSession();
    await mockCognitoUser({
      username: 'testuser'
      // userAttributes...
    });
    const authenticator = this.owner.lookup('authenticator:cognito');
    // Rest of the test
  });
});

mockAuth

In some cases, you may want to mock the Amplify auth object to test authenticationscenarios. You can use the mockAuth helper to add your own mock class tostub certain Amplify functions in tests:

import { mockAuth, MockAuth } from 'ember-cognito/test-support';

module('Acceptance | login', function(hooks) {
  setupApplicationTest(hooks);
  
  test('login failure', async function(assert) {
    await mockAuth(MockAuth.extend({
      signIn() {
        return reject({ message: 'Username or password incorrect.' });
      }
    }));
     
    // Attempt to login, 
    await visit('/login');
    await fillIn('#username', 'testuser');
    await fillIn('#password', 'password');
    await click('[type=submit]');
  
    assert.dom('[data-test-error]').hasText('Username or password incorrect.');
  });
});

Dummy App

The dummy appincludes many use cases for you to see this addon in action, including new user sign up,login, logout, and updating/verifying user attributes.

Support

  • Ember versions 3.4+
  • AWS Amplify 1.x
 相关资料
  • Ember检查器是一个浏览器插件,用于调试Ember应用程序。 灰烬检查员包括以下主题 - S.No. 灰烬检查员方式和描述 1 安装Inspector 您可以安装Ember检查器来调试您的应用程序。 2 Object Inspector Ember检查器允许与Ember对象进行交互。 3 The View Tree 视图树提供应用程序的当前状态。 4 检查路由,数据选项卡和库信息 您可以看到检查

  • 英文原文: http://emberjs.com/guides/getting-ember/index/ Ember构建 Ember的发布管理团队针对Ember和Ember Data维护了不同的发布方法。 频道 最新的Ember和Ember Data的 Release,Beta 和 Canary 构建可以在这里找到。每一个频道都提供了一个开发版、最小化版和生产版。更多关于不同频道的信息可以查看博客

  • ember-emojione ember-emojione is your emoji solution for Ember, based on the EmojiOne project. EmojiOne version 2 is used, which is free to use for everyone (CC BY-SA 4.0), you're only required to giv

  • Ember 3D Ember 3D is an Ember addon for using Three.js - an easy to use, lightweight, javascript 3D library. It is designed to: Prescribe a solid file structure to Three.js code using ES6 modules. Ena

  • Ember Table An addon to support large data set and a number of features around table. Ember Table canhandle over 100,000 rows without any rendering or performance issues. Ember Table 3.x supports: Emb

  • vscode-ember This is the VSCode extension to use the Ember Language Server. Features All features currently only work in Ember-CLI apps that use classic structure and are a rough first draft with a lo