How to check email address exists or not using ASP.NET? - asp.net

How to check the given email (any valid email) address exists or not using ASP.NET?

You can't check if an email exists without actually sending an mail.
The only thing you can check is if the address is in a correct shape with regexes:
string email = txtemail.Text;
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is corrct");
else
Response.Write(email + " is incorrct");

you send invitation mail to user with encrypted key..
If user is verified you have to verified key and you have only verified email..

Here's a code solution that may work for you. This sample sends a message from address different from From: address specified in the message. This is useful when bounced messages should be processed and the developer wants to redirect bounced messages to another address.
http://www.afterlogic.com/mailbee-net/docs/MailBee.SmtpMail.Smtp.Send_overload_3.html

The full process is not so simple.
Its required a full communication with the email server and ask him if this email exist or not.
I know a vendor that give a dll that make all this communication and check if the email exist or not on the server, the aspNetMX at http://www.advancedintellect.com/product.aspx?mx

First you need to import this namespace:
using System.Text.RegularExpressions;
private bool ValidateEmail(string email)
{
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
return true;
else
return false;
}
Visit Here to full source code.

Related

CreateUserWizard Username and Email Enumeration

I've been doing a security review of our website and found an issue with CreateUserWizard.
We do not let people sign up with a duplicate email address or username. The CreateUserWizard will verify this for me but the problem is that I can write a script to hit our server and try username and pretty quickly get a list of username by enumerating through them.
I want to add recaptcha but I can't seem to get it to verify this before it verifies the username. Is there a way to do this?
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnCreatedUser="CreateUserWizard1_CreatedUser" ContinueDestinationPageUrl="~/PleaseVerify.aspx" CssClass="CreateUserWizard" StepNextButtonStyle-CssClass="NextButton" StartNextButtonStyle-CssClass="NextButton" FinishCompleteButtonStyle-CssClass="FinishButton" CreateUserButtonText="Create my ID"
CompleteSuccessText="Your account has been created, but before you can login you must first verify your email address. A message has been sent to the email address you specified. Please check your email inbox and follow the instructions in that email to verify your account."
DisableCreatedUser="True" OnSendingMail="CreateUserWizard1_SendingMail" DuplicateUserNameErrorMessage="That username is already in use, if you think this is you can LINK REMOVED Otherwise try a different username."
DuplicateEmailErrorMessage="That email is already in use, try to <a href='/ForgotPassword.aspx'>recover your password</a>." InvalidPasswordErrorMessage="Please supply at least five letters in your password.">
I don't believe that the username is validated on the client side, so you could override your CreateUserWizard's CreateUserError event handler, check your captcha and NOT pass back an error about the username being already in use. I use a custom control captcha that I pieced together from www.codinghorror.com (http://www.codinghorror.com/blog/2004/11/captcha-control-coda.html), and it triggers before the backend code attempts to create the user and determines that the username/email is in use.
I ended up not using the create user wizard and just doing the simple login in the button handler.
recaptcha.Validate();
if (!recaptcha.IsValid)
{
ErrorMessage.Text = "Invalid Code.";
return;
}
if (!IsValid)
{
return;
}
var duplicateEmail = Membership.FindUsersByEmail(Email.Text);
if (duplicateEmail.Count > 0)
{
ErrorMessage.Text = "That email is already in use, try to <a href='/ForgotPassword.aspx'>recover your password</a>.";
return;
}
var duplicateUsername = Membership.FindUsersByName(UserName.Text);
if (duplicateUsername.Count > 0)
{
ErrorMessage.Text = "That username is already in use, if you think this is you can <a href='http://www.nanaimo.ca/dashboard/'>login</a>, otherwise try a different username.";
return;
}
var newUser = Membership.CreateUser(UserName.Text, Password.Text, Email.Text);
newUser.IsApproved = false;
Membership.UpdateUser(newUser);

How validate for domain name of email address

I have a form in which user enters email address.I am validating it through java script.I want to validate the Domain name of email address
What is the best way to validate domain name of email address in .net ?
best way for check domain name in Email address is use regular expression
this Expression use for validation email
\w+([-+.']\w+)#\w+([-.]\w+).\w+([-.]\w+)*
you can edit domain part in this expression \w+([-.]\w+)*\
this webservive is checking domain:
http://www.ecocoma.com/domain_webservice.aspx
you must substring domain name from email address and send to webservice
notice: for testing this webservive, you must online
sample code for working it:
protected void btnwhoIs_Click(object sender, EventArgs e)
{
try
{
Whois_Service service = new Whois_Service();
Whois whois = new Whois();
service.SoapVersion = SoapProtocolVersion.Soap12;
whois = service.GetWhois("DOM-T36309683M", "", txtWhoIs.Text);
divRes.InnerText = whois.Description;
}
catch (System.Net.WebException ex)
{
divRes.InnerText = ex.Message;
}
}
As #KingCronus said, there's no good method built in the framework for doing this. The most reliable method I know of is using this commercial component: http://cobisi.com/email-validation/.net-component
I've once done work using it for a client and it seemed reliable. You can use it to detect bogus email services (like http://mailinator.com/), but unfortunately, I don't know of any free component that performs this functionality.

Validating Email Using System.Net.Mail.MailAddress Fails

I'm trying to validate a list of email addresses using the following code:
Public Function ValidateEmailAddressField() As Boolean
Dim isValid As Boolean = True
Try
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(",", ";")
Dim validateMailAddress = New MailAddress(txtServiceEmails.Text.Trim)
Return isValid
Catch ex As Exception
isValid = False
Return isValid
End Try
End Function
When I enter "johndoe#amce" or "johndoe#acme, janedoe#acme.org" the code validates true. Is entering an email address without an extension, such as ".com", actually considered a valid email address?
Thanks,
crjunk
In an cooperation environment, a domain does not have to have .com/net/org... 'acme' could be a valid domain, so, the email me#acme could be a valid email address internally.
usually, people use regular expression to valid email address. there are lots of examples.
Yes, it is valid. The domain part of email address must match the requirements for a hostname and depending of local configurations the "extension" may be optative.
A hostname is considered to be a fully qualified domain name (FQDN) if all the labels up to and including the top-level domain name (TLD) are specified. The hostname en.wikipedia.org terminates with the top-level domain org and is thus fully qualified. Depending on the operating system DNS software implementation, an unqualified hostname such as csail or wikipedia may be automatically combined with default domain names configured into the system, in order to determine the fully qualified domain name. As an example, a student at MIT may be able to send mail to "joe#csail" and have it automatically qualified by the mail system to be sent to joe#csail.mit.edu.
Source: Wikipedia
Settled for a Regular Expression Validator solution.
Public Function ValidateEmailAddressField() As Boolean
Dim isValid As Boolean = True
Dim emailExpression As New Regex("^((\s*[a-zA-Z0-9\._%-]+#[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*[,;:]){1,100}?)?(\s*[a-zA-Z0-9\._%-]+#[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4})*$")
Try
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(",", ";")
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(" ", "")
isValid = emailExpression.IsMatch(txtServiceEmails.Text.Trim)
Return isValid
Catch ex As Exception
isValid = False
Return isValid
End Try
End Function

How to protect from tampering of query string?

Hii,
I have a query string like "http://project/page1.aspx?userID=5". The operation won't be performed, if the 'userID' parameter changed manually. How it is possible?
Hii all, thank you for your assistance... and i got some difference sort of solution from some other sites. i don't know that the best solution. that is to encode the value using an encryption and decryption algorithm... The sample code has been written like this...
<a href='Page1.aspx?UserID=<%= HttpUtility.UrlEncode(TamperProofStringEncode("5","F44fggjj")) %>'>
Click Here</a> <!--Created one anchor tag and call the function for TamperProofStringEncode-->
private string TamperProofStringEncode(string value, string key)
{
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + "-" + Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value)));
}
In the page load of 'Page1' call the decode algorithm to decode the query string
try
{
string DataString = TamperProofStringDecode(Request.QueryString["UserID"], "F44fggjj");
Response.Write(DataString);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
private string TamperProofStringDecode(string value, string key)
{
string dataValue = "";
string calcHash = "";
string storedHash = "";
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
try
{
dataValue = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[1]));
calcHash = System.Text.Encoding.UTF8.GetString(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)));
if (storedHash != calcHash)
{
//'Data was corrupted
throw new ArgumentException("Hash value does not match");
// 'This error is immediately caught below
}
}
catch (Exception ex)
{
throw new ArgumentException("Invalid TamperProofString");
}
return dataValue;
}
It sounds like a strange requirement. Are you trying to implement some sort of home-grown security? If it's so, you really shouldn't.
Anyway, one way you could do it would be to take the entire url http://project/page1.aspx?userID=5 and calculate its md5 sum. Then you append the md5 sum to the final url, such as http://project/page1.aspx?userID=5&checksum=YOURCALCULATEDMD5SUM. Then in page1.aspx you will have to validate that the checksum parameter is correct.
However, this approach is quite naïve and it would not necesarily take very long for anyone to figure out the algorithm you have used. If they did they could "easily" change the userid and calculate an md5 sum themselves. A more robust approach would be one where the checksum was encrypted by a key that only you had access to. But again I have to question your motive for wanting to do this, because other security solutions exist that are much better.
Here is another option that I found incredibly useful for my requirements:
4 Guys From Rolla - Passing Tamper-Proof QueryString Parameters
You can't.
Anything in the HTTP request (including URL, query string, cookies, ...) is under the control of the client and is easy to fake.
This is why it is important to whitelist valid content, because the client can arbitrarily add anything it likes in addition to what you you prompt to receive.
My favourite is the following. It uses a HTTPmodule to transparently encode and decode the Querystring with the explicit purpose of preventing tamperring of the querystring.
http://www.mvps.org/emorcillo/en/code/aspnet/qse.shtml
It is perfect when Session is not an option!
You can't tell whether it has been changed manually. If you use query strings then you hyave to make sure that it doesn't matter if it is changed. e.g. if you are using it to show a user their account details, you need to check wether the selected user, is the current user and show an error message instead of user data if it is not.
If the user is allowed to change record 5, but not record 7 for example, this has to be enforced server-side. To do this you need to be able to identify the user, by requiring a login, and giving them a unique session key that is stored in their browser cookie, or as another parameter in the url query string.
There are abundant packages/modules/libraries in man languages for dealing with authentication and sessions in a sensible way - roll you own at your own peril :)
Well - it depends :)
One possibility is to put the userID into a session variable. So the user cannot see or edit the value.
If you have other means to detect if the value is invalid (i.e. does not exist or cannot be for that user (who you can identify through some other way) or the like) you might get away with validating the input yourself in code behind.
But as you probably know you cannot prevent the user changing the query string.

