譯者 | 布加迪
審校 | 重樓
即使您的密碼被盜,OTP驗證系統也可以充當安全的關鍵要素。它讓您無需記住密碼,充當額外的安全層,并降低了網絡釣魚的風險。
不妨學習用Python建立一個OTP驗證系統,它會向您的手機號碼發送一個OTP,有效期只有兩分鐘,如果您連續三次輸錯OTP,賬戶會被鎖住。
Tkinter允許您創建桌面應用程序。它提供了各種小組件,比如按鈕、標簽和文本框,使開發應用程序變得更容易。
Twilio模塊幫助您把短信、彩信和電話呼叫等通信功能與驗證徑直整合到應用程序中。它有一個基于云的基礎設施,以及令人驚嘆的功能,比如號碼配置、消息模板和呼叫記錄。
要安裝Twilio模塊和Tkinter模塊,在終端執行如下命令:
pip install twilio tk
Random模塊是內置的Python模塊,用于生成偽隨機數。有了該模塊,您可以生成隨機數、從列表中選擇隨機元素、打亂列表內容等。您可以用它來構建擲骰子模擬、列表打亂器或隨機密碼生成器。
要使用Twilio并向您的手機發送OTP請求,您需要身份驗證憑據以及Twilio電話號碼。為此:
1. 注冊一個Twilio賬戶,訪問Twilio控制臺。
2. 向下滾動并點擊“獲取電話號碼”按鈕。復制已生成的電話號碼。
3. 向下滾動到“賬戶信息”部分。復制“賬戶SID”和“身份驗證令牌”。
事先聲明一下,您可以在這個GitHub代碼倉庫中找到使用Python構建OTP驗證系統的完整源代碼。
導入必要的模塊,并設置身份驗證憑據。初始化Twilio客戶軟件以驗證身份,并作為API調用的入口點。將到期失效時間設為兩分鐘。
定義一個類:OTPVerification,并初始化構造函數以設置變量的默認值,同時初始化根窗口,并設置應用程序的標題和維度。
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后顯示計時器。設置父元素、它應該顯示的文本以及該有的字體樣式。同樣,創建兩個輸入小組件以獲取用戶輸入。設置父元素、寬度和字體樣式。
創建三個按鈕來發送OTP、重新發送OTP和驗證OTP。設置父元素、它應該顯示的文本、點擊時執行的命令及其字體樣式。使用pack方法組織這些元素。
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_countdown。
def start_timer(self): self.timer_thread = threading.Thread(target=self.timer_countdown) self.timer_thread.start()
定義一個方法timer_countdown()。記錄開始時間,并運行一個無限循環,該循環獲取當前時間并計算已流逝的時間和剩余時間。如果stop_timer為true,終止循環。如果剩余時間小于或等于0,顯示錯誤消息框,表明OTP已過期。
激活重新發送OTP按鈕,將OTP設置為none,并終止。否則,計算剩余的分鐘和秒,將其顯示在計時器標簽上,并休眠一秒鐘。
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發送到您的電話號碼。顯示消息框,啟動計時器,禁用按鈕,并完全清除輸入內容。
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按鈕。
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次,鎖住賬戶。
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分鐘)。
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,重置賬戶。否則顯示程序已鎖住賬戶,并在剩余時間內使用回調再試一次。
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()。像前面一樣重置所有小組件和變量的狀態。
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應用程序。
if __name__ == '__main__': root = tk.Tk() otp_verification = OTPVerification(root) root.mainloop()
在運行OTP驗證程序時,您會看到一個窗口,要求輸入手機號碼。輸入手機號碼以及所在國家代號,然后點擊“發送OTP”按鈕。您會收到一條消息,表明程序已成功發送OTP,按鈕會停用兩分鐘。檢查手機是否收到了OTP,并在過期前輸入它。
在計時器過期前輸入正確的OTP后,您將收到一條消息,表明程序已成功驗證了OTP,退出程序。如果您沒有及時輸入,會收到消息框,表明OTP已過期。可以點擊“重新發送OTP”按鈕以生成新的OTP,并發送到您的手機。
如果您輸錯了OTP,程序將顯示一個消息框,表明“OTP不匹配”。
如果OTP輸錯三次,所有字段將被禁用,賬戶將被鎖住十分鐘。
使用Twilio,您可以為各種事件構建短信通知系統。您可以將其與物聯網設備一起使用,當設備的數值高于或低于某個閾值或者檢測到入侵者時發送短信。您還可以構建具有雙因素身份驗證的安全登錄系統,構建WhatsApp聊天機器人和約會提醒系統。
除此之外,您還可以用它進行電話號碼驗證、營銷活動、發送調查表和收集反饋。在構建任何應用程序時,始終留意Twilio API的定價,以免遭遇意外成本。
原文標題:How to Build an OTP Verification System Using Python,作者:Sai Ashish Konchada
本文鏈接:http://www.tebozhan.com/showinfo-26-10552-0.html如何使用Python構建OTP驗證系統?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com