Click here to Skip to main content
Click here to Skip to main content

Role-based Security with Forms Authentication

By , 26 Jul 2009
 

Introduction

Forms Authentication in ASP.NET can be a powerful feature. With very little code and effort, you can have a simple authentication system that is platform-agnostic. If your needs are more complex, however, and require more efficient controls over assets, you need the flexibility of groups. Windows Authentication gives you this flexibility, but it is not compatible with anything but Internet Explorer since it uses NTLM, Microsoft's proprietary authentication system. Now you must choose how to manage your assets: provide multiple login pages / areas and force users to register for each, or assign groups to users and limit access to pages / areas to particular groups. Obviously, you must choose the latter.

Role-based security in Forms Authentication is one thing Microsoft left out in this round for .NET, but they didn't leave you high-and-dry. The mechanisms are there, they're just not intuitive to code. This tutorial will cover the basics of Forms Authentication, how to adapt it to make use of role-based security, and how to implement role-based security on your site with single sign-ons.

Updated: With ASP.NET 2.0, Microsoft introduced built-in support for role membership. If you're using ASP.NET 2.0 or newer it's recommended you read Managing Authorization using Roles on MSDN. You can use an abstract data provider or create your own. This article was written for ASP.NET 1.0 but will also work for 1.1.

Prerequisites

This tutorial is all about role-based security with Forms Authentication, a detail that Microsoft left out of .NET for this round. This tutorial will use different techniques that are almost completely incompatible with the standard Forms Authentication, save the setup, which we'll cover shortly.

To follow along in this tutorial, you'll need to create a database, a web application, several secured directories, and a few ASP.NET Web Forms (pages).

Creating the Database

We will create a simple database containing a flat table for this tutorial. Using the <credentials/> section of the Web.config file is not an option because no mechanism for roles is supported. For the purposes of brevity, the table we create will be very simple. You're welcome to expand the database to make use of relations (what I would do and actual do use on several sites) for roles. The implementation does start to get a little messy depending on how you do it, and the details are left up to you. This is merely a tutorial about developing role-based security.

So, choose what database management system you want to use (DBMS). For this tutorial, we'll choose the Microsoft Data Engine (MSDE) available with Visual Studio .NET, Office XP Developer, and several other products. We'll add one database, say web, and then add one table, say users. To the users table, we'll add three fields: username, password, and roles. Set the username field to the primary key (since it'll be used for look-ups and needs to be unique), and optionally create an index on the username and password fields together. If you're using Table-creation SQL Scripts, your script might look something like this:

CREATE 
DATABASE web

CREATE TABLE users
(
    username nvarchar(64) CONSTRAINT users_PK PRIMARY KEY,
    password nvarchar(128),
    roles nvarchar(64)
)

CREATE INDEX credentials ON users
(
    username,
    password
)

Feel free to add some credentials to your database, picking a few roles you think are good group names for your site, such as "Administrator", "Manager", and "User". For this tutorial, put them in comma-delimited format in the "roles" field like the following, pipe-delimited (|) table:

username|password|roles
"hstewart"|"codeproject"|"Administrator,User"
"joe"|"schmoe"|"User"

Take note to make the roles case-sensitive. Now let's move on to creating our pages necessary for role-based Forms Authentication.

Creating the Login Pages

If you haven't already done so, create a new Web Application, or attach to an existing Web Application, such as your web server's document root, "/". For this tutorial, we'll assume the Web Application resides in "/", though the procedure for any Web Application is the same.

Before we create any pages or setup our Web.config file, you must understand one thing: the login.aspx (or whatever you call your login page) must be public. If it isn't, your users will not be able to log-in, and could be stuck in an infinite loop of redirects, though I've not tested this and don't care to. So, this tutorial will assume that login.aspx is in "/", while we have two secured sub-directories, users and administrators.

First, we must create a Forms Authentication login system that supports roles. Because Microsoft did not provide for this easily, we will have to take over the process of creating the authentication ticket ourselves! Don't worry, it's not as hard as it sounds. A few pieces of information are needed, and the cookie has to be stored under the right name - the name matching the configured name for Forms Authentication in your root Web.config file. If these names don't match, ASP.NET won't find the Authentication Ticket for the Web Application and will force a redirect to the login page. For simplicity, we will put the code directly into the ASP.NET Web Form, which is easier to code for DevHood and should look something like the following:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
    <title>Login</title>
</head>
<script runat="server">
// If you're using code-behind, make sure you change "private" to
// "protected" since the .aspx page inherits from the .aspx.cs
// file's class
private void btnLogin_Click(Object sender, EventArgs e)
{
    // Initialize FormsAuthentication, for what it's worth
    FormsAuthentication.Initialize();

    // Create our connection and command objects
    SqlConnection conn =
     new SqlConnection("Data Source=localhost;Initial Catalog=web;");
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT roles FROM web WHERE username=@username " +
     "AND password=@password";

    // Fill our parameters
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
Username.Value;
    cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value =
     FormsAuthentication.HashPasswordForStoringInConfigFile(
        Password.Value, "md5"); // Or "sha1"

    // Execute the command
    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.Read())
    {
     // Create a new ticket used for authentication
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, // Ticket version
        Username.Value, // Username associated with ticket
        DateTime.Now, // Date/time issued
        DateTime.Now.AddMinutes(30), // Date/time to expire
        true, // "true" for a persistent user cookie
        reader.GetString(0), // User-data, in this case the roles
        FormsAuthentication.FormsCookiePath);// Path cookie valid for

     // Encrypt the cookie using the machine key for secure transport
     string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, // Name of auth cookie
        hash); // Hashed ticket

     // Set the cookie's expiration time to the tickets expiration time
     if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

     // Add the cookie to the list for outgoing response
     Response.Cookies.Add(cookie);

     // Redirect to requested URL, or homepage if no previous page
     // requested
     string returnUrl = Request.QueryString["ReturnUrl"];
     if (returnUrl == null) returnUrl = "/";

     // Don't call FormsAuthentication.RedirectFromLoginPage since it
     // could
     // replace the authentication ticket (cookie) we just added
     Response.Redirect(returnUrl);
    }
    else
    {
     // Never tell the user if just the username is password is incorrect.
     // That just gives them a place to start, once they've found one or
     // the other is correct!
     ErrorLabel = "Username / password incorrect. Please try again.";
     ErrorLabel.Visible = true;
    }

    reader.Close();
    conn.Close();
}
</script>
<body>
    <p>Username: <input id="Username" runat="server"
