ASP.Net RegisterUser-Template with role assignment

The .Net Framework provides the ability to secure its web applications through users and roles. This allows different parts of a web application are accessible or disabled for certain user roles.

In Visual Studio user roles are managed with the WebSite Administration Tool, which has a pretty significant disadvantage:
If you want to add more users in a live system, you would have to assign users to their roles with the WebSite Administration Tool afterwards. Since these mappings are stored in the user database, which is not always possible in a live systems, because the databases are locked for external access … at least they should be.

It would therefore be useful to assign new users to a role when they are registered. But that is not provided in the automatically created Register class.
This can be changed with a few simple steps:

First, you insert an element in the Register.aspx, in which the roles are written – in this case a DropDownList.
For readability, I have omitted the superfluous elements and marked the changes in color.

Here you can Download the Code of the Class.

<%@ Page Title="Registrieren" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
    CodeBehind="Register.aspx.cs" Inherits="WebApplication2.Account.Register" %> 
 
    <asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser"> 
        <LayoutTemplate> 
            <asp:PlaceHolder ID="wizardStepPlaceholder" runat="server"></asp:PlaceHolder> 
            <asp:PlaceHolder ID="navigationPlaceholder" runat="server"></asp:PlaceHolder> 
        </LayoutTemplate> 
        <WizardSteps> 
            <asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server"> 
                <ContentTemplate>
                    .
                    .
                    . 
                   <asp:ValidationSummary ID="RegisterUserValidationSummary" runat="server" CssClass="failureNotification"  
                         ValidationGroup="RegisterUserValidationGroup"/> 
                    <div class="accountInfo"> 
                        <fieldset class="register">
                            .
                            .
                            .
                            . 
                           <p>
                                <asp:Label id="RoleLabel" runat="server" Text="Rolle des Nutzers"></asp:Label>
                                <asp:DropDownList ID="AvailableRoles" runat="server" SelectionMode="Single" Text="Roles" ></asp:DropDownList>
                           </p>                             
                        </fieldset> 
                        <p class="submitButton"> 
                            <asp:Button ID="CreateUserButton" runat="server" CommandName="MoveNext" Text="Benutzer erstellen"  
                                 ValidationGroup="RegisterUserValidationGroup"/> 
                        </p> 
                    </div> 
                </ContentTemplate> 
                <CustomNavigationTemplate> 
                </CustomNavigationTemplate> 
            </asp:CreateUserWizardStep> 
        </WizardSteps> 
    </asp:CreateUserWizard> 
</asp:Content>

Then add in the Register.aspx.cs add the following lines to the the Page_Load function to fill the DropDownList:
(Note: in Mono following line resulted in a failure, so the roles are entered in the loop

    .
    .
    ddl.DataSource = roles;

In Microsoft .Net binding of a DropDownList to a string-array worked without problems.

protected void Page_Load(object sender, EventArgs e)
{
    RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];

    string[] roles = Roles.GetAllRoles ();

	
    DropDownList ddl = (DropDownList)RegisterUserWizardStep.ContentTemplateContainer.FindControl("AvailableRoles");
	rol.Items.Clear ();
	foreach (string val in roles)
		rol.Items.Add (val);
	rol.SelectedIndex = 0;
}

When the user is created, the CreateUserWizard triggers a OnCreatedUser event, which is assigned to the function RegisterUser_CreatedUser in the Register.aspx.
Now the user must be assigned to the selected role with the command Roles.AddUserToRole. The entries in the database are then generated automatically.

protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
    FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

    DropDownList ddl = (DropDownList)RegisterUserWizardStep.ContentTemplateContainer.FindControl("AvailableRoles");
    TextBox tb = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("UserName");

    Roles.AddUserToRole(tb.Text, rol.SelectedValue);

    string continueUrl = RegisterUser.ContinueDestinationPageUrl;
    if (String.IsNullOrEmpty(continueUrl))
    {
        continueUrl = "~/Default.aspx";
    }
    Response.Redirect(continueUrl);
}        

Schreibe einen Kommentar