Asp.Net Identity PasswordHasher not hashing - asp.net

The following is the code I am using to effect a password change. I am following the pattern in the Manage.aspx page that comes in the Asp>net web application template for changing the password.
Using that method does NOT hash the password, which is odd since the registration DOES hash it. So, i added the passwordhasher. The problem is the IdentityResult is returning false every time even though the three parameters are correct. Every code line produces the correct result until this line, which produces false every time
UPDATE: The usr.ID in the ChangePassword method is the culprit. The username passed in is the ONLY entry in the users table BUT the usr.Id doesn't match the users id in the table. How is it even retrieving an id?
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
Here is the method
Private Sub btnSubmitPasswordChange_Click(sender As Object, e As EventArgs) Handles btnSubmitPasswordChange.Click
Dim db As New MySQLDatabase("MyConnString")
Dim ut As New UserTable(db)
Dim username As String = EncryptDecrypt.DecryptQueryString(Request.QueryString("rtu"))
Dim userId As String = ut.GetUserId(username)
Dim currentPass As String = ut.GetPasswordHash(userId)
Dim usr As New IdentityUser(username)
Dim manager = New UserManager()
manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False}
Dim phasher As New PasswordHasher
Dim newhash As String = phasher.HashPassword(Password.Text)
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
If result.Succeeded Then
Response.Redirect("~/Account/Login.aspx")
Else
lblResetSuccess.Text = "Password change failed!"
End If
Dim changed As Integer = ut.SetPasswordHash(userId, newhash)
End Sub

Related

Login, Email and Password Validation not working correctly with SQL tables Vb