type="text"/><br />
    Password: <input id="Password" runat="server" type="password"/><br
/>
    <asp:Button id="btnLogin" runat="server" OnClick="btnLogin_Click"
     Text="Login"/>
    <asp:Label id="ErrorLabel" runat="Server" ForeColor="Red"
     Visible="false"/></p>
</body>
</html>

You'll notice above that we do one other thing with our passwords: we hash them. Hashing is a one-way algorithm that makes a unique array of characters. Even changing one letter from upper-case to lower-case in your password would generate a completely different hash. We'll store the passwords in the database as hashes, too, since this is safer. In a production environment, you'd also want to consider having a question and response challenge that a user could use to reset the password. Since a hash is one-way, you won't be able to retrieve the password. If a site is able to give your old password to you, I'd consider steering clear of them unless you were prompted for a client SSL certificate along the way for encrypting your passphrase and decrypting it for later use, though it should still be hashed.

Note: without using HTTP over SSL (HTTPS), your password will still be sent in plain-text across the network. Hashing the password on the server only keeps the stored password secured. For information about SSL and acquiring a site or domain certificate, see http://www.versign.com or http://www.thawte.com.

If you don't want to store hashed passwords in the database, change the line that reads FormsAuthentication.HAshPasswordForStoringInConfigFile(Password.Value, "md5") to just Password.Value.

Next, we'll need to modify the Global.asax file. If your Web Application doesn't have one already, right-click on the Web Application, select "Add->Add New Item...->Global Application Class". In either the Global.asax or Global.asax.cs (or Global.asax.vb, if you're using VB.NET), find the event handler called Application_AuthenticateRequest. Make sure it imports / uses the System.Security.Principal namespace and modify it like so:

protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
  if (HttpContext.Current.User != null)
  {
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
     if (HttpContext.Current.User.Identity is FormsIdentity)
     {
        FormsIdentity id =
            (FormsIdentity)HttpContext.Current.User.Identity;
        FormsAuthenticationTicket ticket = id.Ticket;

        // Get the stored user-data, in this case, our roles
        string userData = ticket.UserData;
        string[] roles = userData.Split(',');
        HttpContext.Current.User = new GenericPrincipal(id, roles);
     }
    }
  }
}

What's happening above is that since our principal (credentials - which are your username and roles) is not stored plainly as part of our cookie (nor should it, since a user could modify their list of role-memberships), it needs to be generated for each request. The FormsAuthenticationTicket is actually encrypted as part of a cookie using your machine key (usually configured in machine.config) and the FormsAuthentication module decrypts the tick as part of the user's identity. If you search long and hard enough on Microsoft MSDN web site, you'll find this documentation buried. We use the UserData to obtain the list of roles and generate a new principal. Once the principal is created, we add it to the current context for the user, which the receiving page can use to retrieve credentials and role-memberships.

Securing Directories with Role-based Forms Authentication

To make the role-based authentication work for Forms Authentication, make sure you have a Web.config file in your Web Application root. For the authentication setup, this particular Web.config file must be in your Web Application's document root. You can override the <authorization/> in Web.config files for sub-directories.

To begin, make sure your Web.config file has at least the following:

<configuration>
    <system.web>
        <authentication    mode="Forms">
            <forms name="MYWEBAPP.ASPXAUTH"
                loginUrl="login.aspx"
                protection="All"
                path="/"/>
        </authentication>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</configuration>

The FormsAuthentication name (MYWEBAPP.ASPXAUTH) above it arbitrary, although the name there and the name in the HttpCookie we created to hold the hashed FormsAuthenticationTicket must match, for even though we are overriding the ticket creation, ASP.NET still handles the authorization automatically from the Web.config file.

To control authorization (access by a particular user or group), we can either 1) add some more elements to the Web.config file from above, or 2) create a separate Web.config file in the directory to be secure. While, I prefer the second, I will show the first method:

<configuration>
    <system.web>
        <authentication mode="Forms">
            <forms name="MYWEBAPP.ASPXAUTH"
                loginUrl="login.aspx"
                protection="All"
                path="/"/>
        </authentication>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
    <location path="administrators">
        <system.web>
            <authorization>
                <!-- Order and case are important below -->
                <allow roles="Administrator"/>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="users">
        <system.web>
            <authorization>
                <!-- Order and case are important below -->
                <allow roles="User"/>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
</configuration>

The Web Application always creates relative paths from the paths entered here (even for login.aspx), using it's root directory as the starting point. To avoid confusion with that condition and to make directories more modular (being able to move them around without changing a bunch of files), I choose to put a separate Web.config file in each secure sub-directory, which is simply the <authorization/> section like so:

<configuration>
    <system.web>
        <authorization>
            <!-- Order and case are important below -->
            <allow roles="Administrator"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</configuration>

Notice, too, that the role(s) is/are case-sensitive. If you want to allow or deny access to more than one role, delimit them by commas.

That's it! Your site is setup for role-based security. If you use code-behind, compile your application first. Then try to access a secure directory, such as /administrators, and you'll get redirected to the login page. If login was successful, you're in, unless your role prohibits it, such as the /administrators area. This is hard for the login.aspx page to determine, so I'd recommend a Session variable to store the login attempts and after so many times, return an explicit "Denied" statement. There is another way, however, which is discussed below.

Conditionally Showing Controls with Role-based Forms Authentication

Sometimes it's better to show / hide content based on roles when you don't want to duplicate a bunch of pages for various roles (user groups). Such examples would be a portal site, where free- and membership-based accounts exist and membership-based accounts can access premium content. Another example would be a news page that would display an "Add" button for adding news links if the current user is in the "Administrator" role. This section describes how write for such scenarios.

