Wednesday, August 13, 2008

Programmatically creating DotNetNuke user passwords

When programmatically creating a DotNetNuke portal, the CreatePortal method API expects passwords that are already encrypted. In DotNetNuke, by default the passwords are encrypted using one way Triple DES algorithm. There is existing functionality in DotNetNuke that can be reused to encrypt plain text passwords. Listed below is some sample code that can be used.

Requirements: The code listed below uses the following classes that can be found in the assembly: DotNetNuke.dll

  • DotNetNuke.Security.PortalSecurity
  • DotNetNuke.Common.Globals
  • DotNetNuke.Entities.Users.UserController

   1: string userName = "sampleUserName";
   2:  
   3: //generate a random 8 character password
   4: string password = UserController.GeneratePassword(8)
   5:  
   6: //get the machine's encryption key
   7: string key = Convert.ToString(Globals.HostSettings["EncryptionKey"]);
   8:  
   9: //encrypt the password with the machines encryption key
  10: PortalSecurity portalSecurity = new PortalSecurity();
  11: password = portalSecurity.Encrypt(key, password);

Line 4: We generate a random 8 character password using the static GeneratePassword in the UserController class. It is not required to use the method, you can substitute it with you own logic. Keep in mind to satisfy the password requirements configured in DotNetNuke.
Line 7: When users login, DotNetNuke encrypts the plain text password using the encryption key that is stored in the web.config. It then compares it to the encrypted version that is stored in the database, and if they match the login successed. We have to use the same encryption key or else the user will not be able to login even if he uses the right password. We use the Globals class which contains a collection of utility functions, to retrieve the encryption key.
Line 11: We use the Encrypt method of the PortalSecurity class to encrypt the password.

2 comments:

  1. thanks for this post
    i'm newer in dnn
    but my portal need to create new user by code
    i will try your code

    ReplyDelete
  2. Not Working. Always give blank string.

    ReplyDelete

Subscribe to my feed in your favorite feed reader