views:

63

answers:

4

I've looked around and I can't find the concise steps that I need to take in order to implement forms authentication in my web site. I'm using C# 3.5 with an SQL Server backend.

I have a User table and UserRole table in my database.

I have 5 Directories in my app that contain aspx pages.

Admin
Common
UserRole1
UserRole2
Public

I want role based security on Admin, UserRole1 and UserRole2.

My web.config looks like so...

  <system.web>
    <authentication mode="Forms">
      <forms name=".Authentication" loginUrl="UI/Common/Login.aspx" protection="All" path="/" timeout="30" />
    </authentication>
  ...
  </sytem.web>

  <location path="UI/Admin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

  <location path="UI/UserRole1">
    <system.web>
      <authorization>
        <allow roles="UserRole1"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

  <location path="UI/UserRole2">
    <system.web>
      <authorization>
        <allow roles="UserRole2"/>
        <deny users="*"/> 
      </authorization>
    </system.web>
  </location>

I put a Login Control in my Login.aspx page and my Login.aspx.cs currently looks like so.

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if ((from u in db.Users where u.UserName == Login1.UserName select u).Count() == 1)
    {
        User user = (from u in db.Users where u.UserName == Login1.UserName select u).First();
        //custom Encryption class, returns true if password is correct
        if (Encryption.VerifyHash(Login1.Password, user.Salt, user.Hash))
        {
            string myRole = (from ur in user.UserRoles where ur.UserRoleID == user.UserRoleID select ur.Role).First();
            //???    
        }
        else
        {
            e.Authenticated = false;
        }
    }
    else
    {
        e.Authenticated = false;
    }
}

Annnnd I'm stuck, I don't know how to tell my application what my user's role is.

Please help me :)

Thanks!

Edit:

I changed my Authenticate event code to

        string role = (from ur in user.UserRoles where ur.UserRoleID == user.UserRoleID select ur.Role).First();
        if (!Roles.RoleExists(role))
            Roles.CreateRole(role);
        if (Roles.FindUsersInRole(role, user.UserName).Length == 0)
            Roles.AddUserToRole(user.UserName, role);
        e.Authenticated = true;
        string returnUrl = Request.QueryString["ReturnUrl"];
        if (returnUrl == null) returnUrl = "/";
        Response.Redirect(returnUrl);

However I keep getting kicked back to the login screen.

After login is pressed Fiddler capture looks like
302 /Web/UI/Common/Login.aspx?ReturnUrl=%2fWeb%2fUI%2fAdmin%2fDefault.aspx
302 /Web/UI/Admin/Default.aspx
200 /Web/UI/Common/Login.aspx?ReturnUrl=%2fWeb%2fUI%2fAdmin%2fDefault.aspx

Edit 2:

I think I got the authentication up and running but I randomly get connection socket pipe errors.

My authentication looks like this:

        FormsAuthentication.Initialize();
    if (!Roles.RoleExists(role))
        Roles.CreateRole(role);
    if (Roles.FindUsersInRole(role, user.UserName).Length == 0)
        Roles.AddUserToRole(user.UserName, role);
    e.Authenticated = true;
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
         user.UserName,
         DateTime.Now,
         DateTime.Now.AddMinutes(30), // value of time out property
         true, // Value of IsPersistent property
         string.Empty,
         FormsAuthentication.FormsCookiePath);
    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    if (ticket.IsPersistent) authCookie.Expires = ticket.Expiration;
    authCookie.Secure = false; //set to true when https is enabled
    Response.Cookies.Add(authCookie);

    FormsAuthentication.RedirectFromLoginPage(user.UserName, true);
+1  A: 

You can use the Roles class methods, like so:

Roles.AddUserToRole(string userName, string roleName);
Roles.AddUserToRoles(string userName, string[] roleNames);
Roles.AddUsersToRole(string[] userNames, string roleName);
Roles.AddUsersToRoles(string[] userNames, string[] roleNames;

Make sure you are using System.Web.Security.

Matthew Jones
Hmm, I keep on getting kicked back to the login screen.
Biff MaGriff
@Biff you could try using the LoggedIn event as opposed to the Authenticate event.
Matthew Jones
I think my problem is that I need to persist the user somehow.
Biff MaGriff
A: 

Sorry, see the other answer, I forgot I was looking at one of our own methods that does this :)

CubanX
A: 

I think what you are missing is a Membership Provider. You can either use the default membership provider or add a custom one (that will allow you to do your own validation and role assignments). Take a look at this article from 4 guys. Either way you should be able to plug a membership provider into your system and use the login controls you already have to maintain authentication across your site.

Matt
A: 

Ok I found a solution. http://www.xoc.net/works/tips/forms-authentication.asp

whew

Biff MaGriff