Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make WebSecurity.Login to login using username or email?

Tags:

WebSecurity.Login in simplemembership take username and password, how to make it to login the user using username or email instead of just username?, to make the user free to enter his email or username to login.

like image 568
Amr Elgarhy Avatar asked Sep 13 '12 10:09

Amr Elgarhy


People also ask

What is the Websecurity class in net what is its use?

Definition. Provides security and authentication features for ASP.NET Web Pages applications, including the ability to create user accounts, log users in and out, reset or change passwords, and perform related tasks.

What is Websecurity in MVC?

Based on these templates, the web project is scaffolded and we get the final project structure to work on. If we select an internet application then from the default scaffolding we get a Controller for "Home" and "Account" created. ASP.NET MVC by default provides the authentication using the Web Security.

What is WebMatrix webdata?

WebMatrix.Security. This package contains the helper library to enable OAuth and OpenID authentication for ASP.NET Web Pages websites.


1 Answers

You could inherit from the SimpleMembershipProvider and just override the ValidateUser method like this.

public class ExtendedSimpleMembershipProvider : SimpleMembershipProvider
{
    public override bool ValidateUser(string login, string password)
    {
        // check to see if the login passed is an email address
        if (IsValidEmail(login))
        {
            string actualUsername = base.GetUserNameByEmail(login);
            return base.ValidateUser(actualUsername, password);
        }
        else
        {
            return base.ValidateUser(login, password);
        }

    }

    bool IsValidEmail(string strIn)
    {
        // Return true if strIn is in valid e-mail format.
        return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }

}

This is just one approach. You could write your own MembershipProvider but if you only need to change the ValidateUser method this should work.

Add the following configuration to the web.config to setup the provider.

  <membership defaultProvider="ExtendedSimpleMembershipProvider">   
    <providers>
    <clear/>
    <add name="ExtendedSimpleMembershipProvider"
         type="MyProject.Web.SimpleMembershipProvider, MyProject.Web"/>
    </providers>
  </membership>

That should get you going in the right direction.

like image 127
matt. Avatar answered Oct 18 '22 20:10

matt.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!