Mostrando las entradas con la etiqueta Login Control. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Login Control. Mostrar todas las entradas

martes, 26 de junio de 2018

ASP.Net Login Control - How to get user's password using Membership with passwordFormat like encrypted


    In order to allow the system to get a user's password from our database when we are using a Membership provider and the ASP.Net Login Control, it is necessary to follow up the steps below:

1) Inside the web.config file find the membership tag into the system.web, add/update the properties below:
    enablePasswordRetrieval = "true"
    passwordFormat = "Encrypted"


<membership> <providers> <clear/> <add name="ExtendedSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="testDB" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" passwordFormat="Encrypted" /> </providers> </membership>

2) Create the keys using the code below:

public static class RNGCrypto_MachineKey
{
    public static string getRandomKey(int bytelength)
    {
        byte[] buff = new byte[bytelength];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(buff);
        StringBuilder sb = new StringBuilder(bytelength * 2);
        for (int i = 0; i < buff.Length; i++)
            sb.Append(string.Format("{0:X2}", buff[i]));
        return sb.ToString();
    }
}

How to call the function above?:
string key64 = RNGCrypto_MachineKey.getRandomKey(64);
string key32 = RNGCrypto_MachineKey.getRandomKey(32);

3) Now, inside the web.config file, add the following inside the tag system.web and apply the keys you got from the code above:
 <machineKey validationKey="paste here the key64 string" decryptionKey="paste here the key32 string" validation="SHA1" decryption="AES"/>

4) Change the PasswordFormat from the table Memberships and assign the value 2 (it means Encrypted) to all the users
5) Inside your backend code, write the instructions to reset and save a new password
MembershipUser UserInfo = Membership.GetUser("UserName", false);
string ResetPassword = UserInfo.ResetPassword();
IsPasswordChanged = UserInfo.ChangePassword(ResetPassword, "password");
6) Once you have changed all passwords using the encrypted format (specified in web.config), add the instruction below to get the password from the database
string sPassword = Membership.GetUser("UserName").GetPassword();