The IPrincipal interface, which the GenericPrincipal class we used above implements, has a method called IsInRole(), which takes a string designating the role to check for. So, if we only want to display content if the currently logged-on user is in the "Administrator" role, our page would look something like this:

<html>
<head>
  <title>Welcome</title>
  <script runat="server">
  protected void Page_Load(Object sender, EventArgs e)
  {
   if (User.IsInRole("Administrator"))
    AdminLink.Visible = true;
  }
  </script>
</head>
<body>
  <h2>Welcome</h2>
  <p>Welcome, anonymous user, to our web site.</p>
  <asp:HyperLink id="AdminLink" runat="server"
   Text="Administrators, click here." NavigateUrl="administrators/"/>
</body>
</html>

Now the link to the Administrators area of the web site will only show up if the current user is logged in and is in the "Administrator" role. If this is a public page, you should provide a link to the login page, optionally setting the QueryString variable called ReturnUrl to the path on the server you want the user to return to upon successful authentication.

Summary

This tutorial was created to help you understand the important of role-based security, as well as implement role-based security on your web site with ASP.NET. It's not a hard mechanism to implement, but it does require some know-how of what principals are, how credentials are authenticated, and how users / roles are authorized. I hope you have found this tutorial helpful and interesting, and that it leads you to implement role-based Forms Authentication on your current or upcoming site!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Heath Stewart
Program Manager Microsoft
United States United States
Member
Heath Stewart is a happily married software engineer originally from the Midwest and a graduate of Iowa State University. Heath start programming early in life and enjoys continuous research and development in new languages, frameworks, and platforms. Fluent in many different programming languages, he has developed many large-scale software solutions for companies in different areas, such as Internet filtering, intrusion detection systems, production management systems, and web applications for various purposes. He also enjoys photography.
 
Currently, Heath is a Program Manager in the Visual Studio Professional Deployment Experience (VSPro DEX) team at Microsoft. Previous to his employment, he was a Microsoft MVP for Visual C#.
 
He is also a CodeProject protector and is happy to help the development community.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionImplementation in Vb.Net and SQL ServermemberMember 100250052 May '13 - 8:59 
The article has allowed me to make the following implementation in Vb.Net:
Regards, Ricardo Castillo Téllez, Nicaragua
 
1) wfLogin.vb
 
Partial Class wfLogin
    Inherits System.Web.UI.Page
    Dim stUserName As String
    Dim stUserPwd As String
    Dim stKeyMessage As String
    Dim inNoOfLoginAttempt As Int32
    Dim blLocked As Boolean
 
    Protected Sub btLogIn_Click(sender As Object, e As System.EventArgs) Handles btLogIn.Click
        Try
 
            stUserName = txUser_Name.Text
            stUserPwd = txUser_Pwd.Text
            inNoOfLoginAttempt = Convert.ToInt32(Session("NoOfLoginAttempt"))
 
            'Verificación de bloqueo
            If inNoOfLoginAttempt >= 3 Then
 
                Session("NoOfLoginAttempt") = 0
                inNoOfLoginAttempt = 0
 
                blLocked = clUser.fnLockUser(stUserName)
                If blLocked = True Then
                    clMessage.fnMessage(Me, "Tu cuenta ha sido bloqueada")
                    Exit Sub
                End If
 
            End If
 
            'Inicializar FormsAuthentication
            FormsAuthentication.Initialize()
 
            'Instanciar objeto Usuario
            obGblUser = clUser.fnSelectUser_Auth(stUserName, stUserPwd)
            If Not obGblUser Is Nothing Then
 
                'Crear un nuevo ticket usado para autenticación
                '1 Versión del ticket / Nombre sde usuario asociado al ticket / Fecha-hora emisión / Fecha-hora expiración
                'True cookie de usuario persistente / Nombre del rol (tipo de usuario) / Ruta para validar la cookie
                Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1,
                                                                                        obGblUser.p_User_Name,
                                                                                        DateTime.Now,
                                                                                        DateTime.Now.AddMinutes(30),
                                                                                        True,
                                                                                        obGblUser.p_User_Type_Name,
                                                                                        FormsAuthentication.FormsCookiePath)
 
                'Encriptación de la cookie utilizando la clave del equipo para el transporte seguro 
                'FormsCookieName: Nombre de la cookie de autenticación / hash: ticket encriptado
                Dim hash As String = FormsAuthentication.Encrypt(ticket)
                Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, hash)
 
                'Establecer el tiempo de caducidad de la cookie para su expiración
                If (ticket.IsPersistent) Then
                    cookie.Expires = ticket.Expiration
                End If
 
                'Añadir la cookie a la lista de respuesta de salida
                Response.Cookies.Add(cookie)
 
                'Reenviar a URL solicitada, o página de inicio si no se solicita la página anterior
                Dim returnUrl As String = Request.QueryString("ReturnUrl")
                If (returnUrl Is Nothing) Then
                    returnUrl = "/"
                End If
 
                'No llame FormsAuthentication.RedirectFromLoginPage 
                'ya que podría reemplazar el vale de autenticación (cookie) que acaba de agregar
                Response.Redirect(returnUrl)
 
            Else
 
                'Contador de intentos fallidos
                inNoOfLoginAttempt = inNoOfLoginAttempt + 1
                Session("NoOfLoginAttempt") = inNoOfLoginAttempt
 
                'Nunca le diga al usuario si el nombre de usuario y/o la contraseña es incorrecta. 
                'Eso les da pauta a encontrar las credenciales correctas
                clMessage.fnMessage(Me, "Credenciales no válidas, verifique que el nombre de usuario y clave de acceso son correctas, o bien que el usuario no se encuentre bloqueado")
            End If
 
        Catch ex As Exception
            clMessage.fnMessage(Me, "Error: " + ex.Message)
        End Try
 
    End Sub
 
End Class
 
2) clUser Class Business
 
Public Class clUser
 
    Public Property p_User_Name As String
    Public Property p_User_Descr As String
    Public Property p_User_Full_Name As String
    Public Property p_User_Type_Id As Integer
    Public Property p_User_Type_Name As String
    Public Property p_User_Email As String
 
    Public Shared Function fnSelectUser_Auth(ByVal stUserName As String, ByVal stUserPassword As String) As clUser
        Return clUserBD.fnSelectUser_Auth(stUserName, stUserPassword)
    End Function
    Public Shared Function fnLockUser(ByVal stUserName As String) As Boolean
        Return clUserBD.fnLockUser(stUserName)
    End Function
End Class
 
3) clUser Class Data
 
Public Class clUserBD
 
    Public Shared Function fnSelectUser_Auth(ByVal stUserName As String, ByVal stUserPassword As String) As clUser
 
        Dim cnConnection As SqlConnection = clSqlConnection.fnGetConexion
        Dim cmCommand As New SqlCommand
        Dim drReader As SqlDataReader
        Dim objc As clUser
 
        cmCommand.CommandType = CommandType.StoredProcedure
        cmCommand.CommandText = "SP_SE_USER_AUTH"
        cmCommand.Connection = cnConnection
 
        clSqlConnection.fnAddParameter(cmCommand, "USER_NAME", stUserName, SqlDbType.VarChar)
        clSqlConnection.fnAddParameter(cmCommand, "USER_PWD", stUserPassword, SqlDbType.VarChar)
 
        cnConnection.Open()
        drReader = cmCommand.ExecuteReader(CommandBehavior.CloseConnection)
 
        If drReader.Read Then
            objc = New clUser
            With objc
                .p_User_Name = drReader("USER_NAME")
                .p_User_Full_Name = drReader("USER_FULL_NAME")
                .p_User_Type_Id = drReader("USER_TYPE_ID") 'Role ID
                .p_User_Email = drReader("USER_EMAIL")
                .p_User_Descr = drReader("USER_DESCR")
                .p_User_Type_Name = drReader("USER_TYPE_NAME") 'Role Name
            End With
            Return objc
        Else
            Return Nothing
        End If
 
    End Function
 
    Public Shared Function fnLockUser(ByVal stUserName As String) As Boolean
 
        Dim cnConnection As SqlConnection = clSqlConnection.fnGetConexion
        Dim cmCommand As New SqlCommand
        Dim inRetVal As Integer = 0
 
        cmCommand.CommandType = CommandType.StoredProcedure
        cmCommand.CommandText = "SP_UP_USER_LOCK"
        cmCommand.Connection = cnConnection
        clSqlConnection.fnAddParameter(cmCommand, "USER_NAME", stUserName, SqlDbType.VarChar)
 
        Try
            cnConnection.Open()
            inRetVal = cmCommand.ExecuteNonQuery()
            If inRetVal > 0 Then
                Return True
            Else
                Return False
            End If
 
        Catch ex As Exception
            Throw (ex)
        Finally
            cnConnection.Close()
        End Try
 
    End Function
 
End Class
 
4) Connection Class
 
Public Class clSqlConnection
 
    Public Shared Function fnGetConexion() As SqlConnection
        Dim stConnection As String
        Dim SqlConnection As SqlConnection
        stConnection = ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString
        SqlConnection = New SqlConnection(stConnection)
        Return SqlConnection
    End Function
 
    Public Shared Sub fnAddParameter( _
                                ByVal sqlCommand As SqlCommand, _
                                ByVal stParameterName As String, _
                                ByVal stParameterValue As String, _
                                ByVal SqlDbType As SqlDbType)
        Dim SqlParameter As New SqlParameter
        With SqlParameter
            .ParameterName = stParameterName
            .Value = stParameterValue
            .SqlDbType = SqlDbType
        End With
        sqlCommand.Parameters.Add(SqlParameter)
    End Sub
 
End Class
 
5) In Data Base SQL
 
Table USERS
USER_NAME|USER_FULL_NAME|USER_TYPE_ID|USER_EMAIL|USER_DESCR|USER_PWD (varbinary)|USER_STATUS_ID	
 
CREATE SYMMETRIC KEY MY_SYM_KEY
	WITH ALGORITHM = TRIPLE_DES
	ENCRYPTION BY PASSWORD ='$$$$$-/'

CREATE PROCEDURE SP_UP_USER_ACCT_LOCK
    @USER_NAME VARCHAR(16)
AS
BEGIN
    --3 = LOCKED
    IF EXISTS(SELECT 1 FROM USERS WHERE USER_NAME = @USER_NAME)
        UPDATE USERS SET USER_STATUS_ID = 3 WHERE USER_NAME = @USER_NAME
END
 
CREATE PROCEDURE [dbo].[SP_SE_USER_AUTH]
	@USER_NAME VARCHAR(16),
	@USER_PWD  VARCHAR(16)
AS
	DECLARE
	@CLEARTEXT		NVARCHAR(MAX),
	@PASSWORD		VARBINARY(MAX)
BEGIN
	
	IF EXISTS(SELECT 1 FROM USERS WHERE USER_NAME = @USER_NAME)
	BEGIN
	
		/*OBTENER CLAVE DE ACCESO ENCRIPTADA Y TIPO DE USUARIO*/
		SELECT @PASSWORD = USER_PWD
		FROM USERS 
		WHERE USER_NAME = @USER_NAME	
 
		/*DESENCRIPTA DE CLAVE DE ACCESO*/	
		EXEC SP_OPEN_SYMMETRIC_KEY
		SELECT @CLEARTEXT =	 [dbo].[fn_DecryptByKey](@PASSWORD)
 
		/*SI LA CLAVE COINCIDE RETORNAR TIPO DE USUARIO*/
		IF @USER_PWD = @CLEARTEXT
			SELECT	A.USER_NAME,
					A.USER_FULL_NAME,
					A.USER_TYPE_ID,
					A.USER_EMAIL,
					ISNULL(A.USER_DESCR,'') AS USER_DESCR,
					B.USER_TYPE_NAME --ROLE
			FROM USERS A 
			INNER JOIN USER_TYPE B ON B.USER_TYPE_ID = A.USER_TYPE_ID
			WHERE	A.USER_NAME = @USER_NAME AND 
					A.USER_STATUS_ID = 1
 
	END	
 
