【发布时间】:2010-09-16 00:02:52
【问题描述】:
您使用什么来验证 ASP.NET 表单上的电子邮件地址。我想确保它不包含 XSS 漏洞。
这是 ASP.NET 1.1
【问题讨论】:
标签: asp.net validation email
您使用什么来验证 ASP.NET 表单上的电子邮件地址。我想确保它不包含 XSS 漏洞。
这是 ASP.NET 1.1
【问题讨论】:
标签: asp.net validation email
防止 XSS 与验证输入是不同的问题。
关于 XSS:您不应该尝试检查 input 是否存在 XSS 或相关漏洞。在将字符串插入某些字符是“魔法”的不同语言(例如,在 HTML 或 SQL 中插入字符串时)时,您应该通过正确转义来防止 XSS 攻击、SQL 注入等。例如,像 O'Reilly 这样的名称是完全有效的输入,但如果未转义地插入 SQL,可能会导致崩溃或更糟。您无法通过验证输入来防止此类问题。
验证用户输入对于防止丢失或格式错误的数据很有意义,例如。用户在邮政编码字段中写入“asdf”等。写。电子邮件地址,但语法非常复杂,使用正则表达式验证它并没有提供太多好处。只需检查它是否包含“@”。
【讨论】:
您可以使用正则表达式验证器。 ValidationExpression 属性有一个按钮,您可以在 Visual Studio 的属性面板中按下该按钮,该面板会列出许多有用的表达式。他们使用的电子邮件地址是:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
【讨论】:
在 ASP.NET Web 表单上发布的任何脚本标记都会导致您的网站抛出未处理的异常。
您可以使用 asp 正则表达式验证器来确认输入,只需确保使用 if(IsValid) 子句将代码包装在方法后面,以防您的 javascript 被绕过。 如果您的客户端 javascript 被绕过并且脚本标签被发布到您的 asp.net 表单,asp.net 将抛出一个未处理的异常。
你可以使用类似的东西:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
【讨论】:
验证它是一个真实的电子邮件地址要困难得多。
确认语法正确的正则表达式可能很长(例如,参见http://www.regular-expressions.info/email.html)。确认电子邮件地址的最佳方法是向用户发送电子邮件,并让用户通过单击链接来回复以确认他们已收到电子邮件(大多数注册系统的工作方式)。
【讨论】:
在我们的代码中,我们有一个从 BaseValidator 类继承的特定验证器。
这个类做了以下事情:
这是最接近验证的方式,无需实际向此人发送电子邮件确认链接。
【讨论】:
这是我刚刚根据 Simon Johnson 的想法创建的基本电子邮件验证器。如果需要,它只需要添加 DNS 查找的额外功能。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI;
namespace CompanyName.Library.Web.Controls
{
[ToolboxData("<{0}:EmailValidator runat=server></{0}:EmailValidator>")]
public class EmailValidator : BaseValidator
{
protected override bool EvaluateIsValid()
{
string val = this.GetControlValidationValue(this.ControlToValidate);
string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
Match match = Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);
if (match.Success)
return true;
else
return false;
}
}
}
更新:请不要使用原始的正则表达式。寻找更新更完整的样本。
【讨论】:
[a-z|0-9|] 中的| 似乎是错误的。您是否知道这将匹配 | 字符并且不能作为替代?此外,我的电子邮件地址失败了(用 1a@a.com 或 a@1.com 测试),所以这显然是错误的。
您也应该始终进行服务器端验证。
public bool IsValidEmailAddress(string email)
{
try
{
var emailChecked = new System.Net.Mail.MailAddress(email);
return true;
}
catch
{
return false;
}
}
更新
您也可以在System.ComponentModel.DataAnnotations 中使用EmailAddressAttribute。那么就没有必要尝试捕获它是一个更清洁的解决方案。
public bool IsValidEmailAddress(string email)
{
if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
return true;
else
return false;
}
请注意,IsNullOrEmpty 检查也是必需的,否则 null 值将返回 true。
【讨论】:
快速简单的代码
public static bool IsValidEmail(this string email)
{
const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
【讨论】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for RegexUtilities
/// </summary>
public class RegexUtilities
{
bool InValid = false;
public bool IsValidEmail(string strIn)
{
InValid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
if (InValid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
InValid = true;
}
return match.Groups[1].Value + domainName;
}
}
RegexUtilities EmailRegex = new RegexUtilities();
if (txtEmail.Value != "")
{
string[] SplitClients_Email = txtEmail.Value.Split(',');
string Send_Email, Hold_Email;
Send_Email = Hold_Email = "";
int CountEmail;/**Region For Count Total Email**/
CountEmail = 0;/**First Time Email Counts Zero**/
bool EmaiValid = false;
Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
if (SplitClients_Email[0].ToString() != "")
{
if (EmailRegex.IsValidEmail(Hold_Email))
{
Send_Email = Hold_Email;
CountEmail = 1;
EmaiValid = true;
}
else
{
EmaiValid = false;
}
}
if (EmaiValid == false)
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Enter A Valid Email ID.";
txtEmail.Focus();
txtEmail.Value = null;
ScriptManager.RegisterStartupScript(Page, this.GetType(), "SmoothScroll", "SmoothScroll();", true);
divStatusMsg.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabel();", true);
return false;
}
}
【讨论】: