我想将OTP设置为1分钟,以便1分钟后可以过期。我通过电子邮件发送OTP并且它正在工作但是OTP在1分钟后没有过期。
下面是我的代码。
这是.cs文件
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.Net;
namespace OTP_Generation
{
public partial class OTPThroughEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Sent_OTP_Click(object sender, EventArgs e)
{
//generate otp
Random rand = new Random();
string digits = rand.Next(0, 999999).ToString("D6");
ViewState["otp"] = digits;
bool check = sendMail("Your OTP is :" + digits);
if (check)
{
msg.Text = "OTP sent successfully";
}
else
{
msg.Text = "Error in sending Email";
}
}
public bool sendMail(string msg)
{
bool check = false;
try
{
MailMessage mail = new MailMessage("[email protected]", "[email protected]");
mail.Subject = "Verify code";
mail.Body = msg;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("[email protected]", "******");
smtp.EnableSsl = true;
smtp.Send(mail);
check = true;
}
catch (Exception e)
{
exception.Text = e.Message;
check = false;
}
return check;
}
protected void Verify_OTP_Click(object sender, EventArgs e)
{
if (textBox.Text.Equals(""))
{
msg.Text = "Please Enter the OTP";
return;
}
if(textBox.Text.Equals(ViewState["otp"].ToString()))
{
msg.Text = "OTP verified";
}
else
{
msg.Text = "OTP is wrong";
}
}
}
}
这是.aspx文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OTPThroughEmail.aspx.cs" Inherits="OTP_Generation.OTPThroughEmail" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<label id="l" >Enter OTP digit</label>
<asp:TextBox ID="textBox" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Sent_OTP" Text="Sent OTP" runat="server"
onclick="Sent_OTP_Click" />
<asp:Button ID="Verify_OTP" Text="Verify OTP" runat="server"
onclick="Verify_OTP_Click" />
<br /><br />
<asp:Label ID="msg" runat="server" ></asp:Label>
<br />
<asp:Label ID="exception" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
我还在Web.config文件中的“system.web”中设置了“sessionState”
<sessionState cookieless="false" timeout="1"></sessionState>
当我运行上面的代码时,每次都会验证OTP。我也尝试使用Session(用Session替换ViewState),但它在下一行中抛出NullReferenceException:
if(textBox.Text.Equals(Session["otp"].ToString()))
我在网上搜索但是在1分钟后找不到设置过期的方法。我也试过this,但它没有用。
请帮忙......谢谢
使用Random生成OTP是一种不好的做法。查看TOTP算法(RFC 6238),该算法专门用于生成有效性有限的OTP。
另外,请注意,通过电子邮件发送OTP不是真正的双因素身份验证。
也许,对于你的情况,电子邮件和随机生成器中的OTP都可以,但一般来说应该避免这种做法。