END
 
CREATE PROCEDURE [dbo].[SP_OPEN_SYMMETRIC_KEY]
AS
BEGIN
    SET NOCOUNT ON;
    OPEN SYMMETRIC KEY MY_SYM_KEY
    DECRYPTION BY PASSWORD = '$$$$$-/'
END
 
CREATE FUNCTION [dbo].[fn_DecryptByKey] 
( 
	@value VARBINARY(MAX) 
)
RETURNS NVARCHAR(MAX)
AS 
BEGIN
 
    DECLARE @DecryptedValue NVARCHAR(MAX)
 
    SELECT @DecryptedValue = CAST(DECRYPTBYKEY(@value) AS NVARCHAR(MAX))
   
    RETURN ( @DecryptedValue )
   
END
 
6) Web.Config
 
<configuration>
	
  <system.web>
		
    <compilation debug="true" targetFramework="4.0"/>
    <pages theme="BlueTheme"></pages>
 
    <authentication mode="Forms">
      
      <forms name="XXXX_MyAuth" 
             loginUrl="wfLogin.aspx" 
             protection="All" 
             timeout="10" 
             path="/">        
      </forms>
      
    </authentication>
 
    <authorization>
      <allow users="*"/>
    </authorization>
   
  </system.web>
 
  <location path="Administrator">
    <system.web>
      <authorization>
        <!-- Order and case are important below -->
        <allow roles="Administrator"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  
  <location path="Users">
    <system.web>
      <authorization>
        <!-- Order and case are important below -->
        <allow roles="Users"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  
	<connectionStrings>
		<add name="myConnectionString" connectionString="Data Source=?;Initial Catalog=?;Persist Security Info=True;User ID=?;Password=?" providerName="System.Data.SqlClient"/>
	</connectionStrings>
 
</configuration>
 
7) Global.asax
 
    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        
        If Not (Context.User Is Nothing) Then
            If (HttpContext.Current.User.Identity.IsAuthenticated) Then
                Dim id As FormsIdentity = HttpContext.Current.User.Identity
                Dim ticket As FormsAuthenticationTicket = id.Ticket
                Dim UserData As String = ticket.UserData
                Dim roles() As String = UserData.Split(",")
                HttpContext.Current.User = New System.Security.Principal.GenericPrincipal(id, roles)  
            End If
        End If
 
    End Sub
 
8) Function Message
 
    Private Shared Sub fnSwhowMessage(ByVal frmFormName As System.Web.UI.Page, ByVal sMessage As String)
        'Declara el script para mostrar el mensaje
        sMessage = sMessage.Replace("'", "`").Replace(vbCrLf, "\n")
        Dim sScript As String = "alert('" & sMessage & "');"
        'Muestra el mensaje
        frmFormName.Page.ClientScript.RegisterClientScriptBlock(frmFormName.GetType(), "sScript", sScript, True)
    End Sub

GeneralMy vote of 5memberchandrasekharl8 Nov '12 - 21:31 
Great article on Role-based security
QuestionRole-based Security with Forms AuthenticationmemberMember 931980528 Oct '12 - 4:50 
Sir thanx a lot ,really really helpful, thats what i was searching. Shukriya...Smile | :)
GeneralDoesnt Seem to Work for Imagesmembermanofatlantic6 Aug '12 - 10:38 
This doesnt seem to work if I try to access images in a protected folder.
I get looged out and redirected back to the login page. When I login it gets me back to the login page again.
 
However it seem to work with aspx pages.
 
I am on IIS 7.
 
Please suggest.
QuestionQuestion regarding form based authenticationmembervishalpatwardhan12 Jul '12 - 4:29 
Hi, Just want to ask that if we are using FormAuthentication cookie then we don't need to use Aspnetdb as we can create our custom table as mentioned but if we don't want to use custom table for authentication and authorization then we should use sql membership using aspnet_regsql right ?
GeneralMy vote of 4membervicvis28 Jun '12 - 3:10 
Good for understanding basics
Questionadministrators page is still not visiblemembervicvis28 Jun '12 - 3:09 
Hi Sir,
 
with due respect...i tried to replicate your code given.
Everything worked out expected.Even the cookies was decrypted and role was dereived as "Administrators" but still when global.aspx was called after authentication,again it got redirected to the Login page.
 
I may be mising someething critical....
 
Shall i provide my entire code?
Please help !!
Generalquite good article for understanding of form authenticaion.membersrichavan2 Jun '12 - 18:06 
quite good article for understanding of form authenticaion.
Srikrushna

Generalquite good article for understanding of form authenticaionmembersrichavan2 Jun '12 - 18:05 
quite good article for understanding of form authenticaion
Srikrushna

GeneralMy vote of 5membermanoj kumar choubey28 Feb '12 - 18:28 
Nice
GeneralMy vote of 5memberishan58827 Nov '11 - 22:48 
very useful....thanks a lot..
GeneralMy vote of 3membertony vo manh cuong21 Aug '11 - 16:11 
i dont think good way to put user account and admin in sigle page.
GeneralMy vote of 5memberujjwal meshram1 Apr '11 - 2:51 
My 4 day search ends here. It does not require Membership/role provider.
Thanks
GeneralMy vote of 5memberMonjurul Habib28 Feb '11 - 9:47 
nice one.
GeneralMenu options filteredmemberptoloza15 Feb '11 - 3:24 
To filter menu options just add the following code to web.config file:
 
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider " siteMapFile="Web.sitemap"
securityTrimmingEnabled="true"/>
</providers>
</siteMap>
GeneralMy vote of 4memberptoloza15 Feb '11 - 3:18 
it's very easy and claer
GeneralMy vote of 5memberdas raj29 Oct '10 - 1:32 
excelent
GeneralUsername / password incorrect. Please try again.memberamina8912 Jul '10 - 6:07 
Hi, Thanks for article
I work with visual studio2008 and sqlserver2008, I changed the database connection and my password and login are correct but i have this message Username / password incorrect. Please try again.
Thank you.
GeneralRe: Username / password incorrect. Please try again.protectorHeath Stewart19 Jul '10 - 2:18 
If you copied the code as is, the SqlCommand is probably coming back with an error or no records returned. You'll have to debug the application.
 
