当前位置:首页 > 科技  > 软件

如何使用Python构建OTP验证系统?

来源: 责编: 时间:2023-09-20 21:56:00 523观看
导读译者 | 布加迪审校 | 重楼即使您的密码被盗,OTP验证系统也可以充当安全的关键要素。它让您无需记住密码,充当额外的安全层,并降低了网络钓鱼的风险。不妨学习用Python建立一个OTP验证系统,它会向您的手机号码发送一个OTP,

译者 | 布加迪1G228资讯网——每日最新资讯28at.com

审校 | 重楼1G228资讯网——每日最新资讯28at.com

即使您的密码被盗,OTP验证系统也可以充当安全的关键素。它让您无需记住密码,充当额外的安全层,并降低了网络钓鱼的风险。1G228资讯网——每日最新资讯28at.com

不妨学习用Python建立一个OTP验证系统,它会向的手机号码发送一个OTP,有效期只有两分钟,如果连续三次输错OTP,账户会被锁1G228资讯网——每日最新资讯28at.com

安装TkinterTwilioRandom模块

Tkinter允许您创建桌面应用程序。它提供了各种小组件比如按钮、标签和文本框,使开发应用程序变得更容易。1G228资讯网——每日最新资讯28at.com

Twilio模块帮助您把短信、彩信电话呼叫等通信功能与验证径直整合到应用程序。它有一个基于云的基础设施,以及令人惊叹的功能,比如号码配置、消息模板和呼叫记录。1G228资讯网——每日最新资讯28at.com

安装Twilio模块Tkinter模块,在终端执行如下命令1G228资讯网——每日最新资讯28at.com

pip install twilio tk

Random模块是内置的Python模块,用于生成伪随机数。有了该模块,您可以生成随机数、从列表中选择随机元素、打乱列表内容等。您可以用它来构建掷骰子模拟、列表打乱器或随机密码生成器。1G228资讯网——每日最新资讯28at.com

生成Twilio API并获取电话号码

要使用Twilio并向您的手机发送OTP请求,您需要身份验证凭以及Twilio电话号码。为此:1G228资讯网——每日最新资讯28at.com

1. 注册一个Twilio账户,访问Twilio控制台。1G228资讯网——每日最新资讯28at.com

2. 向下滚动并点击“获取电话号码按钮。复制已生成的电话号码。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

3. 向下滚动到“账户信息”部分。复制账户SID“身份验证令牌1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

构建应用程序的结构

事先声明一下,您可以在这个GitHub代码仓库中找到使用Python构建OTP验证系统的完整源代码。1G228资讯网——每日最新资讯28at.com

导入必要的模块并设置身份验证凭据。初始化Twilio客户软件以验证身份,并作为API调用的入口点。将到期失效时间设为两分钟。1G228资讯网——每日最新资讯28at.com

定义一个类OTPVerification,并初始化构造函数设置变量的默认值,同时初始化根窗口,并设置应用程序的标题和维度。1G228资讯网——每日最新资讯28at.com

import tkinter as tkfrom tkinter import messageboxfrom twilio.rest import Clientimport randomimport threadingimport timeaccount_sid = "YOUR_ACCOUNT_SID"auth_token = "YOUR_AUTH_TOKEN"client = Client(account_sid, auth_token)expiration_time = 120class OTPVerification: def __init__(self, master): self.master = master self.master.title('OTP Verification') self.master.geometry("600x275") self.otp = None self.timer_thread = None self.resend_timer = None self.wrong_attempts = 0 self.locked = False self.stop_timer = False

定义三个标签来请求手机号码和OTP,并在程序发送OTP后显示计时器。设置父元素它应该显示的文本以及有的字体样式。同样,创建两个输入组件以获取用户输入。设置父元素、宽度和字体样式。1G228资讯网——每日最新资讯28at.com

创建三个按钮来发送OTP、重新发送OTP和验证OTP。设置父元素、它应该显示的文本、点击时执行的命令及其字体样式。使用pack方法组织这些元素。1G228资讯网——每日最新资讯28at.com

