How can I set the default role for a new user using Windows Authentication using the SqlRoleProvider?

I have an application that uses Windows Authentication and SqlRoleProvider to authenticate users and manage roles respectively. It works great with my test users, which I added to the default database. The application requires users to log in (using their Windows credentials) and then be able to use this back-end application as the primary "user". If a user needs to be added to a high-level role, the administrator will be responsible for this after the first login.

With that said, how would I add the user to the default role on first login? Logically, I know that I will need to call Roles.IsUserInRole () and then add them if they are not; however, where would I do it? I am having trouble figuring out which event is being used in Global.asax.

thank

EDIT: To expand the scenario a bit, I am not using the full membership provider system due to the requirement to write new providers so that the connection string is stored outside of the web.config. I am not using any registration page or login page and let IIS integrated Windows validation handle the authentication aspects while my extended SqlRoleProvider manages user roles. The system works great for users, I have role settings with hardcoded tests. I'm just looking for a way to add new users (that would be IIS authenticated) to add directly to the default Users role. I seem to have found this; however, I am now looking at ways to prevent it from firing on every request for performance reasons.

+1


source to share


3 answers


I was able to find a solution after digging around and playing around a bit. I added the following code to my Global.asax file and it does what I hope it does.

protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
    if (!Roles.IsUserInRole(e.Identity.Name, "Users"))
    {
        Roles.AddUsersToRole(new string[] { e.Identity.Name }, "Users");
    }
}

      



I am concerned that this code is being run with every page request. Is there a better way to limit this? Should I just add this code to the landing page page_ event instead of Global.asax?

+1


source


I would add a default role to the user right after the user has been checked out.

Something like:



user = Membership.GetUser()
if (user != null)
{
  // default role 
  string[] defaultRoles = {"MyRole"};

  AddUsersToRoles(user, defaultRoles); 

}

      

0


source


Why not include it when registering or registering?

On login, handle this event and enable it. Check each time they log in.

0


source







All Articles