However, since you're using VS2008 (.NET 3.5) I recommend using built-in authentication controls in ASP.NET as mentioned at the top of my article. They are more robust and require less coding and maintenance. Changing connections should also be a lot easier since connections can be more easily entered and referenced in your ASP.NET application configuration files (web.config).
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Program Manager II
Visual Studio Professional Deployment Experience
Microsoft
 
[My Articles] [My Blog]

GeneralMy vote of 5memberJonePolvora11 Jul '10 - 22:38 
Very very nice!
GeneralGreat ArticlememberGaurav Dudeja India8 Apr '10 - 20:38 
Great Article
Gaurav Dudeja
http://www.gdinfotechindia.com

Dont be afraid of changing your life to better !

GeneralThanksmemberAnuj Tripathi7 Jan '10 - 4:51 
Hi Heath,
 
This article is really helpful as well as simpler to understand & implement.
Can you please provide the same type of article for passport authentication & autherzation.
Thanks in advance !
GeneralRe: ThanksprotectorHeath Stewart30 Jan '10 - 8:49 
There's already some good articles about this at http://msdn.microsoft.com/en-us/library/f8e50t0f(VS.71).aspx[^], http://msdn.microsoft.com/en-us/library/f8e50t0f(VS.80).aspx[^], and http://msdn.microsoft.com/en-us/library/aa530793.aspx[^]. The latter is for 2.0 and newer, but I highly recommend ASP.NET 2.0 or newer over any 1.x solution.
 
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Software Design Engineer
Developer Division Customer Product-lifecycle Experience
Microsoft
 
[My Articles] [My Blog]

QuestionApplication_AuthenticateRequest, unable to test project on Visual Studio 2010 Beta 2memberjohn_17267 Dec '09 - 12:57 
Please note that I have been unable to get your sample working on VS 2010 beta 2. In particular, when I create/add the Global.asax file, I cannot see there any method called Application_AuthenticateRequest(...), or anywhere else in the solution for that matter. Do you have any suggestions? The Application_AuthenticateRequest is generated by VS, is it not?
 
TIA.
GeneralCS0029 Error. How can I fix it? I am really a newbie on this. Please helpmembereggy16823 Jul '09 - 10:50 
Hi,
I got an error message, CS0029 cannot implicitly convert type "string" to system.web.ui.webcontrols.labels after I copy and paste all the code into a new asp.net page. I just don't know how to fix it and now I am stuck on it. can anyone help me to solve it since I am just started learning how to write asp.net.
Thank you very much.
GeneralRe: CS0029 Error. How can I fix it? I am really a newbie on this. Please helpprotectorHeath Stewart26 Jul '09 - 5:13 
On whatever line number the error mentions, add ".Text" to the label where the string is assigned.
 
But you shouldn't even be using this anymore. This predates ASP.NET 2.0 that added support for more advanced role membership, built around a whole framework of abstraction.
 
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Software Design Engineer
Developer Division Customer Product-lifecycle Experience
Microsoft
 
[My Articles] [My Blog]

GeneralMachine KeymemberLonj13 Apr '09 - 8:43 
I had this working in a one-server environment, but when moved to server farm, it keeps redirecting back to the log in. The best I can determine is that it is using the machine key to encrypt and when it want to authenticate, is hitting a different server in the farm and fails. What is the solution to this in a server farm?
 
// Encrypt the cookie using the machine key for secure transport
 
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
 
hash); // Hashed ticket
 
thank you in advance...
GeneralRe: Machine KeyprotectorHeath Stewart30 Jan '10 - 8:51 
You need to edit your site's web.config (or even machine's machine.config (.NET 1.x) or default web.config (.NET 2.0+)) to specify the same key across a farm. See http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007_webfarmdeploymentconsiderations[^].
 
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Software Design Engineer
Developer Division Customer Product-lifecycle Experience
Microsoft
 
[My Articles] [My Blog]

GeneralNot Workingmembermarwan198412 Apr '09 - 0:04 
I thinks we should replace redirect by RedirectFromLoginPage Method????
GeneralThank youmemberOne Excluded24 Feb '09 - 8:32 
really....Thumbs Up | :thumbsup:
GeneralApplication_AuthenticateRequest never get HttpContext.Current.Usermemberbelfegor24 Feb '09 - 6:32 
Hi...very good article
 
There's somebody can help me???...Need some guidance with this problem...(asp.net 2.0/vstudio 2005)
 
I have the next directory structure
 
/root
web.config
default.aspx
/admin
      workspace.aspx
/user
      workspace.aspx
 
and web.config see like this:
 
      <pre>
<!--<authentication mode="Windows"/> -->
      <authentication mode="Forms">
         <forms loginUrl="default.aspx" defaultUrl="user/workspace.aspx" name="ck.SRCI.ESEPEAuth" timeout="30" path="/" protection="All" slidingExpiration="true">
         </forms>
      </authentication>
      <authorization>
         <!--<deny users="?" />-->
         <allow users="*"/>
      </authorization>
</system.web>
<location path="user">
      <system.web>
         <authorization>
            <allow roles="Usuario"/>
            <deny users="*"/>
         </authorization>
      </system.web>
   </location>
   <location path="admin">
      <system.web>
         <authorization>
            <allow roles="Administración"/>
            <deny users="*"/>
         </authorization>
      </system.web>
   </location>
</pre>
 

