Creating a Standard DotNetNuke User Via SQL 

Due to popular demand from my "Creating a Host Account Via SQL" article, this article is an extension of that article to show you how to create a regular portal user based on the password for an existing user account.  The first portions of this process are very similar to that of the host account creation, however there are a few additional steps.

Requirements

For these instructions to work properly you MUST know the password of at least one user account in your portal. This can be any user account as long as it is for the same application! Also you should be running DotNetNuke 4.4.1 or later as these instructions have NOT been tested on any previous versions.

Disclaimer

I am providing this example as exactly that an example. Anytime you directly modify the database you are introducing a level of risk. Please take the appropriate safety precautions and backup your database before proceeding, I can not be liable for any data loss that may occur from you performing these steps.

Obtain Needed Information

The first step of the process to creating a new user account via the database is to obtain some needed information. We need the "Application Name" for your DotNetNuke installation, typically this is simply "dotnetnuke", it is set in your web config under the membership element.  We also need the "password", "passwordSalt" and "PasswordFormat" values from the aspnet membership table for a working user account with a known password.  Below is a query to obtain this information.  NOTE: replace the text TestUser with the username of your known working user account.

SELECT m.password, m.passwordsalt, m.passwordformat
FROM aspnet_users u
    
INNER JOIN aspnet_membership m
        
ON (u.userid m.userid)
WHERE u.UserName 'TestUser'

The final piece of information that we need is the id of your portal, this can be obtained from the "Portals" table, below is a query that will give you the portal name and portalId of each portal in your DNN installation.

SELECT PortalId,
     PortalName
FROM Portals

Execute Scripts to Create Account

Now we simply combine our desired new information and the existing information that we obtained to create the user account. Below is a listing of the SQL Code that I used to create the account in my portal. You will need to substitute your own values for the various properties. Also, I am using the long format to accomplish this goal by declaring each of the variables prior to calling the stored procedure, this is simply done to make the code easier to read.  You will also want to change the hard coded values for FirstName, LastName, and DisplayName.  I did not declare variables for those to reduce the length of the sample code.