Facebook Connect and ASP.NET

I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works
In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.
Examples in the documentation are geared towards facebook applications, which this is not.
Update
Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: http://developers.facebook.com/docs/
I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there's a successful login. You use the values of these cookies to perform API calls on the server.
The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that's ready to make requests on behalf of the logged in user.
Here's an example using the Facebook Toolkit on the server after the user has logged in with Facebook Connect.
Server code:
API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
// do something with the friend
}
Utility.cs
public static class Utility
{
public static string ApiKey()
{
return ConfigurationManager.AppSettings["Facebook.API_Key"];
}
public static string SecretKey()
{
return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
}
public static string SessionKey()
{
return GetFacebookCookie("session_key");
}
public static int GetUserID()
{
return int.Parse(GetFacebookCookie("user"));
}
private static string GetFacebookCookie(string name)
{
if (HttpContext.Current == null)
throw new ApplicationException("HttpContext cannot be null.");
string fullName = ApiKey() + "_" + name;
if (HttpContext.Current.Request.Cookies[fullName] == null)
throw new ApplicationException("Could not find facebook cookie named " + fullName);
return HttpContext.Current.Request.Cookies[fullName].Value;
}
}
I followed up on this concept and wrote a full fledged article that solves this problem in ASP.NET. Please see the following.
How to Retrieve User Data from Facebook Connect in ASP.NET - Devtacular
Thanks to Calebt for a good start on that helper class.
Enjoy.
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here: http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see: http://tinyurl.com/57ry3s for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set api.SessionKey and api.UserId from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
Facebook.Entity.User user = api.GetUserInfo(); //will get you started with the authenticated person
This is missing from the answers listed so far:
After login is successful, Facebook recommends that you validate the cookies are in fact legit and placed on the client machine by them.
Here is two methods that can be used together to solve this. You might want to add the IsValidFacebookSignature method to calebt's Utility class. Notice I have changed his GetFacebookCookie method slightly as well.
private bool IsValidFacebookSignature()
{
//keys must remain in alphabetical order
string[] keyArray = { "expires", "session_key", "ss", "user" };
string signature = "";
foreach (string key in keyArray)
signature += string.Format("{0}={1}", key, GetFacebookCookie(key));
signature += SecretKey; //your secret key issued by FB
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signature.Trim()));
StringBuilder sb = new StringBuilder();
foreach (byte hashByte in hash)
sb.Append(hashByte.ToString("x2", CultureInfo.InvariantCulture));
return (GetFacebookCookie("") == sb.ToString());
}
private string GetFacebookCookie(string cookieName)
{
//APIKey issued by FB
string fullCookie = string.IsNullOrEmpty(cookieName) ? ApiKey : ApiKey + "_" + cookieName;
return Request.Cookies[fullCookie].Value;
}
The SecretKey and ApiKey are values provided to you by Facebook. In this case these values need to be set, preferably coming from the .config file.
I followed up from Bill's great article, and made this little component. It takes care of identifying and validating the user from the Facebook Connect cookies.
Facebook Connect Authentication for ASP.NET
I hope that helps somebody!
Cheers,
Adam
You may also use SocialAuth.NET
It provides authentication, profiles and contacts with facebook, google, MSN and Yahoo with little development effort.
My two cents: a very simple project utilizing the "login with Facebook" feature - facebooklogin.codeplex.com
Not a library, but shows how it all works.

Resources