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

如何在Angular 8应用中添加图片字母验证码?

传统字符图片验证码支持状态说明

这类需要用户输入图片中字符的传统验证码目前完全可用,不存在被废弃或者不支持的情况。相比交互类验证码,它不需要依赖第三方服务、适配性更广,特别适合无外网访问权限的内部系统、低部署成本的小型项目使用。

Angular 8 实现方案

你可以根据安全要求选择前端生成或者后端生成两种实现方式:

  • 低安全要求场景可以直接用前端生成方案,推荐使用兼容Angular 8的ngx-captcha@6.0.0版本,安装命令:
    npm install ngx-captcha@6.0.0
    
    首先在对应模块的imports数组中引入CaptchaModule,之后即可在组件中直接调用:
    <!-- 验证码图片区域 -->
    <ngx-captcha 
      type="text" 
      [length]="4" 
      [width]="130" 
      [height]="45" 
      (captchaGenerated)="saveCurrentCaptcha($event)"
      #captchaInstance
    ></ngx-captcha>
    <button type="button" (click)="captchaInstance.reload()">刷新验证码</button>
    
    <!-- 用户输入框 -->
    <input type="text" [(ngModel)]="inputCaptcha" placeholder="请输入图中字符">
    <button type="button" (click)="checkCaptcha()">提交验证</button>
    
    对应的组件逻辑示例:
    import { Component, ViewChild } from '@angular/core';
    import { CaptchaComponent } from 'ngx-captcha';
    
    @Component({
      selector: 'app-captcha-demo',
      templateUrl: './captcha-demo.component.html'
    })
    export class CaptchaDemoComponent {
      @ViewChild('captchaInstance') captchaInstance: CaptchaComponent;
      inputCaptcha = '';
      currentValidCaptcha = '';
    
      // 保存生成的正确验证码
      saveCurrentCaptcha(captcha: string) {
        // 不需要区分大小写的话统一转小写/大写
        this.currentValidCaptcha = captcha.toLowerCase();
      }
    
      // 验证逻辑
      checkCaptcha() {
        if (this.inputCaptcha.toLowerCase().trim() === this.currentValidCaptcha) {
          // 验证通过后的业务逻辑
          console.log('验证通过');
        } else {
          alert('验证码输入错误');
          this.inputCaptcha = '';
          // 自动刷新验证码
          this.captchaInstance.reload();
        }
      }
    }
    
  • 高安全要求场景推荐使用后端生成方案:后端生成带干扰线/噪点的验证码图片,同时返回唯一校验token存储在session中,前端展示图片、收集用户输入后和token一起传给后端校验即可,这种方式验证码生成逻辑完全在服务端,不会被前端爬虫破解,安全性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:09:00