DECLARE @ApplicationName nvarchar(256)
SET @ApplicationName 'DotNetNuke'
DECLARE @UserName nvarchar(256
SET @UserName 'NewUser' --The new user
DECLARE @Password nvarchar(128)
--From the existing user
SET @Password 'LLSXX8xW6+0EbrV4JBzL/YenA1D6BBfRnkYY7FtQvNGmmPOhVdPiAA=='
DECLARE @PasswordSalt nvarchar(128)
--From the existing user
SET @PasswordSalt 'P40ky5tExsx37nUIFnCWZQ=='
DECLARE @Email nvarchar(256)
SET @Email 'TestingAccount@test.com' --You can set this to whatever you want
DECLARE @PasswordQuestion nvarchar(256)
SET @PasswordQuestion ''
DECLARE @PasswordAnswer nvarchar(128)
SET @PasswordAnswer ''
DECLARE @IsApproved bit
SET 
@IsApproved 1
DECLARE @CurrentTimeUtc datetime 
SET 
@CurrentTimeUtc = GETDATE()
DECLARE @CreateDate datetime
SET 
@CreateDate @CurrentTimeUtc
DECLARE @UniqueEmail int
SET 
@UniqueEmail 0
DECLARE @PasswordFormat int
SET 
@PasswordFormat --NOTE: Value from existing user!
DECLARE @PortalId int
SET 
@PortalId 0    --The id of your portal
Declare @UserId uniqueidentifier
DECLARE 
@DNNUserId int

--Make the stored procedure call
EXEC dbo.aspnet_Membership_CreateUser @ApplicationName, @Username, @Password,
                @PasswordSalt, @email, @passwordquestion, @PasswordAnswer, 
                @IsApproved, @CurrentTimeUtc, @CreateDate, @UniqueEmail,
                @PasswordFormat, @UserId

--Insert the record into the DotNetNuke users table
INSERT INTO users (Username, FirstName, LastName, IsSuperUser, Email,
                    DisplayName, UpdatePassword)
    
VALUES(@Username, 'My''NewAccount'0, @Email, 'New Account'0)

--Get the new userid, from the DNN users table
SELECT @dnnuserid userid
FROM Users
WHERE username @Username

--Now, insert the record into the user portals table
INSERT INTO UserPortals (userId, PortalId, CreatedDate)
    
VALUES(@dnnuserid, @PortalId, GETDATE()) 

--Now Give the user permissions to the RECISTERED Users group
INSERT INTO UserRoles (userId, roleId)
SELECT @dnnuserid,
        roleId
FROM Roles
WHERE RoleName 'Registered Users'

The script should execute successfully with simple messages regarding record counts, no error messages should be displayed. To explain a bit more what the above script does.  First the "Declare" and "Set" statements simply build parameters for use later.  We then create the ASP.NET membership records for our new user.  We then create our DotNetNuke user record to ensure that DNN is aware of the user.  Then we obtain the id of the added user and then create a UserPortals record to grant the user access to the specified portal.

Logging In!

You should now be able to navigate to your DNN site and login with the new user account and the password from the account you copied. Upon login you should have full host permissions!

If you have any questions or comments regarding this please let me know! This is considered a last resort, however, it is something that can be used in times of need.

Posted by Mitchel on Monday, May 14, 2007
 

Comments

Does this enter them in the UserRoles table as a "Registered User"

By erik on Tuesday, May 15, 2007 at 2:33 PM

Erik,

I greatly apologize the origional posting did not insert that record. I have updated the script and it now does create the user as a "Registered" user.

By mitchel.sellers@gmail.com on Tuesday, May 15, 2007 at 4:42 PM

Hi there,

I have been looking for this sort of script so I can setup DNN users from a windows application using ADO.

It sort of works and I don't get any errors when running the script. The user information is sitting in all the neccessary tables, but when I attempt to login as the newly created user, I get the following message....
A critical error has occurred.
Object reference not set to an instance of an object.

I also notice that the created date next to the listed users that have been created in this way is blank, though this created date is showing in the membership table.

Are you able to give me any pointers.

Thanks for making this script available to the dotnetnuke community.

Regards

Joe Davies

By Joe Davies on Tuesday, May 29, 2007 at 7:33 AM

Joe,

Which data table shows a blank value for the created date?

By mitchel.sellers@gmail.com on Tuesday, May 29, 2007 at 9:17 AM

Hi Mitchell,

I think the created date comes from the aspnet_membership table. This is the table that has the password and passwordSalt. The date is actually set correctly in this table but it isn't displaying in the user list.

I've carefully looked at all the tables that contain a userID field to see if there is anything obviously missing but it all appears fine. I'm still unable to login with the new users credentials. I've created different users but they are all inaccessible.

Mmmh strange one!

Joe

By Joe Davies on Tuesday, May 29, 2007 at 6:27 PM

That is a strange one.

There isn't by chance an error message in the event log is there?

Also, you do have the userportals entry that ws added after my update to this article correct?

By mitchel.sellers@gmail.com on Tuesday, May 29, 2007 at 10:28 PM

I've sorted it, I had changed the application name from 'dotnetnuke' to what I thought should have been my database name. I put it back as it was and it works like a dream now.

I have now created a simple function in Microsoft Access which reads in your script from a lookup table. I then use replace tokens in the script as simple parameters. A passthrough query is then created on the fly and bingo a new user appears in the portal. I can also force the resetting of a password by using 1 instead of 0 in the bolSetPassword argument.

This script of yours has been a godsend.

Thanks again!

Joe

For those interested see function below
'===========================
Function CreateUser(strUserID As String, strUserEmail As String, intPortalID As Integer, strFirstName As String, _
strLastName As String, strDisplayName As String, bolSetPassword As Integer)

Dim MyDb As Database, MyQ As QueryDef, strSQL As String
Set MyDb = CurrentDb()

' Create a temporary QueryDef object that is not saved.
Set MyQ = MyDb.CreateQueryDef("")

' A system DSN has to be setup for pass through queries.
MyQ.Connect = "ODBC;DSN=dsn;UID=userid;PWD=password;DATABASE=databasename"

' Set ReturnsRecords to false in order to use the Execute method.
MyQ.ReturnsRecords = False

' look up the script and replace the tokens with function arguments
strSQL = DLookup("[CreateNewUser]", "tblSettings")

strSQL = Replace(strSQL, "", strUserID)
strSQL = Replace(strSQL, "", strUserEmail)
strSQL = Replace(strSQL, "", intPortalID)
strSQL = Replace(strSQL, "", strFirstName)
strSQL = Replace(strSQL, "", strLastName)
strSQL = Replace(strSQL, "", strDisplayName)
strSQL = Replace(strSQL, "", bolSetPassword)

MyQ.SQL = strSQL
'Debug.Print strSQL
MyQ.Execute
MyQ.Close
MyDb.Close

End Function

By Joe Davies on Wednesday, May 30, 2007 at 12:14 PM

I was wondering, would the process for updating passwords for dnn user account be achieved similarly?

By Scott on Tuesday, September 25, 2007 at 3:53 PM

Scott,

If you wanted to "copy" a password from an existing account, then yes. If you want to pick a password that another account doesn't have then no.

By mitchel.sellers@gmail.com on Tuesday, September 25, 2007 at 5:25 PM

Thanks Mitchel just the thing I was looking for.

Three questions:
1. What is passwordSalt
2. I want to add a number of users and would like to give them unique passwords. is that possible.
3. Is the UserName unique?

By Ali on Thursday, September 27, 2007 at 2:36 PM

Ali,

1.) It is used to futher secure the actual password that is stored, I am not 100% sure how the salt is used in the microsoft implementation but it is a standard security practice.

