If Request.IsAuthenticated Then
htmlString.Append("<h3>Generic User Information</h3>")
htmlString.Append("<b>name: </b>")
htmlString.Append(User.Identity.Name)
htmlString.Append("<br><b>Authenticated With: </b>")
htmlString.Append(User.Identity.AuthenticationType)
htmlString.Append("<br><br>")
End If
But if i add some code so i get this, then it will not work.
If Request.IsAuthenticated Then
htmlString.Append("<h3>Generic User Information</h3>")
htmlString.Append("<b>name: </b>")
htmlString.Append(User.Identity.Name)
htmlString.Append("<br><b>Authenticated With: </b>")
htmlString.Append(User.Identity.AuthenticationType)
htmlString.Append("<br><b>User ID: </b>")
htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString())
htmlString.Append("<br><br>")
End If
How do i get the userid number, the primary key !?
Public Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If Request.IsAuthenticated Then
Dim conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString)
conn.Open()
Dim cmd As New OleDbCommand("Select Groups.Name FROM ((Roles INNER JOIN Groups ON Groups.GroupID = Roles.GroupID) INNER JOIN Users ON USERS.UserID = Roles.UserID) WHERE Users.Username=@UserName", conn)
cmd.Parameters.AddWithValue("@UserName", User.Identity.Name)
Dim reader As OleDbDataReader = cmd.ExecuteReader()
Dim roleList As New ArrayList()
While reader.Read()
roleList.Add(reader("Name"))
End While
Dim roleListArray As String() = DirectCast(roleList.ToArray(GetType(String)), String())
HttpContext.Current.User = New GenericPrincipal(User.Identity, roleListArray)
reader.Close()
conn.Close()
End If
End Sub
And then i have this on my Loginpage
Private Function ValidateUser(ByVal userName As String, ByVal passWord As String) As Boolean
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim lookupPassword As String
lookupPassword = Nothing
' Check for an invalid userName.
' userName must not be set to nothing and must be between one and 15 characters.
If ((userName Is Nothing)) Then
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
Return False
End If
If ((userName.Length = 0) Or (userName.Length > 15)) Then
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
Return False
End If
' Check for invalid passWord.
' passWord must not be set to nothing and must be between one and 25 characters.
If (passWord Is Nothing) Then
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
Return False
End If
If ((passWord.Length = 0) Or (passWord.Length > 25)) Then
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
Return False
End If
Try
' Consult with your SQL Server administrator for an appropriate connection
' string to use to connect to your local SQL Server.
conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString)
conn.Open()
' Create SqlCommand to select pwd field from the users table given a supplied userName.
cmd = New OleDbCommand("SELECT Password, Username FROM Users WHERE Username=@userName AND Password=@passWord", conn)
cmd.Parameters.Add("@userName", OleDbType.VarChar, 25)
cmd.Parameters("@userName").Value = userName
cmd.Parameters.Add("@passWord", OleDbType.VarChar, 25)
cmd.Parameters("@passWord").Value = passWord
' Execute command and fetch pwd field into lookupPassword string.
lookupPassword = cmd.ExecuteScalar()
' Cleanup command and connection objects.
cmd.Dispose()
conn.Dispose()
Catch ex As Exception
' Add error handling here for debugging.
' This error message should not be sent back to the caller.
System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " & ex.Message)
End Try
' If no password found, return false.
If (lookupPassword Is Nothing) Then
' You could write failed login attempts here to the event log for additional security.
Return False
End If
' Compare lookupPassword and input passWord by using a case-sensitive comparison.
Return (String.Compare(lookupPassword, passWord, False) = 0)
End Function
Private Sub submit_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.ServerClick
If ValidateUser(txtUserName.Value, txtUserPass.Value) Then
Dim tkt As FormsAuthenticationTicket
Dim cookiestr As String
Dim ck As HttpCookie
tkt = New FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now(), DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data")
cookiestr = FormsAuthentication.Encrypt(tkt)
ck = New HttpCookie(FormsAuthentication.FormsCookieName(), cookiestr)
If (chkPersistCookie.Checked) Then ck.Expires = tkt.Expiration
ck.Path = FormsAuthentication.FormsCookiePath()
Response.Cookies.Add(ck)
Dim strRedirect As String
strRedirect = Request("ReturnURL")
If strRedirect <> "" Then
Response.Redirect(strRedirect, True)
Else
strRedirect = "default.aspx"
Response.Redirect(strRedirect, True)
End If
Else
Session("logininfo") = "DBerror"
Response.Redirect("login.aspx", True)
End If
End Sub
And then i have the first code in this thread on my default.aspx page.
(I guess) You are not retreiving the userId from the database after successfull Verification of the Password.
If you are getting the UserId then you will have to store it in Applicationsession veriable. User.Identity does not have the field to store the UserId You can store it in AuthenticationType field of User.Identity but that will only benifit if you dont have
to access authentication type for authentication.(In a case where you just have only one type of authentication.).
When you provide nothing for the GetUser() method, it will get the current user by default. So there is no need to pass User.Identity.Name for the GetUser method.
siraero
Member
419 Points
604 Posts
How do i Get/Show the user ID in user.identity.name !?
Aug 09, 2012 10:33 AM|LINK
Hi
I have this code that works, i get the user name.
If Request.IsAuthenticated Then htmlString.Append("<h3>Generic User Information</h3>") htmlString.Append("<b>name: </b>") htmlString.Append(User.Identity.Name) htmlString.Append("<br><b>Authenticated With: </b>") htmlString.Append(User.Identity.AuthenticationType) htmlString.Append("<br><br>") End IfBut if i add some code so i get this, then it will not work.
If Request.IsAuthenticated Then htmlString.Append("<h3>Generic User Information</h3>") htmlString.Append("<b>name: </b>") htmlString.Append(User.Identity.Name) htmlString.Append("<br><b>Authenticated With: </b>") htmlString.Append(User.Identity.AuthenticationType) htmlString.Append("<br><b>User ID: </b>") htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString()) htmlString.Append("<br><br>") End IfHow do i get the userid number, the primary key !?
christiandev
Star
8607 Points
1841 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 09, 2012 11:01 AM|LINK
If this is just the Standard IPrinciple, then you will only get the name. Are you trying to set up a custom provider?
Regards, Christiandev (@chrisdev80), MCPD Web (2 & 4) & MCTS Windows (www.ScoreDonkey.com)
siraero
Member
419 Points
604 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 09, 2012 11:09 AM|LINK
Hi
i need the user id aswell, and no i havent got a custom provider.
How can i get the Id !?
christiandev
Star
8607 Points
1841 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 09, 2012 11:12 AM|LINK
How does the user Authenticate? Forms / Windows ? Do you check against a DB table for the username and password ?
Regards, Christiandev (@chrisdev80), MCPD Web (2 & 4) & MCTS Windows (www.ScoreDonkey.com)
siraero
Member
419 Points
604 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 09, 2012 11:29 AM|LINK
hi.
Yes i do with Forms.
I do it like this
Global.asax
Public Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) If Request.IsAuthenticated Then Dim conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString) conn.Open() Dim cmd As New OleDbCommand("Select Groups.Name FROM ((Roles INNER JOIN Groups ON Groups.GroupID = Roles.GroupID) INNER JOIN Users ON USERS.UserID = Roles.UserID) WHERE Users.Username=@UserName", conn) cmd.Parameters.AddWithValue("@UserName", User.Identity.Name) Dim reader As OleDbDataReader = cmd.ExecuteReader() Dim roleList As New ArrayList() While reader.Read() roleList.Add(reader("Name")) End While Dim roleListArray As String() = DirectCast(roleList.ToArray(GetType(String)), String()) HttpContext.Current.User = New GenericPrincipal(User.Identity, roleListArray) reader.Close() conn.Close() End If End SubAnd then i have this on my Loginpage
Private Function ValidateUser(ByVal userName As String, ByVal passWord As String) As Boolean Dim conn As OleDbConnection Dim cmd As OleDbCommand Dim lookupPassword As String lookupPassword = Nothing ' Check for an invalid userName. ' userName must not be set to nothing and must be between one and 15 characters. If ((userName Is Nothing)) Then System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.") Return False End If If ((userName.Length = 0) Or (userName.Length > 15)) Then System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.") Return False End If ' Check for invalid passWord. ' passWord must not be set to nothing and must be between one and 25 characters. If (passWord Is Nothing) Then System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.") Return False End If If ((passWord.Length = 0) Or (passWord.Length > 25)) Then System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.") Return False End If Try ' Consult with your SQL Server administrator for an appropriate connection ' string to use to connect to your local SQL Server. conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString) conn.Open() ' Create SqlCommand to select pwd field from the users table given a supplied userName. cmd = New OleDbCommand("SELECT Password, Username FROM Users WHERE Username=@userName AND Password=@passWord", conn) cmd.Parameters.Add("@userName", OleDbType.VarChar, 25) cmd.Parameters("@userName").Value = userName cmd.Parameters.Add("@passWord", OleDbType.VarChar, 25) cmd.Parameters("@passWord").Value = passWord ' Execute command and fetch pwd field into lookupPassword string. lookupPassword = cmd.ExecuteScalar() ' Cleanup command and connection objects. cmd.Dispose() conn.Dispose() Catch ex As Exception ' Add error handling here for debugging. ' This error message should not be sent back to the caller. System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " & ex.Message) End Try ' If no password found, return false. If (lookupPassword Is Nothing) Then ' You could write failed login attempts here to the event log for additional security. Return False End If ' Compare lookupPassword and input passWord by using a case-sensitive comparison. Return (String.Compare(lookupPassword, passWord, False) = 0) End Function Private Sub submit_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.ServerClick If ValidateUser(txtUserName.Value, txtUserPass.Value) Then Dim tkt As FormsAuthenticationTicket Dim cookiestr As String Dim ck As HttpCookie tkt = New FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now(), DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data") cookiestr = FormsAuthentication.Encrypt(tkt) ck = New HttpCookie(FormsAuthentication.FormsCookieName(), cookiestr) If (chkPersistCookie.Checked) Then ck.Expires = tkt.Expiration ck.Path = FormsAuthentication.FormsCookiePath() Response.Cookies.Add(ck) Dim strRedirect As String strRedirect = Request("ReturnURL") If strRedirect <> "" Then Response.Redirect(strRedirect, True) Else strRedirect = "default.aspx" Response.Redirect(strRedirect, True) End If Else Session("logininfo") = "DBerror" Response.Redirect("login.aspx", True) End If End SubAnd then i have the first code in this thread on my default.aspx page.
Mayur Rathi
Member
31 Points
28 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 10, 2012 03:26 PM|LINK
Hi,
(I guess) You are not retreiving the userId from the database after successfull Verification of the Password.
If you are getting the UserId then you will have to store it in Applicationsession veriable. User.Identity does not have the field to store the UserId You can store it in AuthenticationType field of User.Identity but that will only benifit if you dont have to access authentication type for authentication.(In a case where you just have only one type of authentication.).
Ruchira
All-Star
43056 Points
7040 Posts
MVP
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 11, 2012 12:46 PM|LINK
Hello,
Try by changing the below line
To this
When you provide nothing for the GetUser() method, it will get the current user by default. So there is no need to pass User.Identity.Name for the GetUser method.
My Tech blog | My YouTube ChannelPlease 'Mark as Answer' if this post helps you.siraero
Member
419 Points
604 Posts
Re: How do i Get/Show the user ID in user.identity.name !?
Aug 11, 2012 03:31 PM|LINK
then i get this error System.NullReferenceException: for that line of code.