views:

390

answers:

3

I have an application that is using Windows Authentication and a SqlRoleProvider for user authentication and role management respectively. It is working fine with my test users that I have added to the database as defaults. The application requires users to login (using Windows credentials) and then be able to use this internal application as a basic "user". If the user needs to be added to a high level role, an admin would be responsible for this after the first log in.

With that said, how would I add a user to the default role when they first log in? Logically, I know that I would need to call Roles.IsUserInRole() and then add them if they are not; however, where would I do this? I'm having trouble locating which event in the Global.asax to use.

Thanks

EDIT: To expand the scenario a bit, I'm not using a full membership provider system due to requirements on writing new providers to allow the connection string to be stored outside of the web.config. I am not using any form of registration or login page and letting the Windows Integrated Authentication in IIS handle the authentication aspects while my enhanced SqlRoleProvider manages the user roles. The system is working fine for users that I have setup roles via hard coded tests. I am just looking for a way to add new users (who would be authenticated by IIS) to be immediately added to a default "Users" role. I think I found it; however, am now examining ways to make it not fire upon every request for performance reasons.

A: 

I would add the default role to the user directly after the user was fetched.

Something like such:

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

  AddUsersToRoles(user, defaultRoles); 

}
CheGueVerra
+1  A: 

I was able to locate the solution after digging and playing around a bit more. I added the following code to my Global.asax file and it is accomplishing what I am hoping for.

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

I'm concerned since this code fires with every page request. Is there a better way to limit when this occurs? Should I just add this code to the landing page's page_load event instead of the Global.asax?

JamesEggers
A: 

Why not put it when the login or register?

When the login, handle that event and put this in. Check everytime they login.

masfenix
Since I'm using Windows Authentication, the WindowsAuthentication_OnAuthenticate would be the Login event and would fire at every request based on the WindowsAuthenticationModule. I'm not using any login form nor an additional registration form at this time. I'm not using membership; only roles.
JamesEggers