2.) If you want to specifically set a password you will need to go another way, possibly look for a batch import module. I will be working on one to release within the next 2-3 weeks., otherwise John Mitchell over at Snapsis has an .aspx page that you can use to import as well.

3.) Yes, the username must be unique!

By mitchel.sellers@gmail.com on Thursday, September 27, 2007 at 6:38 PM

Of course that you can set unique passwords.
PasswordFormat column is where you can set how you want your password to be stored:
PasswordFormat=0 -> Clear
PasswordFormat=1 -> Hashed
PasswordFormat=2 -> Encrypted

By default dnn is set to use Encryption algorithms - 'Triple DES'

If you are not familiar with hashing and encription you can just simple set your PasswordFormat to be 0.
Or make small research on SHA1, MD5, Triple-DES - It is simple.

By Ali, on Saturday, August 23, 2008 at 1:07 AM

Ali,

Do you happen to know how to properly encrypt the DNN password?

How about what the PasswordSalt stands for?

I've been trying to decrypt the users passwords so that I can export users profile to another application that I am building.

By Tim on Tuesday, October 14, 2008 at 2:20 AM

Tim,

There are methods provided by the UserController class to decrypt the password. Make a post in the forums, and I can try to point you in the right direction.

By mitchel.sellers@gmail.com on Tuesday, October 14, 2008 at 9:16 AM

Mitchel,
This is a great script that I am not using for a custom registration system I am building with Indoogrid. I am using it on the insert record event when adding a new user to my Indoogrid user tables. So, in effect, the system also adds the user to the DNN tables and sets them up as a registered user. This is great. But, now I am trying to modify this script to "update" users on the update event and "delete" users on the delete event. Does anyone know how to properly call the corresponding dnn stored procedures to make this happen?

By Bill Shoao on Friday, March 06, 2009 at 9:53 AM

are you encrypt the paasword while you insert it ?

By almny on Sunday, May 17, 2009 at 5:14 AM

This is great for module Testing, just configure it to loop, with a int at the end of the user and bam, 100's of users added to your database for testing. be mindful, the users will have all the same information unles you add a number or such to randomize it. works great for what i'm using it for, Thanks!

By Marcus on Tuesday, June 09, 2009 at 12:04 PM

I need to delete users from the database???
How can a non-techie like me do this???

Thanks, Chad

By Chad Statham on Monday, July 27, 2009 at 7:50 PM

Chad,

"Can" you? Yes

"Should" you? No, this is a VERY risky operation!

