登陆

asp.net core 腾讯验证码的接入

admin 2020-02-14 131人围观 ,发现0个评论

asp.net core 腾讯验证码的接入

Intro#

之前运用的验证码服务是用的极验验证,并且是比较旧的,良久之前接入的,并且验证码服务依靠 Session,有点不太灵敏,后来发现腾讯也有验证码服务,并且支撑小程序,并且是仅有支撑小程序的验证码。。(独占么。。)

并且相比之下,腾讯验证码不需要依靠 Session,集成起来也比较便利,于是就用了腾讯验证码,详细参阅:https://007.qq.com/product.html?ADTAG=index.block

验证流程#

服务器端接入#

using System.ComponentModel.DataAnnotations;

using System.Net.Http;

using System.Threading.Tasks;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using Newtonsoft.Json;

using WeihanLi.Extensions;

namespace ActivityReservation.Common {

public class TencentCaptchaOptions {

///

/// 客户端AppId

/// [Required] public string AppId { get; set; }

///

/// App Secret Key

/// [Required] public string AppSecret { get; set; } }

public class TencentCaptchaRequest {

///

/// 验证码客户端验证回调的收据 /// public string Ticket { get; set; } ///

/// 验证码客户端验证回调的随机串 /// public string Nonce { get; set; } /// /// 提交验证的用户的IP地址(eg: 10.127.10.2) /// public string UserIP { get; set; } } public class TencentCaptchaHelper { private class TencentCaptchaResponse { /// /// 1:验证成功,0:验证失利,100:AppSecretKey参数校验过错 /// [JsonProperty("response")] public int Code { get; set; } /// /// 歹意等级 [0, 100] /// [JsonProperty("evil_level")] public string EvilLevel { get; set; } /// /// 过错信息 /// [JsonProperty("err_msg")] public string ErrorMsg { get; set; } } private const string TencentCaptchaVerifyUrl = "https://ssl.captcha.qq.com/ticket/verify"; private readonly TencentCaptchaOptions _captchaOptions; private readonly ILogger _logger; private read就要鲁only HttpClient _httpClient; public TencentCaptchaHelper( IOptions option, ILogger logger, HttpClient httpClient) { _captchaOptions = option.Value; _logger = logger; _httpClient = httpClient; } public async Task IsValidRequestAsync(TencentCaptchaRequest requeasp.net core 腾讯验证码的接入st) { // 参阅文档:https://007.qq.com/captcha/#/gettingStart var response = await _httpClient.GetAsync( $"{TencentCaptchaVerifyUrl}?aiasp.net core 腾讯验证码的接入d={_captchaOptions.AppId}&AppSecretKey={_captchaOptions.AppSecret}&Ticket={request.Ticket}&Randstr={request.Nonce}&UserIP={request.Useasp.net core 腾讯验证码的接入rIP}"); var responseText = await response.Content.ReadAsStringAsync(); if (responseText.IsNotNullOrEmpty()) { _logger.Debug($"Tencent captcha verify response:{responseText}"); var result = responseText.JsonToType(); if (result.Code == 1) { return true; } } return false; } } }

Startup 装备:

Copy

services.AddHttpClient(client => client.Timeout = TimeSpan.FromSeconds(3)) .ConfigurePrimaryHttpMessageHandler(() => new NoProxyHttpClientHandler()); services.AddTencentCaptchaHelper(options => { options.AppId = Configuration["Tencent:Captcha:AppId"]; options.AppSecret = Configuration["Tencent:Captcha:AppSecret"]; });

前端接入#

前端接入这儿不作多介绍了,接入方法多种多样,详细能够参阅官方文档:https://cloud.tencent.com/document/product/1110/36841asp.net core 腾讯验证码的接入

下面的代码是 angular spa 在前端接入的中心代码

Copy

private loadCaptcha(): void { var tCaptcha = document.getElementById("tCaptcha"); if (tCaptcha) { this.InitCaptcha(); return; } let script = document.createElement('script'); script.id = "tCaptcha"; script.type = 'text/javascript'; script.src = "https://ssl.captcha.qq.com/TCaptcha.js" if (script.readyState) { //IE script.onreadystatechange = () => { if (script.readyState === "loaded" || script.readyState === "complete") { this.InitCaptcha(); } }; } else { //Others script.onload = () => { this.InitCaptcha(); }; } document.getElementsByTagName('body')[0].appendChild(script); } private InitCaptcha(): void { let captchaDom = document.getElementById('TencentCaptcasp.net core 腾讯验证码的接入ha1'); if (!captchaDom) { return; } this.tencentRecaptcha = new Tencasp.net core 腾讯验证码的接入entCaptcha( captchaDom, appId, (res) => { this.captchaValid = false; console.log(res); // res(用户自动封闭验证码)= {ret: 2, ticket: null} // res(验证成功) = {ret: 0, ticket: "String", randstr: "String"} if (res.ret === 0) { this.captchaInfo.nonce = res.randstr; this.captchaInfo.ticket = res.ticket; this.captchaValid = true; this.tencentRecaptcha.destroy(); let button = document.getElementById("btnSubmit"); button.click(); } } ); console.log(`captcha inited`); this.tencentRecaptcha.show(); }


作者: WeihanLi

出处:https://www.cnblogs.com/weihanli/p/11698176.html

版权:本站运用「CC BY 4.0」创造同享协议,转载请在文章显着方位注明作者及出处。

原文地址:https://www.cnblogs.com/weihanli/p/11698176.html

请关注微信公众号
微信二维码
不容错过
Powered By Z-BlogPHP