我用Angular4和Amazon Cognito创建了一个认证页面

我最近使用Amazon Cognito创建了一个认证界面的备忘录。
由于机会难得,我选择了基于Angular4来制作界面。

使用amazon-cognito-identity-js进行身份验证

我会尝试使用amazon-cognito-identity-js。安装很简单。

$ npm install amazon-cognito-identity-js --save

创建用户池并添加用户信息

创建用户池。我选择了全部默认设置。然后,添加用户。但是,如果通过AWS控制台添加用户,则需要进行邮件等批准程序,所以为了省事,我使用命令进行用户添加和批准处理。

$ aws cognito-idp sign-up --client-id <ClientId> --username <Username> --password <Password> --user-attributes Name=email,Value=<Mail Address>
$ aws cognito-idp admin-confirm-sign-up --user-pool-id <UserPoolId> --username <Username> 

有一个状态为“确认”的用户已经创建完毕。(如果不是确认状态,则尝试通过API登录会返回错误消息要求进行验证)

スクリーンショット 2017-10-18 19.25.38.png

制作画面的参考页面

根据此页面的参考,我创建了一个类似认证画面的东西。

尽管由于版本差异,某些包装的内容可能有些许变化,但没有什么特别的问题,我们已经成功地进行了创建。

制作类似的屏幕

我会用Angular 4轻松地做出来。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { CognitoService } from './cognito.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CognitoService]
})
export class AppComponent {
  userName = '';
  password = '';

  constructor(
    private cognitoService: CognitoService,
    private http: Http
  ) { }

  signIn() {
    this.cognitoService.signIn(this.userName, this.password);
  }
}

<!--The content below is only a placeholder and can be replaced.-->
<div>
  <h1>
    Amazon Cognito Test login
  </h1>
</div>
<div>
  <div id="loginId">
    <div>
      <label>Login ID: </label>
    </div>
    <div>
      <input type="text" [(ngModel)]="userName" />
    </div>
  </div>
  <div id="loginPass">
    <div>
      <label>Password: </label>
    </div>
    <div>
      <input type="password" [(ngModel)]="password" />
    </div>
  </div>

  <div id="signIn">
    <button (click)="signIn()">Sign In</button>
  </div>
</div>

Cognito的服务仅实现了最基本的登录功能。

import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk';
import { CognitoUserPool, CognitoUserAttribute, CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js';
import { environment } from '../environments/environment';

@Injectable()
export class CognitoService {
    userPool = null;
    constructor() {
        AWS.config.region = environment.region;
        const data = { UserPoolId: environment.userPoolId, ClientId: environment.clientId };
        this.userPool = new CognitoUserPool(data);
    }

    signIn(userName, password) {
        const userData = {
            Username: userName,
            Pool: this.userPool
        };

        const cognitoUser = new CognitoUser(userData);
        const authenticationData = {
            Username: userName,
            Password: password
        };

        const authenticationDetails = new AuthenticationDetails(authenticationData);
        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: function (result) {
                alert('Sign in succeded');
            },
            onFailure: function (err) {
                alert(err);
            }
        });

        return;
    }
}

只需要写下使用这些的环境变量就可以了。

export const environment = {
  production: false,
  region: 'xxxxxxxxx',
  userPoolId: 'xxxxxxxxxxxxxxxxxxxxx',
  clientId: 'xxxxxxxxxxxxxxxxxxx'

};

结果在这里。

我试着访问一下

我尝试使用注册的用户进行访问。成功地访问了。

スクリーンショット 2017-10-18 19.31.46.png

如果输入错误的账户信息,那么当然无法访问。

スクリーンショット 2017-10-18 19.31.53.png

总结

虽然做得很马虎,但我已经使用Angular4基于Cognito创建了一个界面。如果能实现路由等功能,似乎可以创建一个相当不错的SPA应用程序。我还需要更加深入地学习Angular4。

bannerAds