By mitchel.sellers@gmail.com on Monday, July 27, 2009 at 7:51 PM

Do you know if there is a way to create a portal using SQL?

Thanks.

By mike on Tuesday, November 24, 2009 at 1:52 PM

Mike,

You can, but there is a lot of data to do

By mitchel.sellers@gmail.com on Tuesday, November 24, 2009 at 1:53 PM

Beautiful! We used this to create a custom user registration form and put the user into the system then redirect to another page.

We are manually assigning a password and they are supplying the username. So they get registered into the system with a unique username and a common password.

The problem I am having now is that I need the user to be logged in with their userid when they get redireted because the page they land on requires them to be registered.

I have searched for about half a day trying to find an answer to this to no avail. Any ideas?

By cmmitw on Thursday, December 31, 2009 at 3:12 PM

I am getting this error, can you please tell me the solution.
"we cannot insert the value Null into column UserID on the UserProfile table."

By Kiran on Friday, January 22, 2010 at 12:37 PM

I got that solved, but i have one more question not related to this
I have DNN website and Attached database, and i have 2nd database also, which i need to modify through DNN website, but i am getting permissions error when i try to access or modify 2nd database, here is the error "The SELECT permission was denied on the object 'retirees', database 'RebisTest', schema 'dbo'. The UPDATE permission was denied on the object 'retirees', database 'RebisTest', schema 'dbo'." RebisTest is the second database. I tried a lot but i am not able to solve the issue can you suggest me something that can work.

By Kiran on Friday, January 22, 2010 at 4:56 PM

I got that solved, but i have one more question not related to this
I have DNN website and Attached database, and i have 2nd database also, which i need to modify through DNN website, but i am getting permissions error when i try to access or modify 2nd database, here is the error "The SELECT permission was denied on the object 'retirees', database 'RebisTest', schema 'dbo'. The UPDATE permission was denied on the object 'retirees', database 'RebisTest', schema 'dbo'." RebisTest is the second database. I tried a lot but i am not able to solve the issue can you suggest me something that can work.

By kiran on Friday, January 22, 2010 at 4:57 PM

I would like to add all Registered users to another role.
Could you help me with this?

By Phil Speth on Wednesday, January 27, 2010 at 6:56 AM

Sir,
I need same kind of encrryption in php.
can you help me. Because I have to integrate my php login to aspnet_membership table.

By bharat on Sunday, January 31, 2010 at 1:16 AM

nice script
However, encounter issue with encrypting the password so that it does not save clear text as it is when user register online.
I change password format = 2, but my password 1234567 does not get encrpyted.

Btw, currently using DNN 5.04.1

By bpwebonline on Sunday, May 16, 2010 at 10:18 AM

Hi Mitchel,

Great script! However I have a question about the passwordSalt... Where does the it come from? In my database, in the table aspnet_Membership, every users created by the module "Users and roles" of dnn have a different password salt. If I create users with this script they will all have the same passwordSalt. Is there any security issues or every thing is ok? I use DNN 5.4.4. Thank you.

By Jeff Ferland on Wednesday, September 08, 2010 at 8:59 AM

I ran into many of the same "password salt" questions a number of years ago when first trying to move user accounts between different DNN instances.

"Password salt" refers to a value that is added to a password before encryption. I.e., the password is "salted" with extra characters to make the resulting encrypted value harder to decrypt. The salt provides two notable security benefits: (1) the resulting encrypted value is longer so brute force password-guessing attacks will require many, many more passes before hitting the right combination of characters; (2) the pre-encrypted value will not match up against any "dictionary" word values so dictionary-based attacks are useless.

With regards to using a random salt for each user account versus the same salt value across all accounts: Random salts help in cases where the salt value for one account is discovered. If a single salt is used for all accounts then discovering the salt for one account means the other account passwords are at greater risk of decoding since (a) brute force attacks are much easier when not having to guess the salt, and (b) dictionary-based attacks become feasible.

