You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 16应用中实现基于Cognito用户名密码的登录功能

Angular 16 集成 AWS Cognito 登录实现方案

1. 安装适配依赖

使用AWS官方维护的Amplify库,完全兼容Angular 16,执行以下命令安装:

npm install aws-amplify@^6 @aws-amplify/auth@^6 @aws-amplify/angular@^6

2. 初始化Cognito配置

在src/main.ts中添加Amplify初始化代码,替换为你的Cognito用户池信息:

import { Amplify } from 'aws-amplify';
import { Auth } from '@aws-amplify/auth';

Amplify.configure({
  Auth: {
    region: '你的用户池区域',
    userPoolId: '你的用户池ID',
    userPoolWebClientId: '你的应用客户端ID',
    // 若用户池开启验证,可添加此项控制是否强制验证完成后登录
    mandatorySignIn: false
  }
});

3. 构建登录组件

生成组件

ng generate component auth/login

编写登录表单(login.component.html)

<div class="login-wrapper">
  <h3>用户登录</h3>
  <form (ngSubmit)="handleLogin()">
    <div class="form-group">
      <label>用户名</label>
      <input type="text" [(ngModel)]="username" name="username" required>
    </div>
    <div class="form-group">
      <label>密码</label>
      <input type="password" [(ngModel)]="password" name="password" required>
    </div>
    <button type="submit" class="login-btn">登录</button>
    <p *ngIf="errorMsg" class="error-text">{{ errorMsg }}</p>
  </form>
</div>

实现登录逻辑(login.component.ts)

import { Component } from '@angular/core';
import { Auth } from '@aws-amplify/auth';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  username: string = '';
  password: string = '';
  errorMsg: string = '';

  constructor(private router: Router) {}

  async handleLogin() {
    this.errorMsg = '';
    try {
      const user = await Auth.signIn(this.username, this.password);
      // 登录成功:跳转首页或存储用户信息
      await this.router.navigate(['/home']);
      console.log('登录成功,用户信息:', user);
    } catch (err: any) {
      this.errorMsg = err.message || '登录失败,请检查用户名/密码';
      console.error('登录错误:', err);
    }
  }
}

4. 配置表单依赖

在app.module.ts中导入FormsModule,支持表单双向绑定:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // 其他已导入模块
    FormsModule
  ]
})
export class AppModule { }

5. 常见问题排查

  • 确保Cognito应用客户端未开启「生成客户端密钥」,前端无法安全存储密钥
  • 核对用户池区域、ID、客户端ID是否完全匹配
  • 确认用户已完成邮箱/手机号验证(若用户池开启了验证规则)
  • 若出现依赖版本冲突,可删除node_modules和package-lock.json后重新安装

内容的提问来源于stack exchange,提问作者Harshit Awasthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 14:05:01