asp.net core 騰訊驗(yàn)證碼的接入示例代碼
Intro
之前使用的驗(yàn)證碼服務(wù)是用的極驗(yàn)驗(yàn)證,而且是比較舊的,好久之前接入的,而且驗(yàn)證碼服務(wù)依賴 Session,有點(diǎn)不太靈活,后來發(fā)現(xiàn)騰訊也有驗(yàn)證碼服務(wù),而且支持小程序,并且是唯一支持小程序的驗(yàn)證碼。。(壟斷么。。)
而且相比之下,騰訊驗(yàn)證碼不需要依賴 Session,集成起來也比較方便,于是就用了騰訊驗(yàn)證碼,詳細(xì)參考:https://007.qq.com/product.html?ADTAG=index.block
驗(yàn)證流程
服務(wù)器端接入
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 { /// <summary> /// 客戶端AppId /// </summary> [Required] public string AppId { get; set; } /// <summary> /// App Secret Key /// </summary> [Required] public string AppSecret { get; set; } } public class TencentCaptchaRequest { /// <summary> /// 驗(yàn)證碼客戶端驗(yàn)證回調(diào)的票據(jù) /// </summary> public string Ticket { get; set; } /// <summary> /// 驗(yàn)證碼客戶端驗(yàn)證回調(diào)的隨機(jī)串 /// </summary> public string Nonce { get; set; } /// <summary> /// 提交驗(yàn)證的用戶的IP地址(eg: 10.127.10.2) /// </summary> public string UserIP { get; set; } } public class TencentCaptchaHelper { private class TencentCaptchaResponse { /// <summary> /// 1:驗(yàn)證成功,0:驗(yàn)證失敗,100:AppSecretKey參數(shù)校驗(yàn)錯誤 /// </summary> [JsonProperty("response")] public int Code { get; set; } /// <summary> /// 惡意等級 [0, 100] /// </summary> [JsonProperty("evil_level")] public string EvilLevel { get; set; } /// <summary> /// 錯誤信息 /// </summary> [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 readonly HttpClient _httpClient; public TencentCaptchaHelper( IOptions<TencentCaptchaOptions> option, ILogger<TencentCaptchaHelper> logger, HttpClient httpClient) { _captchaOptions = option.Value; _logger = logger; _httpClient = httpClient; } public async Task<bool> IsValidRequestAsync(TencentCaptchaRequest request) { // 參考文檔:https://007.qq.com/captcha/#/gettingStart var response = await _httpClient.GetAsync( $"{TencentCaptchaVerifyUrl}?aid={_captchaOptions.AppId}&AppSecretKey={_captchaOptions.AppSecret}&Ticket={request.Ticket}&Randstr={request.Nonce}&UserIP={request.UserIP}"); var responseText = await response.Content.ReadAsStringAsync(); if (responseText.IsNotNullOrEmpty()) { _logger.Debug($"Tencent captcha verify response:{responseText}"); var result = responseText.JsonToType<TencentCaptchaResponse>(); if (result.Code == 1) { return true; } } return false; } } }
Startup 配置:
services.AddHttpClient<TencentCaptchaHelper>(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/36841
下面的代碼是 angular spa 在前端接入的核心代碼
private loadCaptcha(): void { var tCaptcha = document.getElementById("tCaptcha"); if (tCaptcha) { this.InitCaptcha(); return; } let script = <any>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('TencentCaptcha1'); if (!captchaDom) { return; } this.tencentRecaptcha = new TencentCaptcha( captchaDom, appId, (res) => { this.captchaValid = false; console.log(res); // res(用戶主動關(guān)閉驗(yàn)證碼)= {ret: 2, ticket: null} // res(驗(yàn)證成功) = {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 = <HTMLElement>document.getElementById("btnSubmit"); button.click(); } } ); console.log(`captcha inited`); this.tencentRecaptcha.show(); }
使用效果:
老版網(wǎng)站接入效果:
Reference
https://github.com/WeihanLi/ActivityReservation
https://reservation.weihanli.xyz/Home/Reservate
https://reservation-client.weihanli.xyz/reservation/new
https://cloud.tencent.com/document/product/1110/36841
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
relaxlife.net發(fā)布一個自己開發(fā)的中文分詞程序
relaxlife.net發(fā)布一個自己開發(fā)的中文分詞程序...2007-03-03asp.net上傳圖片并作處理水印與縮略圖的實(shí)例代碼
asp.net 上傳圖片并作處理(生成縮略圖 、在圖片上增加文字水印、在圖片上生成圖片水?。┑膶?shí)例代碼,經(jīng)過測試!2013-06-06Asp.Net+XML操作基類(修改,刪除,新增,創(chuàng)建)
更新內(nèi)容: 1,根據(jù)父節(jié)點(diǎn)屬性讀取字節(jié)點(diǎn)值 2,根據(jù)節(jié)點(diǎn)屬性讀取子節(jié)點(diǎn)值(較省資源模式)2008-07-07ASP.Net Post方式獲取數(shù)據(jù)流的一種簡單寫法
這篇文章主要介紹了ASP.Net Post方式獲取數(shù)據(jù)流的一種簡單寫法,本文直接給出代碼實(shí)例,需要的朋友可以參考下2015-05-05KindEditor圖片上傳的Asp.net代碼實(shí)例
KindEditor是一個不錯的網(wǎng)頁在線編輯器,可是它只提供了asp,php,jsp上傳的類,沒有提供Asp.net上傳的類,廢話不多說,下面是ASP.NET的代碼2013-11-11ASP.NET Core中使用令牌桶限流的實(shí)現(xiàn)
這篇文章主要介紹了ASP.NET Core中使用令牌桶限流的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04ASP.NET Core 配置和使用環(huán)境變量的實(shí)現(xiàn)
這篇文章主要介紹了ASP.NET Core 配置和使用環(huán)境變量的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08在?.NET?平臺使用?ReflectionDynamicObject?優(yōu)化反射調(diào)用的代碼詳解
這篇文章主要介紹了在?.NET?平臺使用?ReflectionDynamicObject?優(yōu)化反射調(diào)用代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03