Of course, if someone manages to gain access to the DNN admin and/or host accounts (you DID change those usernames from the defaults, didn't you?) the attacker can use a simple SQL query (via the SQL "host" menu option, the Reports module, an XMOD module, etc.) to grab a copy of all the accounts and salt values from the asp_membership table so random salts wouldn't matter so much...

Hopefully that explanation helps a little more than it confuses. Cheers!

By mamlin on Wednesday, October 06, 2010 at 5:25 PM

...I should have added: I've only crudely described one approach to the use of password salt. Some approaches don't attempt to keep the salt private. DNN's leveraging of aspnet_membership use of password salt *does* mean to keep the value private.

By mamlin on Wednesday, October 06, 2010 at 5:41 PM

Comments from the following blog entry: Run the SQL Script to Create and Register a User with DNN, located at: http://community.dynamics.com/product/crm/crmtechnical/b/marcellotonarelli/archive/2010/12/05/run-the-sql-script-to-create-and-register-a-user-with-dnn.aspx

By Marcello Tonarelli's Microsoft Dynamics CRM Blog on Sunday, December 05, 2010 at 2:57 AM

Comments from the following blog entry: Run the SQL Script to Create and Register a User with DNN, located at: http://community.dynamics.com/product/crm/crmtechnical/b/marcellotonarelli/archive/2010/12/05/run-the-sql-script-to-create-and-register-a-user-with-dnn.aspx

By Marcello Tonarelli's Microsoft Dynamics CRM Blog on Sunday, December 05, 2010 at 3:04 AM

Thanks for the great script. This made my job of migrating 700+ users to a new DNN portal.

I modified it a bit and put it in a script:
http://devmemoir.blogspot.com/2011/02/migrating-users-to-dotnetnuke.html

By Larry Eisenstein on Tuesday, February 15, 2011 at 10:18 AM

Thanks for the great code, it was exacly what i need. But i need one more help, am going to use this code in a form to create a user & assign a password to it. my question is how to assign the value of the password & password salt from text field?!

By Eman on Wednesday, February 23, 2011 at 1:18 PM

For versions 4.9 above, DNN not hard deleting users, rather just mark a Deleted bit.

By DNN Developers on Tuesday, March 15, 2011 at 2:49 PM

Thank for a great script. It saves me a lot of time.

By Duc Minh Nguyen on Thursday, March 24, 2011 at 4:33 AM

Excellent script - thanks! I'm using this to authenticate employees against customer eligibility records and create new users for the employees as they validate.

I do have one issue to solve - I've added some custom profile properties and need to populate these based on the DNN user account used to create the new users. This script doesn't add any records into the UserProfile table and I can seem to insert one manually:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserProfile_Users". The conflict occurred in database "DNN", table "dbo.Users", column 'UserID'.

By MattD on Thursday, April 07, 2011 at 8:58 AM

Follow-up to my comment, I must have been doing something in the wrong order in SQL. I have since been able to insert the records for the User profile data without issue.

Thanks again for a great script!

By MattD on Tuesday, April 26, 2011 at 5:28 PM

Great Post !!!
I want to know how to authenticate the same user using sql query/stored procedure.

By Sachin on Friday, August 26, 2011 at 8:35 AM

GREAT POST!

There's one minor oversight that I can see right away. Roles (rolenames) are specific to portals, so you need to make sure you're setting the RoleID for the RoleName from the right portal when you create the user...

--Now Give the user permissions to the RECISTERED Users group
INSERT INTO UserRoles (userId, roleId)
SELECT @dnnuserid,
roleId
FROM Roles
WHERE RoleName = 'Registered Users'
AND PortalID = @portalID

By Michael Larter on Friday, November 04, 2011 at 10:27 AM

I used this script to try to migrate users but I have found an issue in it. When you migrate the users, it does not create the ProfileProperties for properties like FirstName, LastName, email, etc.

The problem is DNN uses these ProfileProperties in it's search function. So, after you have migrated the users and try to search for them, you will not find them.

I'm sure there is a few extra statements you can add to fix this but this caught me by surprise.

By LarryE on Wednesday, April 11, 2012 at 10:38 AM

Name (required)

Email (required)

Website

CAPTCHA image
Enter the code shown above:

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Friend of RedGate

www.datasprings.com - DotNetNuke Modules ICG Hosting

Click here for advertising information.

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.