I can validate correctly user access on default.aspx :
 
   <pre>FormsAuthentication.Initialize();
 
                  string roles = BLL.Permisos.Instance.getUsuarioRoles(SessionManager.Instance.currentUserId);
 
                  if (BG.Tools.Configuration.Instance.isSuperAdmin(SessionManager.Instance.currentUserId))
                  {
                        if (roles != "")
                        {
                              roles += "|sadmin";
                        }
                        else
                        {
                              roles += "sadmin";
                        }
 
                  }
 
                  FormsAuthenticationTicket oTicket = new FormsAuthenticationTicket(
                        1,
                        SessionManager.Instance.currentUser,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(SessionManager.Instance.sessionTimeout),
                        false,
                        roles,
                        FormsAuthentication.FormsCookiePath);
 
                  string encryptedTicket = FormsAuthentication.Encrypt(oTicket);
 

                  HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                  if (oTicket.IsPersistent) authCookie.Expires = oTicket.Expiration;
                  Response.Cookies.Add(authCookie);
 
                  Response.Redirect("user/workspace.aspx",false);</pre>
 
And redirect to default users page, but on global.asax y receive always HttpContext.Current.User==null and cannot create the IPrincipal object
 

<pre>protected void Application_AuthenticateRequest(object sender, EventArgs e)
      {
            <b>if (HttpContext.Current.User != null)</b>            {
 
                  if (HttpContext.Current.User.Identity.IsAuthenticated)
                  {
 
                        if (HttpContext.Current.User.Identity is FormsIdentity)
                        {
                              FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                              FormsAuthenticationTicket ticket = id.Ticket;
 
                              // Get the stored user-data, in this case, our roles
                              string userData = ticket.UserData;
                              string[] roles = userData.Split('|');
                              HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
                        }
                        else
                        {
                              Response.StatusCode = 401;
                              throw new Exception("Método de autentificación no soportado " +
                                    HttpContext.Current.User.Identity.AuthenticationType);
                        }
                  }
            }
}</pre>
 
What I'm doing wrong (cookies are already sent but always I'm redirected to the login page)???
 
Previously I made correct forms/windows mixed authentication with custom roles but I can't understand this new 'dilema'
 
Thanks in advice
AnswerRe: Application_AuthenticateRequest never get HttpContext.Current.Usermemberbelfegor24 Feb '09 - 12:43 
now...I answer my self (too many time wasted and I forget to think about it more harder)
 
"there is a limit of 4KB that is dictated by the max cookie size"
 
I was putting many privilegies on the ticket userdata
 
The solution was to move the roles string info on aditional crypted cookie and now all is working like a charm!!!
QuestionRe: Application_AuthenticateRequest never get HttpContext.Current.Usermembermohask19 Feb '11 - 2:15 
@belfegor: Iam also facing the same problem and your msg on the forum to have the solution has relived my worry. Could you please advise me how "to move the roles string info on aditional crypted cookie"?
QuestionAlways show incorrect user namememberHimanshu Verma30 Dec '08 - 0:03 
Hi,
I have implemented your coding as it but whenever I login it shows incorrect login/password. I dont know why it bypass the if block and comes directly in else block of login page's btnclick event.
Also I am confused of using name property in <Form> tag, what should be name property for me.
GeneralRoleManager and RoleProvidermemberan_phu24 Dec '08 - 7:43 
People should really be using the RoleManager and RoleProvider now. They were part of the ASP.NET 2.0 release.
QuestionProblem with loginmemberProteus21 Oct '08 - 23:04 
Hi,
I have implement this solution in my application. When I login to system for the first time, everything works great. But when I logout , and want to login once again there appear page with this message HTTP Error 404 - Not Found. If I want to login to system after this error shows, I have to go back to previous page (login page), reload it, and then my user is login to system.
Can someone help me?
GeneralWroked like charm!memberrawwool19 Oct '08 - 0:40 
I changed the storage to XML and used XPath query instead.
GeneralRedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberPranjaliBhide29 Sep '08 - 23:05 
I developed a site with a reserved section based on roles, when I try to access that page i got redirected correctly to the loginpage and on the address bar i see
the ReturnUrl containig the address to point to:
 
http://localhost/SiteName/login.aspx?ReturnUrl=%2fSiteName%
2fadministrator%2fdefault.aspx
 
administrator/default.aspx is the page I have to reach
I authenticate succesfully but when the following instruction executes without error:
FormsAuthentication.RedirectFromLoginPage(user, chkRemember.Checked)
i still remain in the same page, only user and pwd disappear
 
the address in the bar is still the same....
 
otherwise if i submit incorrect user o pwd I got an error that indicates the redirect correctly fails:
If AuthenticateUser(userEncoded, pwdEncoded, roles) Then
FormsAuthentication.RedirectFromLoginPage("@" & ruoli, chkRemember.Checked)
 
Else
lblLogin.Text = "Access denied!"
End If
 

Any idea?
 
Thanks,
In Advance.
Generalvery helpful one thanksmembersnopbear27 Aug '08 - 23:34 
very helpful one thanks Shucks | :->
GeneralCan't Sign Out a user whatsoever.memberjohnnythaiho22 Aug '08 - 4:47 
Hi,
 
I used your tutorial and log user in successfully with their roles, but I have problem to sign out the user. After sign out, the user still be able to go back to the security page without log in. I think it's the problem with cashing memory. I google around any use all suggestion but it doesn't work at all. I hope you can help me out here.
 
FYI: I used all the code as suggest as below:
FormsAuthencation.SignOut();
Session.Abondon();
HttpCookie cookies = Context.Request.Cookies[FormsAuthentication.FormsCookieName];//Or Response
cookies.Expires = DateTime.Now.AddDays(-1);
Context.Response.Cookies.Add(cookies);

Thanks in advance.
 
Johnny
GeneralRe: Can't Sign Out a user whatsoever.memberMember 152512127 Aug '08 - 6:33 
Hi,
 
I also cannot sign out at all... this worked fine in 1.1, but trying in 3.5 now (2.0) and it simply doesn't log the user out.
 
Have tried removing the cookie, setting the current user to null, SignOut(), RedirectToLoginPage(), all sorts.
 
Does anyone have any ideas how to sign out of a custom role-based forms authentication???
 