what I've been trying to do is grab the username, password and email from my sql table and validate it through my login form on vb.net. So, when I type in the username, password, and email in the form it should tell me if the login was successful or not. However, Whenever I type in the username, password and email from the sql table I created (MembershipInfo) into my login form I keep getting the error "Username, Password or Email is not correct, please try again" even though I know the username, password and email are correct (currently looking at it). I've tried multiple videos on youtube and even some solutions on here as well as on other sites, but nothing works. Can someone please tell me what I'm doing wrong? Here is my vb code:
Imports System.Data
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Public Shared conS As String = "Server= ; Database=Yourdatabase ;Trusted_Connection=Yes;"
Public Shared con As SqlConnection = New SqlConnection(conS)
Protected Sub TextBox8_TextChanged(sender As Object, e As EventArgs) Handles TextBox8.TextChanged
End Sub
Protected Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim un, pw, em, dbUN, dbPW, dbEM As String
un = TextBox7.Text
pw = TextBox8.Text
em = TextBox9.Text
Dim cmdUN As New SqlCommand("Select UserName from MembershipInfo Where Username = #p1", con)
With cmdUN.Parameters
.Clear()
.AddWithValue("#p1", un)
End With
Dim cmdPW As New SqlCommand("Select Pass from MembershipInfo Where UserName = #p1", con)
With cmdPW.Parameters
.Clear()
.AddWithValue("#p1", un)
End With
Dim cmdEM As New SqlCommand("Select Email from MembershipInfo where UserName = #p1", con)
With cmdEM.Parameters
.Clear()
.AddWithValue("#p1", un)
End With
Try
If con.State = ConnectionState.Closed Then con.Open()
dbUN = cmdUN.ExecuteScalar
dbPW = cmdPW.ExecuteScalar
dbEM = cmdEM.ExecuteScalar
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
End Try
If un = dbUN And pw = dbPW And em = dbEM Then
MsgBox("Login Sucessful", vbExclamation, "Welcome")
Else
MsgBox("Username, Password or Email does not match, please try again", vbExclamation, "Error")
End If
End Sub
End Class
And here is my sql code (I don't know if its needed but its better to be cautious):
Create Table MembershipInfo
(
MembershipID INT NOT NULL PRIMARY KEY Identity(1,1),
Firstname varchar(50) not null,
Lastname varchar(50) not null,
UserName char(50) not null,
Pass char(50) not null,
Email char(50) not null
);
INSERT INTO MembershipInfo VALUES
('Jaycie', 'Adams', 'Imtotiredforthis', 'Golden1#1', 'JAdams2#gmail.com'),
('Bret', 'Steidinger', 'HellowWord', 'Wowwzaa12#', 'Reynolds13#gmail.com'),
('Rebecca', 'Wong', 'SomethingSomething1#1', 'Outofideas11', 'ReWong34#gmail.com'),
('Ciel', 'Phantomhive', 'DownwiththeQeen1#1', 'FellintomytrapWaha22#', 'CielPhantom22#gmail.com'),
('Jane', 'Borden', 'TiredTM4#1', 'Justtakemypasswordalready#3', 'JBorden56#gmail.com');
Select * from MembershipInfo;
Do not declare Connections outside of the method where they are used. This is true of any database object that exposes a Dispose method.
Why not just use the email as the username.
These lines from Create Table will require fixed length strings. Not at all what you want. Stick to varchar or nvarchar.
UserName char(50) not null,
Pass char(50) not null,
Email char(50) not null
I am not familiar with the Insert syntax that you used.
Using blocks handle closing and disposing objects even if there is an error.
Use the Add method of the Parameters collection for Sql Server. http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
Try to use meaningful names for you controls.
Protected Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If IsLoginValid(txtEmail.Text, txtPassword.Text) Then
MsgBox("Login Sucessful", vbExclamation, "Welcome")
Else
MsgBox("Username, Password or Email does not match, please try again", vbExclamation, "Error")
End If
End Sub
Private Function IsLoginValid(email As String, pword As String) As Boolean
Dim RetVal As Integer
Using cn As New SqlConnection(conS),
cmd As New SqlCommand("Select Count(*) From MembershipInfo Where Email = #Name And Pass = #Pass")
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = email
cmd.Parameters.Add("#Pass", SqlDbType.VarChar, 50).Value = pword
cn.Open()
RetVal = CInt(cmd.ExecuteScalar)
End Using
If RetVal = 1 Then
Return True
End If
Return False
End Function
The worst part of this code is that you are storing passwords as plain text. Passwords should be salted and hashed before storage.

Pull Outlook OfficeLocation using Alias

While referencing Return list of names and email address from outlook to vb.net listbox I am trying to fill in a ASP:Textbox with the Office Location of the user.
Currently I pull the current logged in user. The user's username on their PC is also their Outlook Alias. With that being said, I am trying to use the username/Alias to pull the Office location within Outlook. I currently have the following issue with my coding:
'get logged in user(works)
Dim username As String
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
username = User.Identity.Name.Substring(3)
'Office Location of User
Dim itemx As String
'Create an Outlook application.
Dim oApp As Outlook._Application = New Outlook.Application()
'Get the MAPI namespace.
Dim oNS As Outlook.NameSpace = oApp.Session
'Get the Global Address List.
Dim oALs As Outlook.AddressLists = oNS.AddressLists
Dim oGal As Outlook.AddressList = oALs.Item(1)
'Get all the entries.
Dim oEntries As Outlook.AddressEntries = oGal.AddressEntries
For Each entry In oEntries
If oEntries.GetExchangeUser.Alias = username Then
itemx = oEntries.GetExchangeUser.OfficeLocation
End If
Next
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article in MSDN.
As a workaround you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information. Or just a low-level API on which Outlook is based on - Extended MAPI.
Main thing that I learned was that you need a password and username to access outlook.
Get user ID from PC (Alias for Outlook):
Dim usernameQuery As String
Dim UserQ As System.Security.Principal.IPrincipal
UserQ = System.Web.HttpContext.Current.User
usernameQuery = User.Identity.Name.Substring(3).ToUpper
UserText.Text = usernameQuery
Then:
Call function like so:
'outlook office location **************************************************
LocationText.Text = GetUserInfo(usernameQuery, "physicaldeliveryofficename")
'OTHER OPTIONS YOU CAN QUERY
'Dim svalue As String = GetUserInfo(UserAccount, "mail")
'Dim svalue As String = GetUserInfo(UserAccount, "givenName")
'Dim svalue As String = GetUserInfo(UserAccount, "sn")
'Dim svalue As String = GetUserInfo(UserAccount, "l")
'Dim svalue As String = GetUserInfo(UserAccount, "st")
'Dim svalue As String = GetUserInfo(UserAccount, "streetAddress")
'Dim svalue As String = GetUserInfo(UserAccount, "postalCode")
'Dim svalue As String = GetUserInfo(UserAccount, "telephoneNumber")
'Dim svalue As String = GetUserInfo(useraccount, "co")
'txtName.Text = GetUserInfo(UserAccount, "givenName") & " " & GetUserInfo(UserAccount, "sn")
'txtPhone.Text = GetUserInfo(UserAccount, "telephoneNumber")
'********************************************************************************
Function:
Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
Try
Dim sPath As String = "LDAP://"full_path"/DC="path_value",DC="path_value",DC="path_value" "
Dim SamAccount As String = Right(inSAM, Len(inSAM) - InStr(inSAM, "\"))
Dim myDirectory As New DirectoryEntry(sPath, "username", "password") 'pass the user account and password for your Enterprise admin.
Dim mySearcher As New DirectorySearcher(myDirectory)
Dim mySearchResultColl As SearchResultCollection
Dim mySearchResult As SearchResult
Dim myResultPropColl As ResultPropertyCollection
Dim myResultPropValueColl As ResultPropertyValueCollection
'Build LDAP query
mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")
mySearchResultColl = mySearcher.FindAll()
'I expect only one user from search result
Select Case mySearchResultColl.Count
Case 0
Return "Null"
Exit Function
Case Is > 1
Return "Null"
Exit Function
End Select
'Get the search result from the collection
mySearchResult = mySearchResultColl.Item(0)
''Get the Properites, they contain the usefull info
myResultPropColl = mySearchResult.Properties
If myResultPropColl.Contains(inType) Then
myResultPropValueColl = myResultPropColl.Item(inType)
Return CStr(myResultPropValueColl.Item(0))
End If
'displayname, mail
'Retrieve from the properties collection the display name and email of the user
'myResultPropValueColl = myResultPropColl.Item(inType)
'Return CStr(myResultPropValueColl.Item(0))
Catch ex As System.Exception
End Try
Return "Null"
End Function
FYI-
full_path = "value"."value"."value"

Server Transfer with Session

I have a site contains login page and Default this is part of my code when trying to server transfer from login to Default
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim wrapper As New Simple3Des(MyKey)
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim user As String = wrapper.EncryptData(userNamePlan)
Dim pass As String = wrapper.EncryptData(PasswordPlan)
Session("un") = user.ToString
Session("pw") = PassWorldTextBox.Text
Server.Transfer("Default.aspx")
...
if I change Session("un") = user.ToString to UserNameTextBox.text it will transfer, if not, fail. And no Error Messages. Don't know why
I hope user is already string..Then you can write..
System.Web.HttpContext.Current.Session(“un”)=user;

Get Data from One Table and Insert to Another Via Form Submission

How do I get a UserID from one database table (Users) to be inserted into another table (Ticket)? Both columns in each table has the same datatype (int). Please take a look:
Users
UserID
UserName
Password
FirstName
LastName
Email
Updated
Deleted
Ticket
TicketID
DateCreated
UserIDNum FK
FullName
Email
Subject
Message
Deleted
These are all of the codes involved:
Partial Public Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
MaintainScrollPositionOnPostBack = True
SetFocus(helpTopicDDL)
Else
SetFocus(fullNameTXTBOX)
End If
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select * from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#Username", Data.SqlDbType.VarChar)
cmdCheckEmail.Parameters.Add("#Username", SqlDbType.VarChar)
cmdCheckEmail.Parameters.Item("#Username").Value = Session("Ticket")
Dim obj As Object = cmdCheckEmail.ExecuteScalar()
If obj IsNot Nothing Then
mailLBL.Text = Convert.ToString(obj)
End If
End If
sConnection.Close()
End Sub
Protected Sub submitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitBTN.Click
Dim sdConnection As String = ConfigurationManager.AppSettings("TrackTicketsConnectionString2")
Dim iRowCount As Integer
Dim cmdInsertTicket As New Data.SqlClient.SqlCommand
Dim conticket As New Data.SqlClient.SqlConnection
conticket.ConnectionString = sdConnection
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "Insert Into Ticket " _
& "( DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values( #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
'Dim appUserName As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.NVarChar)
'cmdInsertTicket.Parameters.Add(appUserName)
'cmdInsertTicket.Parameters.Item("#UserName").Value = User.Identity.Name
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
Dim appFullName As New Data.SqlClient.SqlParameter("#FullName", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appFullName)
cmdInsertTicket.Parameters.Item("#FullName").Value = fullNameTXTBOX.Text
Dim appEmail As New Data.SqlClient.SqlParameter("#Email", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appEmail)
cmdInsertTicket.Parameters.Item("#Email").Value = emailAddTXTBOX.Text
Dim appTicketType As New Data.SqlClient.SqlParameter("#TicketType", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appTicketType)
cmdInsertTicket.Parameters.Item("#TicketType").Value = helpTopicDDL.SelectedValue
Dim appSubject As New Data.SqlClient.SqlParameter("#Subject", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appSubject)
cmdInsertTicket.Parameters.Item("#Subject").Value = subjectTXTBOX.Text
Dim appMessage As New Data.SqlClient.SqlParameter("#Message", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appMessage)
cmdInsertTicket.Parameters.Item("#Message").Value = messageTXTBOX.Text
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
conticket.Open()
Try
iRowCount = cmdInsertTicket.ExecuteScalar()
statusLBL.Text = "Ticket has been submitted successfully."
Catch
statusLBL.Text = "Ticket has not been submitted. Please try again."
End Try
conticket.Close()
End Sub
What I really wanted is for a person's UserID to be stored in Ticket table after he has logged in to fill out a form and submitted it. I'm at a loss in how to pull the data from Users table to insert into Ticket table. Any help is much appreciated as I'm still learning.
EDIT:
Inserting the UserID into the Tickets table when adding a record first requires that you have access to the UserID value. You then need to pass this value in your INSERT statement.
Looks like we first need to retrieve the UserId. Since you are using FormsAuthentication we can retrieve the UserName from the User.Identity.Name object and use that as the value in our first query to retrieve the UserId.
Dim cmdS As String = "Select [UserID] from Users Where Deleted='N' AND UserName=#UserName"
Dim cmdGetUserId As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.VarChar)
cmdGetUserId.Parameters.Add("#UserName", SqlDbType.VarChar)
cmdGetUserId.Parameters.Item("#UserName").Value = User.Identity.Name
Dim obj As Object = cmdGetUserId.ExecuteScalar
Dim myUserId As Integer = Integer.Parse(obj)
Now that we have the UserId value for our current user we can modify our INSERT statement and parameters.
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "INSERT INTO Ticket " _
& "(UserID, DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values(#UserID, #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
Dim appUserId As New Data.SqlClient.SqlParameter("#UserID", Data.SqlDbType.Int)
cmdInsertTicket.Parameters.Add(appUserId)
cmdInsertTicket.Parameters.Item("#UserID").Value = myUserId
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
...
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
You can access authentication information through the User.Identity object once the user has been authenticated. Might also want to think about implementing a custom IIdentity class to store the UserID if you will need access to it often. Here's a good MSDN article about Custom Authentication: http://msdn.microsoft.com/en-us/library/ms172766(v=vs.80).aspx
UPDATE:
In regards to the comment below, you are retrieving the UserID because the SqlCommand is being executed with the ExecuteScalar method which returns the value of the first column of the first row. I would recommend taking a closer look at the SqlCommand object: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx and this ADO.NET primer on MSDN: http://msdn.microsoft.com/en-us/library/e80y5yhx(v=vs.80).aspx

Find If User is Member of Active Directory Group ASP.NET VB?

I am using Active Directory to authenticate users for an intranet site. I would like to refine the users that are authenticated based on the group they are in in Active Directory. Can someone show me or point me to directions on how to find what groups a user is in in ASP.NET 4.0 (VB)?
I realize this post is quite old but I thought I might update it with processes I am using. (ASP.Net 4.0, VB)
If using integrated windows security, on a domain.
Page.User.IsInRole("domain\GroupName") will check to see if the authenticated user is a member of the specified group.
If you would like to check another users group membership other than the authenticated user.
Two stage for checking multiple groups with the same user principal:
Dim MyPrincipal As New System.Security.Principal.WindowsPrincipal _
(New System.Security.Principal.WindowsIdentity("UserID"))
Dim blnValid1 As Boolean = MyPrincipal.IsInRole("domain\GroupName")
Single stage for checkin a single group:
Dim blnValid2 As Boolean = New System.Security.Principal.WindowsPrincipal _
(New System.Security.Principal.WindowsIdentity("userID")).IsInRole("domain\GroupName")
NOTE:: The IsInRole method does work with nested groups. If you have a top level group with a sub group that is a member, and the user is a member of the sub group.
I think I have the ultimate function to get all AD groups of an user included nested groups without explicit recursion:
Imports System.Security.Principal
Private Function GetGroups(userName As String) As List(Of String)
Dim result As New List(Of String)
Dim wi As WindowsIdentity = New WindowsIdentity(userName)
For Each group As IdentityReference In wi.Groups
Try
result.Add(group.Translate(GetType(NTAccount)).ToString())
Catch ex As Exception
End Try
Next
result.Sort()
Return result
End Function
So just use GetGroups("userID"). Because this approach uses the SID of the user, no explicit LDAP call is done. If you use your own user name it will use the cached credentials and so this function is very fast.
The Try Catch is necessary because in large companyies the AD is so big that some SIDs are getting lost in space.
For those who may be interested, this is how I ended up coding it:
Dim ID As FormsIdentity = DirectCast(User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = ID.Ticket
Dim adTicketID As String = ticket.Name
Dim adSearch As New DirectorySearcher
adSearch.Filter = ("(userPrincipalName=" & adTicketID & ")")
Dim adResults = adSearch.FindOne.Path
Dim adResultsDirectory As New DirectoryEntry(adResults)
Dim found As Boolean = False
For Each entry In adResultsDirectory.Properties("memberOf")
Response.Write(entry)
Response.Write("<br/>")
If entry = "CN=GroupName,CN=UserGroup,DC=my,DC=domain,DC=com" Then
found = True
End If
Next
If Not (found) Then
Response.Redirect("login.aspx")
End If
I found this here.
''' <summary>
''' Function to return all the groups the user is a member od
''' </summary>
''' <param name="_path">Path to bind to the AD</param>
''' <param name="username">Username of the user</param>
''' <param name="password">password of the user</param>
Private Function GetGroups(ByVal _path As String, ByVal username As String, _
ByVal password As String) As Collection
Dim Groups As New Collection
Dim dirEntry As New _
System.DirectoryServices.DirectoryEntry(_path, username, password)
Dim dirSearcher As New DirectorySearcher(dirEntry)
dirSearcher.Filter = String.Format("(sAMAccountName={0}))", username)
dirSearcher.PropertiesToLoad.Add("memberOf")
Dim propCount As Integer
Try
Dim dirSearchResults As SearchResult = dirSearcher.FindOne()
propCount = dirSearchResults.Properties("memberOf").Count
Dim dn As String
Dim equalsIndex As String
Dim commaIndex As String
For i As Integer = 0 To propCount - 1
dn = dirSearchResults.Properties("memberOf")(i)
equalsIndex = dn.IndexOf("=", 1)
commaIndex = dn.IndexOf(",", 1)
If equalsIndex = -1 Then
Return Nothing
End If
If Not Groups.Contains(dn.Substring((equalsIndex + 1), _
(commaIndex - equalsIndex) - 1)) Then
Groups.Add(dn.Substring((equalsIndex + 1), & _
(commaIndex - equalsIndex) - 1))
End If
Next
Catch ex As Exception
If ex.GetType Is GetType(System.NullReferenceException) Then
MessageBox.Show("Selected user isn't a member of any groups " & _
"at this time.", "No groups listed", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
'they are still a good user just does not
'have a "memberOf" attribute so it errors out.
'code to do something else here if you want
Else
MessageBox.Show(ex.Message.ToString, "Search Error", & _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Try
Return Groups
End Function
End Class
To just check if a user is member of a group including sub-groups just use:
Public Function IsInGroup(ByVal objectName As String, groupName As String) As Boolean
Try
return New WindowsPrincipal(New WindowsIdentity(objectName)).IsInRole(groupName))
Catch ex As Exception
End Try
Return False
End Function

Resources