me too - by the way, here is my latest version of what I've been using - which supports anonymous users ... Public Class UserInfo Public Shared Function InfoString(ByVal ID As String, ByVal Name As String, ByVal Email As String) As String Return ID + "|" +
Name + "|" + Email End Function Public Shared Function InfoString() As String If HttpContext.Current.Request.IsAuthenticated Then Return HttpContext.Current.User.Identity.Name Else Return "Anonymous" End If End Function Public Shared Function ID(Optional ByVal
_UserInfo As String = "") As String If _UserInfo = "" Then If HttpContext.Current.Request.IsAuthenticated Then Return HttpContext.Current.User.Identity.Name.Split("|").GetValue(0) Else Return "0" End If Else Return _UserInfo.Split("|").GetValue(0) End If End
Function Public Shared Function Name(Optional ByVal _UserInfo As String = "") As String If _UserInfo = "" Then If HttpContext.Current.Request.IsAuthenticated Then Return HttpContext.Current.User.Identity.Name.Split("|").GetValue(1) Else Return "Anonymous"
End If Else Return _UserInfo.Split("|").GetValue(1) End If End Function Public Shared Function Email(Optional ByVal _UserInfo As String = "") As String If _UserInfo = "" Then If HttpContext.Current.Request.IsAuthenticated Then Return HttpContext.Current.User.Identity.Name.Split("|").GetValue(2)
Else Return "Anonymous" End If Else Return _UserInfo.Split("|").GetValue(2) End If End Function end class
OK, bear with me on this because I've also got mixed into the bag the requirement to have mixed anonymous and NT authentication on the portal this code was written for. This is the custom object needed to extend the Context.User.Identity object (by the way,
I mistakenly said above the Context.User object inherits GenericIdentity - I meant the Context.User.Identity object): Public Class PortalIdentity Inherits GenericIdentity Private _employeeID As String Private _firstName As String Private _lastname As String
Private _roles As ArrayList Private _groupID As Integer Public Property LastName() As String Get Return _lastname End Get Set(ByVal Value As String) _lastname = Value End Set End Property Public Property GroupID() As Integer Get Return _groupID End Get Set(ByVal
Value As Integer) _groupID = Value End Set End Property Public Property EmployeeID() As String Get Return _employeeID End Get Set(ByVal Value As String) _employeeID = Value End Set End Property Public Property Roles() As ArrayList Get Return _roles End Get
Set(ByVal Value As ArrayList) _roles = Value End Set End Property Public ReadOnly Property FirstName() As String Get Return _firstName End Get End Property Public Sub New(ByVal name As String, ByVal FirstName As String) MyBase.New(name) _firstName = FirstName
End Sub Public Sub New(ByVal name As String, ByVal FirstName As String, ByVal type As String) MyBase.New(name, type) _firstName = FirstName End Sub End Class The other piece you must add is to manually serialize the object into the cookie (the FormsAuthentication
does this for you -- could possibly use the default FormsAuthentication routine to serialize and encrypt the cookie, but I haven't tested it since I am using NT authentication). The following function sends the cookie to the client if it does not already exist.
(again, this has a bit of tendency towards NT authentication - noted where applicable): Public Shared Sub SetUserIdentityCookie() ' Handles the single instance where a client is authenticating. ' The sender is the application context. We need to grab a reference
to it. Dim httpCon As HttpContext = HttpContext.Current Dim client As SqlDataReader ' Get roles from UserRoles table, and add to cookie Dim _user As New EmployeesDB() ' THIS LINE ASSUMES NT AUTHENTICATION. YOU WOULD OTHERWISE DO THE TYPICAL ' CHECK USING THE
LOGIN FORM AND VERIFYING THE CREDENTIALS ARE VALID. client = _user.GetSingleEmployeeByUserIdentity(httpCon.User.Identity.Name) ' DATA RETURNED FROM THE DATABASE ABOUT THIS CLIENT. COULD ALSO COMBINE ' THIS WITH THE STEP TO VALIDATE THE CLIENT. If client.Read()
Then 'Create an identity and serialize it to a cookie. - PASS IN THE NAME FROM THE ' DB, NOT httpCon.User.Identity.Name <- again, NT Authentication Dim ident As New PortalIdentity(httpCon.User.Identity.Name, client("first_name"), "CustomSecurity") ident.EmployeeID
= client("employee_id") ident.GroupID = client("group_id") ident.LastName = client("last_name") ident.Roles = _user.GetRoles(ident.EmployeeID) ' serialization objects Dim stream As New System.IO.MemoryStream() Dim format As New Formatters.Binary.BinaryFormatter()
Try ' Actually serialize format.Serialize(stream, ident) ' Declare a new cookie Dim cookie As New HttpCookie("portalsettings") cookie.Value = Convert.ToBase64String(stream.ToArray) ' Set cookie timeout cookie.Expires = Now.AddHours(8) httpCon.Response.Cookies.Add(cookie)
' Add our own custom principal to the request containing the roles httpCon.User = New GenericPrincipal(ident, ident.Roles.ToArray(GetType(String))) Catch ex As Exception ' Do nothing -- just don't authenticate End Try End If client.Close() End Sub The other
possibility is reading the cookie and reconstituting the custom identity object when a request comes in: If Not Request.Cookies("portalsettings") Is Nothing Then ' Reconstitute identity from cookie Dim ident As PortalIdentity Dim stream As New System.IO.MemoryStream()
Dim format As New Formatters.Binary.BinaryFormatter() Dim bytes() As Byte Try ' Get the byte array from the cookie bytes = Convert.FromBase64String(httpCon.Request.Cookies("portalsettings").Value) ' Write the byte array to a memory stream stream.Write(bytes,
0, UBound(bytes) + 1) ' Set the stream to the beginning and deserialize stream.Position = 0 ident = CType(format.Deserialize(stream), PortalIdentity) ' Add our own custom principal to the request containing the roles in the auth ticket httpCon.User = New GenericPrincipal(ident,
ident.Roles.ToArray(GetType(String))) Catch ex As Exception ' Do nothing End Try End If End Sub I created my own HTTPHandler to consolidate this functionality in one module, but you could just as easily replace the given code in the global.asax.vb file with
this code (probably needs minor tweaking, haven't done it myself). One thing to keep in mind is that the object now stored in Context.User.Identity might or might not be a PortalIdentity object (depending on whether the user has authenticated or not). So,
to make a call to one of the custom properties, you need to verify that you've got the correct object. For example, in my portaldesktopheader.ascx.vb file, to add personalization to the header, I've got: ' Personalize If TypeOf context.User.Identity Is PortalIdentity
Then WelcomeMessage.Text = "Welcome, " & CType(Context.User.Identity, PortalIdentity).FirstName & " |" WelcomeMessage.Visible = True hlLogout.Visible = True hlLogin.Visible = False End If Hope that was clear enough to point you in the right direction. =) David
Great!!!! I tried this methord , and its works!!!!! Because of formsauthentication only allow pass string value, cannot in object, so, it cannot include more information after auth. Thanks for David's Code and i have something to ask, hm... do u mind to post
out the Httphandler code? also i am also trying to code it
Hi David, Can i ask you something for the code : Public Sub New(ByVal name As String, ByVal FirstName As String) MyBase.New(name) _firstName = FirstName End Sub Public Sub New(ByVal name As String, ByVal FirstName As String, ByVal type As String) MyBase.New(name,
type) _firstName = FirstName End Sub i dont know what does MyBase.New(name) means Best Regards Herbert
Herbert, MyBase is an inheritance keyword in VB.Net to refer to an object's base class. Since I inherit from GenericIdentity, in addition to populating the extra data I am interested in, I instantiate the base class by calling one of the available Mybase.New()
methods. That way, I've got the additional methods and properties as well as the base class methods and properties (you can check using the object browser to see that the extended class has all the methods and properties of the base class in addition to the
ones I added). In response to your other email, the security handler is attached. I've actually included everything in the module, so there will be redundancy here from what I originally posted. The gist is this: In web.config, anonymous access is set (allow
users="?"). On login.aspx, I've denied anonymous access (deny users="?"). I've also got the security scheme set to NT Authentication (Intranet portal, not Internet portal). Finally, on the code-behind for login.aspx, if the user is authenticated, then I call
the SetUserIdentityCookie() method to set the cookie. The net result of all of this is that when the user attempts to login, he has to authenticate to hit login.aspx. This is done automatically in IE by passing his/her NT credentials to the webserver. After
this, the cookie is set and the user is redirected to the homepage or to a redirect page. Complete module follows: ****************************************************** Imports System Imports System.Web Imports System.Web.Security Imports System.Security.Principal
Imports System.Runtime.Serialization Namespace ASPNetPortal Public Class PortalIdentity Inherits GenericIdentity Private _employeeID As String Private _firstName As String Private _lastname As String Private _roles As ArrayList Private _groupID As Integer
Public Property LastName() As String Get Return _lastname End Get Set(ByVal Value As String) _lastname = Value End Set End Property Public Property GroupID() As Integer Get Return _groupID End Get Set(ByVal Value As Integer) _groupID = Value End Set End Property
Public Property EmployeeID() As String Get Return _employeeID End Get Set(ByVal Value As String) _employeeID = Value End Set End Property Public Property Roles() As ArrayList Get Return _roles End Get Set(ByVal Value As ArrayList) _roles = Value End Set End
Property Public ReadOnly Property FirstName() As String Get Return _firstName End Get End Property Public Sub New(ByVal name As String, ByVal FirstName As String) MyBase.New(name) _firstName = FirstName End Sub Public Sub New(ByVal name As String, ByVal FirstName
As String, ByVal type As String) MyBase.New(name, type) _firstName = FirstName End Sub End Class Public Class SecurityUtility Public Shared Sub SetUserIdentityCookie() ' Handles the single instance where a client is authenticating. Dim httpCon As HttpContext
= HttpContext.Current Dim client As SqlDataReader ' Get roles from UserRoles table, and add to cookie Dim _user As New EmployeesDB() client = _user.GetSingleEmployeeByUserIdentity(httpCon.User.Identity.Name) If client.Read() Then 'Create an identity and serialize
it to a cookie. Dim ident As New PortalIdentity(httpCon.User.Identity.Name, client("first_name"), "CustomSecurity") ident.EmployeeID = client("employee_id") ident.GroupID = client("group_id") ident.LastName = client("last_name") ident.Roles = _user.GetRoles(ident.EmployeeID)
' serialization objects Dim stream As New System.IO.MemoryStream() Dim format As New Formatters.Binary.BinaryFormatter() Try ' Actually serialize format.Serialize(stream, ident) ' Declare a new cookie Dim cookie As New HttpCookie("portalsettings") cookie.Value
= Convert.ToBase64String(stream.ToArray) ' Set cookie timeout cookie.Expires = Now.AddHours(8) httpCon.Response.Cookies.Add(cookie) ' Add our own custom principal to the request containing the roles httpCon.User = New GenericPrincipal(ident, ident.Roles.ToArray(GetType(String)))
Catch ex As Exception ' Do nothing -- just don't authenticate End Try End If client.Close() End Sub End Class Public Class SecurityModule Implements IHttpModule Public Sub New() ' Just a creator sub End Sub Public Sub Init(ByVal context As System.Web.HttpApplication)
Implements System.Web.IHttpModule.Init ' Need to register our module with the application context. AddHandler context.AuthenticateRequest, AddressOf Me.AuthenticateRequest End Sub Public Sub Dispose() Implements System.Web.IHttpModule.Dispose ' Not necessary
to implement anything here. End Sub Private Sub AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) ' Process authentication here ' The sender is the application context. We need to grab a reference to it. Dim httpApp As HttpApplication = CType(sender,
HttpApplication) Dim httpCon As HttpContext = httpApp.Context If Not httpCon.Request.Cookies("portalsettings") Is Nothing Then ' Handles all other instances ' Reconstitute identity from cookie Dim ident As PortalIdentity Dim stream As New System.IO.MemoryStream()
Dim format As New Formatters.Binary.BinaryFormatter() Dim bytes() As Byte Try ' Get the byte array from the cookie bytes = Convert.FromBase64String(httpCon.Request.Cookies("portalsettings").Value) ' Write the byte array to a memory stream stream.Write(bytes,
0, UBound(bytes) + 1) ' Set the stream to the beginning and deserialize stream.Position = 0 ident = CType(format.Deserialize(stream), PortalIdentity) ' Add our own custom principal to the request containing the roles in the auth ticket httpCon.User = New GenericPrincipal(ident,
ident.Roles.ToArray(GetType(String))) Catch ex As Exception ' Do nothing End Try End If End Sub End Class End Namespace HTH, David
Dear David, Thanks for you code first, I am trying to write module and complie it into dll, but its it possible that using Data Object in DLL file? because when i import system.data.sqlclient it said that : Namespace or type 'SqlClient' for the Imports 'System.Data.SqlClient'
cannot be found. am i did something wrong? Best Regards Herbert
Dear David, I found that problem now i miss to include System.Data.dll when i compile :P vbc /t:library /r:System.dll,System.Data.dll,System.Web.dll UserIdentityCookieHandler.vb Best Regards Herbert
Dear David, Finally i done it, But i change something , i am not using Cookie to store identity the following is my code, if possible , can you comment on it (of course it is great for anyone comment) Dim uiUserInfo As UserInfo uiUserInfo = LoginVerify(txtcompanycode.text,
txtuserid.text, txtpassword.text) If uiUserInfo.UserID <> "" Then Dim stream As New System.IO.MemoryStream() Dim format As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter() Dim objContext As HttpContext = HttpContext.Current Format.serialize(stream,uiUserInfo)
Dim objIdentity = New GenericIdentity(Convert.ToBase64String(stream.toarray),"CustomAuthentication") Dim strRoles(1) As String ' Because i dont have any role now so i define a array manually strRoles(0) = "User" objContext.User = new GenericPrincipal(uiUserInfo,
strRoles) ' the change is the following -------------------- FormsAuthentication.RedirectFromLoginPage(Convert.ToBase64String(stream.toarray),false) '-------------------------------- Else lblError.Text = uiUserInfo.USerName End If ----------------------------------------------------------------------------------
Public Class UserInfo Inherits GenericIdentity Private _UserID As String Private _UserName As String Private _CompanyCode As String Public Shared Function InfoString(ByVal UserID As String, ByVal UserName As String, ByVal CompanyCode As String) As String Return
UserID + vbCRLF + UserName + vbCRLF + CompanyCode End Function Public Property UserID As String Get Return _UserID End Get Set _UserID = Value End Set End Property Public Property UserName As String Get Return _UserName End Get Set _UserName = Value End Set
End Property Public Property CompanyCode As String Get Return _CompanyCode End Get Set _CompanyCode = Value End Set End Property Public Sub New(ByVal UserID As String, ByVal UserName As String, ByVal CompanyCode As String) MyBase.New(UserID) _UserID = UserID
_UserName = UserName _CompanyCode = CompanyCode End Sub Public Sub New(ByVal UserID As String, ByVal UserName As String, ByVal CompanyCode As String, ByVal Type As String) MyBase.New(UserID,Type) _UserID = UserID _UserName = UserName _CompanyCode = CompanyCode
End Sub End class Public Class UserIdentityCookieHandler Implements IHttpModule Public Sub Init( ByVal objApp As HttpApplication ) Implements IHttpModule.Init AddHandler objApp.AuthenticateRequest, AddressOf Me.AuthenticateRequest End Sub Public Sub Dispose()
Implements IHttpModule.Dispose End Sub Public Sub AuthenticateRequest(Sender As Object, e As EventArgs ) If Sender.Request.IsAuthenticated Then Dim objApp As HttpApplication = CType(Sender, HttpApplication ) Dim objContext As HttpContext = objApp.Context Dim
stream As New System.IO.MemoryStream() Dim format As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter() Dim Bytes() as Byte Bytes = Convert.FromBase64String(objContext.User.Identity.Name) stream.Write(bytes,0,UBound(bytes)+1) stream.Position
= 0 Dim uiUserInfo As Userinfo uiUserInfo = Ctype(format.deserialize(stream),Userinfo) Dim strRoles(1) As String ' Because i dont have any role now so i define a array manually strRoles(0) = "User" objContext.User = new GenericPrincipal(uiUserInfo, strRoles)
End If End Sub End Class After Form Authentication i can use Ctype(Context.User.Identity,UserInfo).Username, Ctype(Context.User.Identity,UserInfo).CompanyCode, Retrieve my User Identity Because i still new in .NET, hope someone can give me a comment if i am
wrong Best Regards Herbert
DavidGMiles
Participant
1860 Points
372 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 11, 2003 07:19 PM|LINK
Lead Developer [vb & c#] - MCAD
SpaceWorld
Member
10 Points
2 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 11, 2003 11:07 PM|LINK
mbeller
Member
255 Points
51 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 12, 2003 11:59 PM|LINK
Lightship Partners LLC
davidbarrett
Member
155 Points
31 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 13, 2003 06:14 PM|LINK
kaillee
Member
70 Points
14 Posts
Re: Extending Context.User.Identity.Name to add USERID
Feb 28, 2003 07:33 AM|LINK
Herbert Lee
kaillee
Member
70 Points
14 Posts
Re: Extending Context.User.Identity.Name to add USERID
Mar 03, 2003 01:03 AM|LINK
Herbert Lee
davidbarrett
Member
155 Points
31 Posts
Re: Extending Context.User.Identity.Name to add USERID
Mar 03, 2003 03:35 PM|LINK
kaillee
Member
70 Points
14 Posts
Re: Extending Context.User.Identity.Name to add USERID
Mar 03, 2003 11:33 PM|LINK
Herbert Lee
kaillee
Member
70 Points
14 Posts
Re: Extending Context.User.Identity.Name to add USERID
Mar 04, 2003 12:03 AM|LINK
Herbert Lee
kaillee
Member
70 Points
14 Posts
Re: Extending Context.User.Identity.Name to add USERID
Mar 04, 2003 02:04 AM|LINK
Herbert Lee