programing

ASP.NET에 대한 전자 메일 주소 확인

easyjava 2023. 6. 13. 22:53
반응형

ASP.NET에 대한 전자 메일 주소 확인

ASP.NET 양식에서 전자 메일 주소의 유효성을 검사하는 데 사용하는 항목XSS 악용이 없는지 확인하고 싶습니다.

ASP.NET 1.1입니다.

ASP.NET 웹 양식에 게시된 스크립트 태그로 인해 사이트에서 예외가 발생하고 처리되지 않습니다.

aspregex validator를 사용하여 입력을 확인할 수 있습니다. Javascript가 바이패스되는 경우를 대비하여 if(IsValid) 절로 코드를 메서드 뒤에 감쌉니다.클라이언트 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>

여기 사이먼 존슨의 아이디어를 바탕으로 방금 만든 기본 이메일 검증기가 있습니다.필요한 경우 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;
        }

    }
}

업데이트: 원본 Regex를 사용하지 마십시오.보다 완벽한 최신 샘플을 찾습니다.

정규식 검증기를 사용할 수 있습니다.ValidationExpression 속성에는 Visual Studio 속성 패널에서 누를 수 있는 버튼이 있어 많은 유용한 표현식이 나열됩니다.전자 메일 주소에 사용되는 주소는 다음과 같습니다.

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

항상 서버 측 검증도 수행해야 합니다.

public bool IsValidEmailAddress(string email)
{
    try
    {
        var emailChecked = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch
    {
        return false;
    }
}

갱신하다

사용할 수도 있습니다.EmailAddressAttributeSystem.ComponentModel.DataAnnotations그렇다면 더 깨끗한 해결책을 시도해 볼 필요가 없습니다.

public bool IsValidEmailAddress(string email)
{
    if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
        return true;
    else
        return false;
}

참고:IsNullOrEmpty체크 또한 필요합니다. 그렇지 않으면null값이 true로 반환됩니다.

실제 전자 메일 주소인지 확인하는 것은 훨씬 더 어렵습니다.

구문이 올바른지 확인하는 정규식은 매우 길 수 있습니다(예: http://www.regular-expressions.info/email.html 참조).전자 메일 주소를 확인하는 가장 좋은 방법은 사용자에게 전자 메일을 보내고 링크를 클릭하여 전자 메일을 받았는지 확인하여 사용자에게 회신하도록 하는 것입니다(대부분의 등록 시스템 작동 방식).

코드에는 BaseValidator 클래스에서 상속된 특정 Validator가 있습니다.

이 클래스는 다음 작업을 수행합니다.

  1. 정규식에 대해 전자 메일 주소를 확인합니다.
  2. 도메인에 대한 MX 레코드를 조회하여 배달할 서버가 적어도 있는지 확인합니다.

이것은 실제로 사용자에게 전자 메일 확인 링크를 보내지 않고도 유효성 검사에 가장 근접할 수 있는 방법입니다.

XSS를 방지하는 것은 입력을 검증하는 것과는 다른 문제입니다.

XSS 관련:XSS 또는 관련 공격에 대한 입력을 확인하려고 하면 안 됩니다.일부 문자가 "마법"인 다른 언어에 문자열을 삽입할 때(예: HTML 또는 SQL에 문자열을 삽입할 때) 올바르게 이스케이프하여 XSS 악용, SQL 주입 등을 방지해야 합니다.예를 들어 O'Reilly와 같은 이름은 완벽하게 유효한 입력이지만 SQL에 이스케이프하지 않고 삽입하면 충돌이 발생하거나 더 악화될 수 있습니다.입력을 검증하여 이러한 문제를 방지할 수 없습니다.

사용자 입력의 유효성을 검사하면 누락되거나 잘못된 형식의 데이터(예: 사용자가 zip-code 필드에 "asdf"를 쓰는 등)를 방지할 수 있습니다.Wrt. 이메일 주소, 그러나 구문이 너무 복잡하여 정규식을 사용하여 유효성을 검사하는 데 큰 이점을 제공하지 않습니다."@"가 포함되어 있는지 확인하십시오.

빠르고 간단한 코드

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;
                    }
                }

언급URL : https://stackoverflow.com/questions/182542/email-address-validation-for-asp-net

반응형