Cheers,
 
Tom.
GeneralRe: Can't Sign Out a user whatsoever.memberjohnnythaiho27 Aug '08 - 7:18 
Hi Tom,
 
FormsAuthentication.SignOut() will sign out the user, but won't clear the cache memory.
 
Try to find out yourself by sign the user out with FormAuthentication.SignOut() and get back to that page with the url address. It will let you in, but if you hit the refresh button, it will kick you out of that page and forward you to the Login.aspx page (if you set up that way).
 
If this is the issue, don't try to waist your time with some suggestions like to set the cookies.Expire because this has nothing to do with cookies.
 
Here is what I found and it work for me.
 
you can use the directive for your page like this
<![CDATA[<% OutputCache Duration="1" VaryByParm="none" %>]]>
 
or set the cache expire with Page_Load for that page, I like this way better
 
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpries(DateTime.Now);
}
 
Good Luck,
 
Johnny
GeneralRe: Can't Sign Out a user whatsoever.memberMember 152512127 Aug '08 - 22:03 
Thanks for your prompt reply, Johhny.
 
Unfortunately, this also did not work for me - I had tested whether it might be the cache. Refreshing the page doesn't redirect me to the login, so I can only assume that the cache is not the issue.
 
This is really quite a puzzler - as I mentioned, this all seemed to work fine in ASP.NET 1.1.
 
Here is my code, in case you have any other suggestions:
 
Login.aspx button_click event
 
// check that the user's password hash and username are present
// get the user's roles from the DB

// set up the authentication:

// create an authentication ticket
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1,	// version
    TextEmail.Text,	// user name
    DateTime.Now,	// creation
    RememberLogin.Checked ? DateTime.MaxValue : DateTime.Now.AddMinutes(120),// expiration
    RememberLogin.Checked,		// persistent
    roles           // user data
    );
 
// encrypt the ticket
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
 
// create a cookie and add the encrypted ticket to the cookie as data
// this cookie is used in the global AuthenticateRequest event to 
// retreive the userid and then get the user from the system and store
// the data in the context for the remainder of the request
HttpCookie authCookie = new HttpCookie(
    FormsAuthentication.FormsCookieName, 
    encryptedTicket);
 
// if the user has asked us to remember them, then we want the cookie to last for ever
if (authTicket.IsPersistent)
    authCookie.Expires = authTicket.Expiration;
else
    authCookie.Expires = DateTime.Now.AddMinutes(120);
 
// add the cookie to the outgoing cookies collection
Response.Cookies.Add(authCookie);
     
// this cookie as we already have in the code above
if (FormsAuthentication.GetRedirectUrl(TextEmail.Text, false).Length > 0)
{
    string rdUrl = FormsAuthentication.GetRedirectUrl(TextEmail.Text, false);
    Response.Redirect(FormsAuthentication.GetRedirectUrl(TextEmail.Text, false));
}
else Response.Redirect("default.aspx");
 
Global.asax
 
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.User != null)
    {
	if (HttpContext.Current.User.Identity.IsAuthenticated)
	{
  	     if (HttpContext.Current.User.Identity is FormsIdentity)
       	     {
       	          FormsIdentity id =
       	              (FormsIdentity)HttpContext.Current.User.Identity;
       	          FormsAuthenticationTicket ticket = id.Ticket;
 
       	          // Get the stored user-data, in this case, our roles
       	          string userData = ticket.UserData;
       	          string[] roles = userData.Split(',');
       	          HttpContext.Current.User = new GenericPrincipal(id, roles);
	    }
	}
    }
}
 
Any ideas you may have would be appreciated.
 
Many thanks in advance,
 
Tom.
GeneralRe: Can't Sign Out a user whatsoever.memberTommy W27 Aug '08 - 22:35 
Hi Johnny, Heath, All,
 
I am still slightly confused, but have found a solution to this issue.
 
I was attempting to set the name and domain of the name and domain of the cookie:
 
    <authentication mode="Forms">
      <forms loginUrl="~/login.aspx"
             domain="www.somesite.com"
             name="somesite">
      </forms>
    </authentication>
 
However, as I was running on localhost:xxx I assume that this caused the issue. Perhaps when the application is actually sitting on the domain, this will be fine.
 
Thanks very much for your help!
 
Tom.
GeneralRe: Can't Sign Out a user whatsoever.memberjohnnythaiho28 Aug '08 - 3:08 
Hi Tom,
 
I am glad that you found the solution. I am sure that your input above will help other people. Also I like to say thanks to Mr. Stewart for his very usefull article.
 
Johnny.
GeneralRe: Can't Sign Out a user whatsoever.memberTommy W28 Aug '08 - 3:10 
As would I!
GeneralRe: Can't Sign Out a user whatsoever.memberSR8122 Feb '09 - 15:47 
Hi,
I am able to sign out the user only by putting a button(signout) on the form and then by simply writing formsauthentication.signout command in its button click event..so when the user opens the site again hes prompted to login again to see the secure pages.
But..instead of clicking the button,when the user hits the cross button and closes the browser. If he opens the site again,He is still logged in and hes abel to see secure pages..
I ve tried lot of things mentioned in this article, in the global.asx the app_end event is never called when the user hits cross button.
but i am still not able to logout the user when he hits the cross button.
Can any1 help?
GeneralRe: Can't Sign Out a user whatsoever.memberSR8122 Feb '09 - 17:54 
Ok found it, Just by changing the following line..

Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(Username.Text, False, 30)
By setting ispersistant to false the cooke is nomore durable.
GeneralThis code with Web.sitemapmemberMember 46654377 Aug '08 - 8:26 
Specifying directory security in the web.config, works fine. But when I specify roles in web.sitemap it does not work. Could you explaing why?
QuestionIs there a VB version?memberchieut28 Jul '08 - 4:28 
Hi,
 
I want to use this role based security but would like to do it in VB. Do you knoe if there is one like this in VB?
 
Thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 26 Jul 2009
Article Copyright 2002 by Heath Stewart
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid