473,689 Members | 2,822 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom login will not work

When I started a new ASP project I was eager to use the login facilities
offered in Framework 2.0/VS 2005.

I wanted:
- A custom principal that could hold my integer UserID from the database
- An easy way to classify different pages as either Admin, Member or Public,
where login is necessary for Admin and Member but not for Public. My idea was
to put the pages in different directories to easily keep my order.
- An easy menu system that would show only accesible pages

I carefully read the newsgroups and put together what I thought was a good
mix of working ideas. I think I am quite close but I don't really make it all

Hopefully someone can give me a hint by scanning through my code sample:

=============== =============== =============== ==

web.config content:
<authenticati on mode="Forms">
<forms loginUrl="Publi c/Login.aspx" defaultUrl="/Default.aspx"
name=".ASPXFORM SAUTH" path="\">
<authorizatio n>
<deny users="?"/>
<allow users="*"/>

Global.asax content:
<script runat="server">

Protected Sub Application_Aut henticateReques t(ByVal sender As Object,
ByVal e As System.EventArg s)
Dim app As HttpApplication
Dim authTicket As FormsAuthentica tionTicket
Dim authCookie As String = ""
Dim cookieName As String = FormsAuthentica tion.FormsCooki eName
Dim userIdentity As FormsIdentity
Dim userData As String
Dim userDataGroups As String()
Dim PersonID As Integer
Dim roles As String()
Dim userPrincipal As CustomPrincipal
Dim AllowAccess as Boolean
app = DirectCast(send er, HttpApplication )

If app.Request.IsA uthenticated AndAlso
app.User.Identi ty.Authenticati onType = "Forms" Then
'Get authentication cookie
authCookie = app.Request.Coo kies(cookieName ).Value
Catch ex As Exception
'Cookie not found generates exception: Redirect to loginpage
Response.Redire ct("Login.aspx" )
End Try

'Decrypt the authentication ticket
authTicket = FormsAuthentica tion.Decrypt(au thCookie)

'Create an Identity from the ticket
userIdentity = New FormsIdentity(a uthTicket)

'Retrieve the user data from the ticket
userData = authTicket.User Data

'Split user data in main sections
userDataGroups =
userData.Split( CustomPrincipal .DELIMITER_SECT IONS)

'Read out ID and roles
PersonID = CType(userDataG roups(0), Integer)
roles = userDataGroups( 1).Split(Custom Principal.DELIM ITER_ROLES)

'Rebuild the custom principal
userPrincipal = New CustomPrincipal (userIdentity, PersonID, roles)

'Set the principal as the current user identity
app.Context.Use r = userPrincipal

End If
'If we already are heading for Login page then we don't need to
check anything more
If Request.Url.Abs olutePath.ToLow er =
FormsAuthentica tion.LoginUrl.T oLower Then
Exit Sub
End If

'Evaluate if access is allowed
Select Case BaseDirectory(R equest.Url)
Case "Member", "Admin"
'For all restricted pages we need to check user validity

If IsNothing(app.C ontext.User) Then
'User is not authenticated
AllowAccess = False

ElseIf IsNothing(SiteM ap.CurrentNode) OrElse
(SiteMap.Curren tNode.Roles.Cou nt = 0) Then
'Missing SiteMap means access is implicitly allowed
AllowAccess = True

AllowAccess = False
'Loop through each role and check to see if user is in
one of them
For Each Role As String In SiteMap.Current Node.Roles
If app.Context.Use r.IsInRole(Role ) Then
AllowAccess = True
Exit For
End If
End If
Case Else
'Public folders are always OK
AllowAccess = True

End Select

If Not AllowAccess Then
Response.Redire ct(FormsAuthent ication.LoginUr l)
End If

End Sub

Protected Function BaseDirectory(B yVal u As System.Uri) As String
Select Case u.Segments.Leng th
Case Is < 3
Throw New Exception("Base Directory expecting at least one
level of directories")
Case 3
Return ""
Case Else
Return u.Segments(2).R eplace("/", "")
End Select
End Function


Public Class CustomPrincipal
Inherits System.Security .Principal.Gene ricPrincipal

Private _PersonID As Integer

Public Const DELIMITER_SECTI ONS As String = ";"
Public Const DELIMITER_ROLES As String = ","

Public Enum Roles
Member = 1
Editor = 2
Admin = 3
End Enum

Public Sub New(ByVal identity As System.Security .Principal.IIde ntity,
ByVal PersonID As Integer, ByVal roles As String())
MyBase.New(iden tity, roles)
_PersonID = PersonID
End Sub

Public ReadOnly Property UserName() As String
Return MyBase.Identity .Name
End Get
End Property

Public ReadOnly Property PersonID() As Integer
Return _PersonID
End Get
End Property

Public Shadows ReadOnly Property IsInRole(ByVal role As Roles) As Boolean
Return MyBase.IsInRole (role)
End Get
End Property

End Class

Partial Class Login
Inherits System.Web.UI.P age

Protected Sub cmdLogin_Click( ByVal sender As Object, ByVal e As
System.EventArg s) Handles cmdLogin.Click
Dim p As Person
Dim RedirectUrl As String

p = New Person
p.Load(txtUserI D.Text, txtPassword.Tex t)

If p.IsEmpty Then
Throw New Exception("Logi n failed. Please check your
username and password and try again.")
End If

'Create a ticket with validated user
CreateAuthentic ationTicket(p, chkPersist.Chec ked)

'Redirect to requested page
RedirectUrl = GetReturnUrl
Response.Redire ct(RedirectUrl)
Catch ex As Exception
lblFailure.Text = ex.Message
End Try
End Sub

Public ReadOnly Property GetReturnUrl() As String
If IsNothing(Reque st.QueryString( "ReturnUrl" )) Then
'Default page
Return FormsAuthentica tion.DefaultUrl
'Requested page if present
Return Request.QuerySt ring("ReturnUrl ")
End If
End Get
End Property

Public Sub CreateAuthentic ationTicket(ByV al p As Person, ByVal
Persistant As Boolean)
Dim authTicket As FormsAuthentica tionTicket
Dim encTicket As String
Dim cookie As HttpCookie

'Create a ticket
authTicket = New FormsAuthentica tionTicket(1, p.Name, _
DateTime.Now.Ad dMonths(1), _
Persistant, p.UserData)

'Encrypt the ticket into a string
encTicket = FormsAuthentica tion.Encrypt(au thTicket)

'Create the cookie
cookie = New HttpCookie(Form sAuthentication .FormsCookieNam e,

If Persistant Then
'Specify expiration date
cookie.Expires = Now.AddMonths(1 )
End If

'Save the cookie
Response.Cookie s.Add(cookie)
Catch ex As Exception
Throw New Exception("Crea teAuthenticatio nTicket: " & ex.Message)
End Try
End Sub
End Class

Sitemap content:
<siteMapNode title="Start" url="default.as px" description="Re turn to start
page" roles="*">
<siteMapNode title="Activiti es">
<siteMapNode title="Calender " url="Public/Calendar.aspx" roles="*" />
<siteMapNode title="My Responsibility"
url="Member/MyResponsibilit y.aspx" roles="*" />
<siteMapNode title="Edit Activity" url="Member/ActivityEdit.as px"
roles="1" />
<siteMapNode title="Add Activity" url="Member/ActivityAdd.asp x"
roles="2" />
=============== =============== =============== ===
Problems found with this code:
1) You need to click Logout twice to get out
2) You don't reach pages in the Public folder without logging in
3) After login some redirection doesn't work.
If the Login page itself is placed in a subdirectory, then it will not find
the defaultURL.
4) The TreeView control based on a sitemap always show all menus even if
they are mapped to different roles.
Sep 13 '06 #1
1 4992
Hello jaklithn,

From your description, you're wantting to build an ASP.NET web application
which is protected by forms authentication and you will also add some
addtional data like userID and roles associated with each user. Then,you'll
authorize the access to each page and the display links of navigation menu
according to these roles. You're wondering how to conveniently implement
this in ASP.NET 2.0,correct?

As for this scenario, based on my experience, here are some of my
understanding and suggestion:

For forms authentication, you do can use the global.asax or a custom
httpmodule to manually parse the authentication cookie and get additional
user data(roles) from it and assign them to our custom principal class
instance. However, the drawback of this is:

1. We can not use the built-in role-manager service in ASP.NET 2.0(new
feature), which can help us automatically handle role management(asso ciate
role to a certain user after authentication)

2. If you want to customize our navigation controls(such as Treeview or
menu ) to display items according to current user's authorization roles,
you need to manually write code instead of using the built-in security
trimming feature.
I have another solution you can also consider here:

Instead of manually do the role management(thro ugh global.asax or
httpmodule), use the built-in membership and role management service:

#ASP.NET 2.0 Membership, Roles, Forms Authentication, and Security

You just need to configure the membership provider and enable role manager
in web.config, by default it use SQL Express database file as persistent

And for the authorization on page url , it still is automatically managed
as long as you configure the <authorizations ettings correctly. For
navigation menu's displaying, you can have a look at the Site-Map security
trimming feature in ASP.NET 2.0:
#ASP.NET Site-Map Security Trimming

here is a live example provided by ASP.NET product manager ScottGu, the
example is using windows authentication , but it easier to change to forms

#Recipe: Implementing Role-Based Security with ASP.NET 2.0 using Windows
Authentication and SQL Server

and the only problem here is that how to store the additional userID
data(or any other additional data associated with each user). Here I
suggest you consider using the Profile service which can help store some
custom data(basic types or custom class type) that associate with each
user(mapping to forms authentication &membership service):

#ASP.NET Profile Properties Overview

Please have a look at these resources. If there is anything unclear, please
feel free to let me know.


Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Oct 16 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Mark Aurit | last post by:
I have an intranet application that uses w2k Integrated Windows Authentication to authenticate users. We now have a situation where people will be accessing it who are on our network but will not be logged into w2k - so now they are challenged and fail the challenge. To handle that situation I plan to use iis custom errors with one of the 401 codes to redirect the user to a generic page. The problem is that I cant figure out how to...
by: anonymous | last post by:
Hi all, I've been searching the way to achieve the following task. But no luck so far. I have a web site(main site), which requires authentication. This authentication is set at Windows directory level, so user will see the pop up gray box in order to log in rather than custom web page. The username and password are stored at active directory level, thus this is the windows integrated security.
by: Nick | last post by:
the customError feature is not working. I have it setup as the help says in my web.config file. <customErrors defaultRedirect="DsAppError.aspx" mode="RemoteOnly"/> I tried in a couple different parts of my site to throw a dummy exception and I always get to the page that says change my web.config to the statement above.
by: John Lau | last post by:
Hi, I am looking at the MS KB Article 306355: HOW TO: Create Custom Error Reporting Pages in ASP.NET by Using Visual C# .NET This article describes how to redirect errors to a custom html error page. All six steps in the article work just fine. Then at the end of the article, there is a little comment about redirecting errors to an aspx page (instead of an html page):
by: Beren | last post by:
Hello With trial and error I'm attempting to create an extended identity to store some more data than just the Name, for example a Subscription and a LastSearchPerformed property... Is this a good idea ? I'm coming from ASP and Session variables, but I explicitly wanted to avoid that for .NET. The problem I'm facing is that I don't find a good way to bring my source
by: Graham | last post by:
I have created a custom MembershipProvider called "LassieMembershipProvider" that derives from "MembershipProvider". This providor is located in a Businesslogic layer dll called "Enlighten.LinkMad.Businesslogic". In one of my frontend websites I use this type to authenticate a user who is trying to login. The following excerpt is from the web.config of the particular site showing the reference to the custom provider, allowing .Net to do...
by: Klaus Jensen | last post by:
Hi I face this challenge: An existing site with 50000+ html-files needs to be protected by a custom login-system which has two goals: 1. Protect HTML-content (authentication required) 2. If the same username is used by two persons at the same time, they have to be logged out (when a login is used, other users currently logged in
by: =?Utf-8?B?UGFyYWcgR2Fpa3dhZA==?= | last post by:
Hi All, We have a requirement where we have to develop a custom Login Page which will accept user's NT credentials ( Username , password, domain name). This then needs to be passed to a website which uses Windows Authentication Now my question is how do we pass these credentials to IIS in classic ASP? Would appreciate any help/pointers on this. Thanks in advance.
by: seanwalsh | last post by:
Hi I'm new to ASP.NET (from classic ASP) and wasn't aware of the Forms Authentication security when I started working on a website. So I built a login page that stores a CustomUser object in the Session, and then I put a login check in the Master Page codebehind, Page_Load event, which redirects to the Login.aspx if the login check fails. I realise NOW that I should have gone th Forms Authentication (using web.config) route, but I dont...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.