[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 776
  • Last Modified:

Active Directory & Username Login permissions

Dear Experts-Exchange,
 
I have been working on this project for many days without success and your help and solution is really much appreciative.
 
It's about Active Directory, username login permissions to view or not some asp.net web applications.
 
Please see code below:
 
Imports System.DirectoryServices

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
        Dim User As System.Security.Principal.IPrincipal
        User = System.Web.HttpContext.Current.User

        Dim username As String = "JBlake"
        Dim username1 As String = "ABaron"
        Dim username2 As String = "DDale"
        Dim username3 As String = "JPack"
        Dim username4 As String = "JDoe"

        Try

            If Not Roles.IsUserInRole(User.Identity.Name, "username, username1, username2, username3, username4") Then
                Response.Redirect("~/NotAuthorized.aspx", False)
            else
                 Response.Redirect("phonedirectory.aspx", false)
            End If

        Catch ex As Exception

        End Try

When username: JBlake, ABaron, DDale, JPack, JDoe (these are not allow to view a web application
called "phonedirectory") log in the "NotAutorized.aspx" doesn't display and but they are viewing the page where they are not
allowed to view it and also display an error message: The parameter 'roleName' must not contain commas. Parameter name: roleName.  
What am I doing wrong?

Hope you could help me on this.  Thanks much
0
slb2008
Asked:
slb2008
  • 18
  • 8
  • 6
  • +1
1 Solution
 
abkmaCommented:
I believe that because all of there names are included in the quote block that it is treating them all as one username.  I believe you can only pass one username anyways.  Also,  You would need to have it in the form of:

 If Not Roles.IsUserInRole(User.Identity.Name," & username & ")

else it will pass the literal string of "username" to the method.  If it were me I would put the unauthorized users into an array and then loop through lines each value to determine authorization and redirects.
0
 
naldiianCommented:
I am not sure this methodology makes a lot of sense to begin with. After generating a security prinicipal object from the login context user, you then do a comparison against a text attribute to check for access control on the site, which really defeats the point of creating a security pricipal object at all.
It makes more sense to use standard ACL comparison for the site or component you are trying to restrict, or at least use a security group on the server or in AD that holds the users for which you wish to deny access for comparison. Then you can compare group membership of the user at login, and if they are not in that group they get access - at least then you can add and remove people in the restricted group as needed.
Doesn't that make sense, and seem like a better option?
0
 
slb2008Author Commented:
Thanks Abkma for the quick response.
Please could you show me a line of code how to put the unauthorized users into an array and loop through lines each to determine authorization and redirects.
 
 
 
0
Easily manage email signatures in Office 365

Managing email signatures in Office 365 can be a challenging task if you don't have the right tool. CodeTwo Email Signatures for Office 365 will help you implement a unified email signature look, no matter what email client is used by users. Test it for free!

 
abkmaCommented:
naladiian,

You have a valid point.  of course another alternative would be to put these users into their own role and deny that role rights to the page.  In addition if you were using a site map based menu you could keep them from even having the page available to them on the menu.
0
 
abkmaCommented:
I don't do a lot of arrays in Visual Studio.  However,I believe it would function similar to this:
Imports System.DirectoryServices

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
        Dim User As System.Security.Principal.IPrincipal
        User = System.Web.HttpContext.Current.User
 
        Dim username(4) AS String
		    username(0) = "JBlake"
            username(1) = "ABaron"
            username(2) = "DDale"
            username(3) = "JPack"
            username(4) = "JDoe"
		Dim i = 0
		
			For i = 0 to 4 
				Try

				If Not Roles.IsUserInRole(User.Identity.Name,username(i)) Then
					Response.Redirect("~/NotAuthorized.aspx", False)
				else
					Response.Redirect("phonedirectory.aspx", false)
				End If
	
			Catch ex As Exception

			End Try
			i=i+1
			Next

Open in new window

0
 
slb2008Author Commented:
Thanks naldiian for the quick response.
It was very interesting to ready your comments.  In the active directory I have a lot groups  for example group A with names :  john, roy, mark, kate.  in group B:  paul, roy, anne, kate.  in group c: kate, john, david, april... I have been try to use this following code :

Dim RequiredGroup As String = "A"

If Not Roles.IsUserInRole(User.Identity.Name, "RequiredGroup") Then
Response.Redirect("~/NotAuthorized.aspx", False)
            else
                 Response.Redirect("phonedirectory.aspx", false)
            End If

But I don't want john and mark to view the web application....only roy and kate are allowed to view it and edit the data....  Also I don't want to add or remove users in the restricted group.
 
0
 
slb2008Author Commented:
Abkma, the code you sent was pretty quick.  I am going to try and test it .  I'll let you know.  thanks.
After reading your comments to nalddian, I agree naldiian had a good point, but you know I have a intranet with different web applications, and every active directory user who login can view all the pages, and I am trying to figure out the best way for each username to have some permissions or not using some lines of Visual basic code, since  I don't have rights or access to the active directory to make these users into their own role and deny that role rights to the page.
 
0
 
slb2008Author Commented:
abkma,  
I tried your line of code, doesn't work well because...I asked an username: Jblake  to login in his workstation and after he logged in display the following message redirect to "NotAuthorized.aspx".  Later I asked another username who the name is not in the line code :  username is: AThompson,  after she logged in,  redirects to the "NotAuthorized.aspx" and not to "phonedirectory.aspx".
 
0
 
abkmaCommented:
I wonder if something like the following might work.  I did notice a problem with your original logic in that you are basically using Roles.IsUserInRole(username,username) and really what we are after here is Roles.IsUserInRole(username,role).  There was also a flaw in my logic in that a user could be redirected out of the loop before processing all of the prohibited names.  I've added a flag value in an attemp to deal with that.

Imports System.DirectoryServices

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
        Dim User As System.Security.Principal.IPrincipal
        User = System.Web.HttpContext.Current.User
 
        Dim username(4) AS String
            username(0) = "JBlake"
            username(1) = "ABaron"
            username(2) = "DDale"
            username(3) = "JPack"
            username(4) = "JDoe"
        Dim i AS integer = 0
		Dim redFlag as Boolean = False
                
                        For i = 0 to 4 
							Try
								IF User.Identity.Name = username(i) THEN redFlag = TRUE 
									ELSE redFlag = FALSE 
								End IF
							Catch ex As Exception
                        End Try
                        i=i+1
                        Next
						
						If redFlag = True THEN Response.Redirect("~/NotAuthorized.aspx", False)
							ELSE IF Roles.IsUserInRole(User.Identity.Name,"Desired_Role") Then
								Response.Redirect("phonedirectory.aspx", false)
							End IF
						End If

Open in new window

0
 
slb2008Author Commented:
Abkama,
I tried it and still not working..  There is a line of code shows  

Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
Dim username(4) As String

username(0) = "JBlake"
username(1) = "ABaron"
username(2) = "DDale"
username(3) = "JPack"
username(4) = "JDoe"
Dim i As Integer = 0
Dim redFlag As Boolean = False
For i = 0 To 4
Try
If User.Identity.Name = username(i) Then
redFlag = True
Else : redFlag = False    <------------------------------------------------  Why after Else shows two dots ??
End If
Catch ex As Exception
End Try
i = i + 1
Next
If redFlag = True Then
Response.Redirect("~/NotAuthorized.aspx", False)
ElseIf Roles.IsUserInRole(User.Identity.Name, "Desired_Role") Then    <--------------------   why Desired_Role ?
Response.Redirect("phonedirectory.aspx", False)
End If

When the username Jblake logins his redflag is true but goes to  ElseIf Roles.IsUserInRole(User.Identity.Name, "Desired_Role") Then    goes to end if.  
Doesn't go to Response.Redirect("~/NotAuthorized.aspx", False)

 
0
 
abkmaCommented:
It puts the two dots in if you put your else action on the same line as the else keyword.  If you were to move the redFlag = False down to the next line it would go away.  The "Desired_Role" needs to be changed to whatever role you were originally going to check for.  If these are the only excluded users you could remove the use of the Roles.IsUserInRole method.  

What happens for users whom are not in this list?  Is there redFlag = FALSE?  Do they get redirected?  You could change the end to:

If redFlag = True Then
Response.Redirect("~/NotAuthorized.aspx", False)
End If
if redFlag = False Then
    If Roles.IsUserInRole(User.Identity.Name, "Desired_Role") Then
                  Response.Redirect("phonedirectory.aspx", False)
    End if
    Else:  Response.Redirect("~/NotAuthorized.aspx", False)
End If

I'm wondering if he didn't redirect once he hit the redirection because the response.redirect is set to false.  I don't usually use the  endResponse Boolean at the end.  But my understanding from my reading would be that the False may be telling the code to continue processing the rest of the code on the page.  I would generally just use Response.Redirect("~/NotAuthorized.aspx").  I'm not sure if that is a poor practice, but it is how I typically do it.
0
 
slb2008Author Commented:
Abkma,  I'll test it later.  I'll be in in hour.  thanks.
0
 
slb2008Author Commented:
abkama,
Still the same. Username jblake goes to phonedirectory.aspx.  In the line of code never gets redflag = true and goes to if redflag = false then phonedirectory.aspx.
After debugging the lines of code, I could see when the username jblake is logged in reads username (0), username (1), username (2).... later goes if user.Identity = username (i)  (is 0) then goes else : redflag = false...  I was wondering why if the username is 0 never goes to redflag = true...  You think is the array or the loop?
0
 
slb2008Author Commented:
Abkama,
I am very familiar with the links you sent me.  I have everyhing in my project with LDAPAutehtication.vb, globals.vb, web.config, activeDirectory to autenticate users to asp.net website, cookies ticket.... using vb.net...I don't have anything to add....except a good real-world solution and try to figure out what the best way when Active Directory username logs in have not authorization to view  the page...I have been try using Active Directory groups/users in this following code that works but ...there are some usernames that belongs in the group I don't want them to allow to view the pages.
 
 Dim RequiredGroup As String = "ABS"
Try
'If User.IsInRole("ABS") Then
' 'End If
If Roles.IsUserInRole(User.Identity.Name, "RequiredGroup") Then
Response.Redirect("/NotAuthorized.aspx", False)
else
Response.Redirect("/phonedirectory.aspx", False)
' End If
Catch ex As Exception
' End Try
'End If
'Return
 
0
 
CodeCruiserCommented:
Abkama,

I am very familiar with the links you sent me.

-------------------------------------------------------------------------------


I think you misread user name!
0
 
slb2008Author Commented:
I am so sorry codecruiser.  Yes , I misread the username.  Have you been following up my comments?  Do have any ideas if you could help me despite somes links you sent me that I am very familiar with...  Thanks.
0
 
CodeCruiserCommented:
Yes I read the whole thread. But the trouble in such a situation is that you understand the full project so we can not just give you a piece of code to put in the project. The reason I pasted the links was that I was hoping you may be able to pick some missing piece of this jigsaw from those working examples.
0
 
slb2008Author Commented:
CodeCruiser, you would like  to receive all the code I have been working so you can see.  I will attached each code in word file for you to review.  let me know.  thanks
0
 
CodeCruiserCommented:
Yeah attach the code.
0
 
CodeCruiserCommented:
But i would not be able to see it today (bed time now)
0
 
slb2008Author Commented:
In few minutes I am going to attach the code file for your review .and  let me know by tomorrow. thanks.
0
 
slb2008Author Commented:
CodeCruiser,
Please see the attached file in word for your review.  thanks

CODE.doc
0
 
abkmaCommented:
I did some poking around tonight with some existing code that does a similar process and rediscovered that case does matter.  You will want to make sure that the case of your user names stated in the code match the case that they are stored in Active directory.  I would change the names in the code to lower case  and then change User.Identity.Name to LCASE(User.Identity.Name ).  I suspect that is why the redFlag is not getting set to TRUE.  
0
 
slb2008Author Commented:
Abkma,
 I was wondering why the redflag was not getting set to true.  It was always to getting  False redflag.  I will check out and I let know tomorrow.  Thanks.
0
 
CodeCruiserCommented:
So the problem seems to be this line

If User.Identity.Name = username(i) Then

Set a breakpoint to see what's the value of User.Identity.Name.

Also, to avoid problems with character case, try to always compare strings in lower case.

If User.Identity.Name.ToLower() = username(i).ToLower() Then
0
 
slb2008Author Commented:
Hi CodeCruiser & abkma,
Sorry the delay.  I checked and I put the lower case.  see the code below:
Dim User As System.Security.Principal.IPrincipal        
User = System.Web.HttpContext.Current.User          
Dim username(4) AS String            
username(0) = "jblake"            
username(1) = "abaron"            
username(2) = "ddale"            
username(3) = "jpack"            
username(4) = "jdoe"
Dim i = 0
For i = 0 To 4
Try
 
'If User.Identity.Name.ToLower() = username(i).ToLower Then
If Not Roles.IsUserInRole(User.Identity.Name.ToLower, username(i)) Then
Response.Redirect("~/NotAuthorized.aspx")
Else
Response.Redirect("")
End If
Catch ex As Exception
End Try
i = i + 1
Next
I tried and test it and it's almost there.  but how come my name sbaker is not in username in the line code, and I am denied to view the page.
After debugging, I follow the debugg and could see if the username is abaron, first check the username (0), later comes username (2), and username (4), but never reads the
username (1), username(3)... !!!!!  When abaron is logged he can view the page ????  strange.  If it's me I received a message "not authorized to view the page"????
There is a little problem is not working correctly.
 
0
 
abkmaCommented:
The line 'If User.Identity.Name.ToLower() = username(i).ToLower Then' appears to me to be commented out.  You're still not putting a "role" (in your case AD group) into the IsUserRole but rather two user names.  So the code is saying if you're username is not in role 'jblake' then redirect you.

I still would maintain that you need the flags else user number two will be redirected on his first pass through the loop.

0
 
slb2008Author Commented:
Please review the code and tell what I am doing wrong:

Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
Dim username(5) As String

Dim username(4) AS String            
username(0) = "jblake"            
username(1) = "abaron"            
username(2) = "ddale"            
username(3) = "jpack"            
username(4) = "jdoe"

Dim i = 0
Dim redFlag As Boolean = False
For i = 0 To 5
Try

If User.Identity.Name = username(i).ToLower  Then
If User.Identity.Name.ToLower() = username(i).ToLower Then
redFlag = True
Else : redFlag = False
End If
 
If redFlag = True Then
Response.Redirect("~/NotAuthorized.aspx", False)
ElseIf Roles.IsUserInRole(User.Identity.Name, "Desired_Role") Then
'Response.Redirect("phonedirectory.aspx", False)
End If
Catch ex As Exception
End Try
i = i + 1
Next
 
Please correct it.  thanks.
0
 
abkmaCommented:
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User

Dim username(4) AS String            
username(0) = "jblake"            
username(1) = "abaron"            
username(2) = "ddale"            
username(3) = "jpack"            
username(4) = "jdoe"

Dim i = 0
Dim redFlag As Boolean = False
For i = 0 To 5
    Try
        If User.Identity.Name.ToLower() = username(i).ToLower Then
            redFlag = True
        End If
    Catch ex As Exception
    End Try
    i = i + 1
Next
 
If redFlag = True Then
    Response.Redirect("~/NotAuthorized.aspx")
End IF

if Roles.IsUserInRole(AD_GROUP) Then  <-------If want members of a AD group redirected
    Response.Redirect("phonedirectory.aspx")      you must put a string here representing a
End If                                                                             group name.  Otherwise you can redirect
                                                                                        everyone whom hasn't already been
0
 
slb2008Author Commented:
What do you mean to put a string to representing a group name.  I have a group called "WorkerUsers" that contains a complete list of user that are member of that group includes jblake, abaron, ddale, jpack, jdoe...   and the username jdoe logged in and the final result was this username jdoe went to phonedirectory.aspx which is not right.  I don't know...I am feelling a little frustated with behavior of the code... but is not working correctly...
 
0
 
slb2008Author Commented:
Abkma, Thanks for your help...I didn't receive any message from you....I am going to close this thread giving you 500 points.  Thanks for sharing with me with your code that helped me  for future projects.  I have a new question that I am going to publish in few minutes  and my question will be  "Active Directory - SQL Apps permissions"
 
Thanks
0
 
slb2008Author Commented:
Pretty close to be a good solution...
0

Featured Post

Free tool for managing users' photos in Office 365

Easily upload multiple users’ photos to Office 365. Manage them with an intuitive GUI and use handy built-in cropping and resizing options. Link photos with users based on Azure AD attributes. Free tool!

  • 18
  • 8
  • 6
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now