self.label1 = tk.Label(self.master,  text='Enter your mobile number:', fnotallow=('Arial', 14)) self.label1.pack() self.mobile_number_entry = tk.Entry(self.master,  width=20, fnotallow=('Arial', 14)) self.mobile_number_entry.pack() self.send_otp_button = tk.Button(self.master,  text='Send OTP',  command=self.send_otp, fnotallow=('Arial', 14)) self.send_otp_button.pack() self.timer_label = tk.Label(self.master,  text='',  fnotallow=('Arial', 12, 'bold')) self.timer_label.pack() self.resend_otp_button = tk.Button(self.master,  text='Resend OTP',  state=tk.DISABLED,  command=self.resend_otp, fnotallow=('Arial', 14)) self.resend_otp_button.pack() self.label2 = tk.Label(self.master,  text='Enter OTP sent to your mobile:', fnotallow=('Arial', 14)) self.label2.pack() self.otp_entry = tk.Entry(self.master,  width=20, fnotallow=('Arial', 14)) self.otp_entry.pack() self.verify_otp_button = tk.Button(self.master,  text='Verify OTP',  command=self.verify_otp, fnotallow=('Arial', 14)) self.verify_otp_button.pack()

构建应用程序的功能

定义一个方法start_timer(),它在单独的线程中运行timer_countdown1G228资讯网——每日最新资讯28at.com

def start_timer(self): self.timer_thread = threading.Thread(target=self.timer_countdown) self.timer_thread.start()

定义一个方法timer_countdown()。记录开始时间并运行一个无限循环,该循环获取当前时间并计算已流逝的时间和剩余时间。如果stop_timer为true,终止循环。如果剩余时间小于或等于0,显示错误消息框,表明OTP已过期。1G228资讯网——每日最新资讯28at.com

激活重新发送OTP按钮,将OTP设置为none,并终止。否则,计算剩余的分钟和秒,将其显示在计时器标签上,并休眠一秒钟。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

