Extending Identity – Adding Roles at User Registration

Depending on the application there may be times that it is desirable or required to add a user to a role immediately when they register. Other times you may want to add users to various roles depending on what privileges you want them to have. This is very easily accomplished in the Register method of the AccountController. This is the third post in a 3 part series on extending the ASP.NET Identity Framework.

If you desire every user to be placed into a specific role immediately when they register (without an administrator needing to do it manually) you can simply add the following code to the HttpPost Register method of the AccountController.

if (result.Succeeded)

{

await SendEmailConfirmationTokenAsync(model.Email, "Please Confirm you Email for Domain.com");

UserManager.AddToRole(user.Id, "Members");

return View("EmailNotConfirmed");

}

This will place every newly registered user into the “Members” role. At times however you may want to place users into special roles based on various factors. In this case I typically give those users a special passcode that they enter when they register. I will add an additional passcode field to the Register form and the Register ViewModel . When a user enters a the passcode I will check for the passcode and assign the role that correlates with the provided passcode as follows.

if (result.Succeeded)

{

await SendEmailConfirmationTokenAsync(model.Email, "Please Confirm you Email for domain.com");

if (model.Passcode == "MyPrecious")

{

UserManager.AddToRole(user.Id, "LordOfTheRingFans");

}

if (model.Passcode == "Inconceivable!")

{

UserManager.AddToRole(user.Id, "PrincessBrideFans");

}

return View("EmailNotConfirmed");

}

The above code will add the user to the specified role based off the passcode entered when they registered.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s