Angular统计无效登录尝试次数后显示错误提示的实现方法
Angular 登录组件累计失败次数锁定实现方案
实现逻辑按用户名维度单独统计认证失败次数,累计达3次时展示指定锁定提示,具体修改如下:
- 新增组件状态字段
在原有组件类的属性定义中,添加两个字段分别存储各用户失败次数、当前用户锁定状态:// 结构为 { 用户名: 累计失败次数 },按用户维度独立计数 private failedLoginCounts: Record<string, number> = {}; // 标记当前输入的账号是否已被撤销权限 public isUserRevoked = false; - 调整提交认证逻辑
修改原有的onSubmit方法,在认证失败时累计计数,达到阈值后触发锁定状态,同时登录成功时重置对应用户的计数:async onSubmit(): Promise<void> { this.loginInvalid = false; this.formSubmitAttempt = false; this.isUserRevoked = false; if (this.form.valid) { const username = this.form.get('username')?.value?.trim(); // 已锁定用户直接拦截,不发起认证请求 if (this.failedLoginCounts[username] >= 3) { this.isUserRevoked = true; return; } try { const password = this.form.get('password')?.value; await this.accessService.authenticate(username, password); // 登录成功后清除该用户的历史失败计数 if (this.failedLoginCounts[username]) { delete this.failedLoginCounts[username]; } } catch (err) { // 认证失败,对应用户计数+1 this.failedLoginCounts[username] = (this.failedLoginCounts[username] || 0) + 1; // 判断是否达到锁定阈值 if (this.failedLoginCounts[username] >= 3) { this.isUserRevoked = true; } else { this.loginInvalid = true; } } } else { this.formSubmitAttempt = true; } } - 修改模板错误提示与交互
调整模板中的错误提示区块,根据状态展示对应文案,同时锁定状态下禁用提交按钮:<form [formGroup]="form" (ngSubmit)="onSubmit()"> <h2>Log In</h2> <mat-error *ngIf="loginInvalid"> 用户名或密码错误 </mat-error> <mat-error *ngIf="isUserRevoked"> Failed: USERID REVOKED </mat-error> <mat-form-field class="full-width-input"> <input matInput placeholder="邮箱" formControlName="username" required> <mat-error> 请输入有效的邮箱地址 </mat-error> </mat-form-field> <mat-form-field class="full-width-input"> <input matInput type="password" placeholder="密码" formControlName="password" required> <mat-error> 请输入密码 </mat-error> </mat-form-field> <button mat-raised-button color="primary" [disabled]="isUserRevoked">登录</button> </form> - 可选优化:监听用户名输入变化
在ngOnInit生命周期中添加用户名输入框的value订阅,用户修改用户名时自动重置错误和锁定状态,避免不同用户状态混淆:async ngOnInit(): Promise<void> { this.form.get('username')?.valueChanges.subscribe(() => { this.loginInvalid = false; this.isUserRevoked = false; }); }
注意:上述前端实现仅适用于本地演示场景。生产环境下登录失败计数、账号锁定逻辑必须在服务端实现,前端存储的计数在页面刷新后会清零,也可被用户随意篡改,不具备安全防护能力。
内容的提问来源于stack exchange,提问作者Neha Modi
相关产品推荐
相关产品推荐