def timer_countdown(self): start_time = time.time() while True: current_time = time.time() elapsed_time = current_time - start_time remaining_time = expiration_time - elapsed_time if self.stop_timer: break if remaining_time <= 0: messagebox.showerror('Error', 'OTP has expired.') self.resend_otp_button.config(state=tk.NORMAL) self.otp = None break minutes = int(remaining_time // 60) seconds = int(remaining_time % 60) timer_label = f'Time Remaining: {minutes:02d}:{seconds:02d}' self.timer_label.config(text=timer_label) time.sleep(1)

定义一个方法send_otp()。如果locked为true,显示相应的消息。否则提取并验证电话号码,生成一个随机的OTP。提供之前获取的手机号码,使用客户软件将OTP发送到您的电话号码。显示消息框,启动计时器,禁用按钮,并完全清除输入内容。1G228资讯网——每日最新资讯28at.com

def send_otp(self):   if self.locked: messagebox.showinfo('Account Locked', 'Your account is locked. Try  again later.') return mobile_number = self.mobile_number_entry.get() if not mobile_number: messagebox.showerror('Error', 'Please enter your mobile number.') return self.otp = random.randint(1000, 9999) message = client.messages.create( body=f'Your OTP is {self.otp}.', from_='TWILIO_MOBILE_NUMBER', to=mobile_number ) messagebox.showinfo('OTP Sent', f'OTP has been sent to {mobile_number}.') self.start_timer() self.send_otp_button.config(state=tk.DISABLED)  self.resend_otp_button.config(state=tk.DISABLED)  self.otp_entry.delete(0, tk.END)
def send_otp(self):   if self.locked: messagebox.showinfo('Account Locked', 'Your account is locked. Try  again later.') return mobile_number = self.mobile_number_entry.get() if not mobile_number: messagebox.showerror('Error', 'Please enter your mobile number.') return self.otp = random.randint(1000, 9999) message = client.messages.create( body=f'Your OTP is {self.otp}.', from_='TWILIO_MOBILE_NUMBER', to=mobile_number ) messagebox.showinfo('OTP Sent', f'OTP has been sent to {mobile_number}.') self.start_timer() self.send_otp_button.config(state=tk.DISABLED)  self.resend_otp_button.config(state=tk.DISABLED)  self.otp_entry.delete(0, tk.END)

定义一个方法resend_otp()。如果锁住,显示相应的消息。否则获取并验证电话号码,重新生成随机的OTP,重新发送OTP,显示消息框,启动计时器,并禁用重新发送OTP按钮。1G228资讯网——每日最新资讯28at.com

def resend_otp(self): if self.locked: messagebox.showinfo('Account Locked', 'Your account is locked. Try  again later.') return mobile_number = self.mobile_number_entry.get() if not mobile_number: messagebox.showerror('Error', 'Please enter your mobile number.') return self.otp = random.randint(1000, 9999) message = client.messages.create( body=f'Your OTP is {self.otp}.', from_='TWILIO_MOBILE_NUMBER', to=mobile_number ) messagebox.showinfo('OTP Sent', f'New OTP has been sent to {mobile_number}.') self.start_timer() self.resend_otp_button.config(state=tk.DISABLED)

定义一个方法verify_otp()。获取OTP,并检查用户是否没有输入任何内容。如果存储的OTP为None,要求用户先生成OTP。如果用户输入的OTP与存储的OTP匹配,显示OTP验证成功,停止时器并退出程序。否则检查错误的输入尝试。如果输错次数超过3次,锁住户。1G228资讯网——每日最新资讯28at.com

def verify_otp(self): user_otp = self.otp_entry.get() if not user_otp: messagebox.showerror('Error', 'Please enter OTP.') return if self.otp is None: messagebox.showerror('Error', 'Please generate OTP first.') return if int(user_otp) == self.otp: messagebox.showinfo('Success', 'OTP verified successfully.') self.stop_timer = True  exit() else: self.wrong_attempts += 1 if self.wrong_attempts == 3: self.lock_account() else: messagebox.showerror('Error', 'OTP does not match.')

定义一个方法lock_account()。设置锁住状态为true,显示标签为“账户已锁住”。禁用所有标签、条目和按钮。停止现有的计时器,启动新的计时器10分钟1G228资讯网——每日最新资讯28at.com

def lock_account(self): self.locked = True self.label1.config(text='Account Locked') self.mobile_number_entry.config(state=tk.DISABLED) self.send_otp_button.config(state=tk.DISABLED) self.timer_label.config(text='') self.resend_otp_button.config(state=tk.DISABLED) self.label2.config(text='') self.otp_entry.config(state=tk.DISABLED) self.verify_otp_button.config(state=tk.DISABLED) self.stop_timer = True  countdown_time = 10 * 60  self.start_countdown(countdown_time)

定义一个方法start_countdown()。如果剩余时间小于等于0,重置账户。否则显示程序已锁住账户,并在剩余时间内使用回调再试一次。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

def start_countdown(self, remaining_time): if remaining_time <= 0: self.reset_account() return minutes = int(remaining_time // 60) seconds = int(remaining_time % 60) timer_label = f'Account Locked. Try again in: {minutes:02d}:{seconds:02d}' self.timer_label.config(text=timer_label) self.master.after(1000, self.start_countdown, remaining_time - 1)

定义一个函数reset_account()。像前面一样重置所有小组件和变量的状态。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

def reset_account(self): self.locked = False self.wrong_attempts = 0 self.label1.config(text='Enter your mobile number:') self.mobile_number_entry.config(state=tk.NORMAL) self.send_otp_button.config(state=tk.NORMAL) self.timer_label.config(text='') self.resend_otp_button.config(state=tk.DISABLED) self.label2.config(text='Enter OTP sent to your mobile:') self.otp_entry.config(state=tk.NORMAL) self.verify_otp_button.config(state=tk.NORMAL) self.stop_timer = False

创建根窗口类的实例,并运行Tkinter应用程序。1G228资讯网——每日最新资讯28at.com

if __name__ == '__main__': root = tk.Tk() otp_verification = OTPVerification(root) root.mainloop()

使用OTP验证的输出示例

在运行OTP验证程序时,您会看到一个窗口,要求输入手机号码。输入手机号码以及所在国家代,然后点击发送OTP按钮。会收到一条消息,表明程序已成功发送OTP,按钮会停用两分钟。检查手机是否收到了OTP,并在过期前输入它。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

在计时器过期前输入正确的OTP,您将到一条消息,表明程序已成功验证了OTP,退出程序。如果您没有及时输入,收到消息框,表明OTP已过期。可以点击重新发送OTP按钮生成新的OTP并发送到您的手机。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

如果您输错OTP,程序将显示一个消息框,表明“OTP不匹配1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

如果OTP输错三次,所有字段将被禁用,账户将被锁住十分钟。1G228资讯网——每日最新资讯28at.com

1G228资讯网——每日最新资讯28at.com

结合使用Twilio与Python

使用Twilio,您可以为各种事件构建短信通知系统。您可以将其与物联网设备一起使用,当设备的数值高于或低于某个阈值或者检测到入侵者时发送短信。您可以构建具有双因素身份验证的安全登录系统,构建WhatsApp聊天机器人和约会提醒系统。1G228资讯网——每日最新资讯28at.com

此之外,您还可以用它进行电话号码验证、营销活动、发送调查和收集反馈。在构建任何应用程序时,始终留意Twilio API定价,以免遭遇意外成本。1G228资讯网——每日最新资讯28at.com

原文标题:How to Build an OTP Verification System Using Python,作者:Sai Ashish Konchada1G228资讯网——每日最新资讯28at.com


1G228资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-10552-0.html如何使用Python构建OTP验证系统?

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 国际奥委会CITO艾拉里奥·孔纳:杭州亚运会用云计算创造历史

下一篇: Spring强大的数据格式化处理功能,你必须得知道

标签:
  • 热门焦点
  • 直屏旗舰来了 iQOO 12和K70 Pro同台竞技

    旗舰机基本上使用的都是双曲面屏幕,这就让很多喜欢直屏的爱好者在苦等一款直屏旗舰,这次,你们等到了。据博主数码闲聊站带来的最新爆料称,Redmi下代旗舰K70 Pro和iQOO 12两款手
  • 5月iOS设备性能榜:M1 M2依旧是榜单前五

    和上个月一样,没有新品发布的iOS设备性能榜的上榜设备并没有什么更替,仅仅只有跑分变化而产生的排名变动,刚刚开始的苹果WWDC2023,推出的产品也依旧是新款Mac Pro、新款Mac Stu
  • Golang 中的 io 包详解:组合接口

    io.ReadWriter// ReadWriter is the interface that groups the basic Read and Write methods.type ReadWriter interface { Reader Writer}是对Reader和Writer接口的组合,
  • 一个注解实现接口幂等,这样才优雅!

    场景码猿慢病云管理系统中其实高并发的场景不是很多,没有必要每个接口都去考虑并发高的场景,比如添加住院患者的这个接口,具体的业务代码就不贴了,业务伪代码如下:图片上述代码有
  • Python异步IO编程的进程/线程通信实现

    这篇文章再讲3种方式,同时讲4中进程间通信的方式一、 Python 中线程间通信的实现方式共享变量共享变量是多个线程可以共同访问的变量。在Python中,可以使用threading模块中的L
  • 腾讯VS网易,最卷游戏暑期档,谁能笑到最后?

    作者:无锈钵来源:财经无忌7月16日晚,上海1862时尚艺术中心。伴随着幻象的精准命中,硕大的荧幕之上,比分被定格在了14:12,被寄予厚望的EDG战队以绝对的优势战胜了BLG战队,拿下了总决
  • 大厂卷向扁平化

    来源:新熵作者丨南枝 编辑丨月见大厂职级不香了。俗话说,兵无常势,水无常形,互联网企业调整职级体系并不稀奇。7月13日,淘宝天猫集团启动了近年来最大的人力制度改革,目前已形成一
  • OPPO K11搭载高性能石墨散热系统:旗舰同款 性能凉爽释放

    日前OPPO官方宣布,将于7月25日14:30举办新品发布会,届时全新的OPPO K11将正式与大家见面,将主打旗舰影像,和同档位竞品相比,其最大的卖点就是将配备索尼
  • AI艺术欣赏体验会在上海梅赛德斯奔驰中心音乐俱乐部上演

    光影交错的镜像世界,虚实幻化的视觉奇观,虚拟偶像与真人共同主持,这些场景都出现在2019世界人工智能大会的舞台上。8月29日至31日,“AI艺术欣赏体验会”在上海
Top