• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • Last Modified:

Current user Active Directory

I have a network with Active Directory and I want to response.write (which means store in a session) the current logged in user to a Intranet webpage. If the user is logged in with DOMAIN\UserN on windows logon, that username should be showed on the webpage.

If I got that username, I can also take out other stored variables on the user? Like Telephone Number?
Maybe also extensionAttribute1 from Exchange Advanced tab on the user? (not important)



There exist a huge list of answers on this question but nobody seems to fit in, really complex or does not works as I want. In a Access database I've use a simple solution as this below, but does of course not work in ASP.NET environment.

    Dim cmdBaseCon As New ADODB.Command
    With cmdBaseCon
        .ActiveConnection = CurrentProject.BaseConnectionString
        .CommandType = adCmdStoredProc
        .CommandText = "proc_GetCurrentUserSS"
        .Parameters(0).Direction = adParamReturnValue
        .Parameters(1).Direction = adParamOutput
        .Execute
        GetCurrentUser = Nz(.Parameters(1), "No username returned")
    End With
0
dingir
Asked:
dingir
  • 7
  • 5
  • 2
1 Solution
 
DhaestCommented:
To get the current username form active directory, you can easily do this:

With this userEntry.Properties["fullname"].Value, you can get more properties if you want
(the code to get all the properties is also below)
private string GetUserName()    
{
        string retVal = string.Empty;
        //Pull the username out of the domain\user string.
          retVal = Page.User.Identity.Name.Split('\\')[1];
          DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + userName +",User");
        retVal = (string)userEntry.Properties["fullname"].Value;
        return retVal;
     }
 
 
 
 
public static void PrintDirectoryEntryProperties(System.DirectoryServices.DirectoryEntry entry, string sComment)
 
        { 
 
            // loop through all the properties and get the key for each
 
            foreach (string Key in entry.Properties.PropertyNames)
 
            {
 
                string sPropertyValues = String.Empty;
 
                // now loop through all the values in the property;
 
                // can be a multi-value property
 
                foreach (object Value in entry.Properties[Key])
 
                    sPropertyValues += Convert.ToString(Value) + ";";
 
                // cut off the separator at the end of the value list
 
                sPropertyValues = sPropertyValues.Substring(0, sPropertyValues.Length - 1);
 
                // now add the property info to the property list
 
                Debug.WriteLine(Key + "=" + sPropertyValues);
 
            }
 
        }

Open in new window

0
 
dingirAuthor Commented:
Hi,

 Thank's for answer. I forgot to tell that I need a VB Solution. Possible?
0
 
DhaestCommented:
I tried to translate the functions above...
Private Function GetUserName() As String 
    Dim retVal As String = String.Empty 
    'Pull the username out of the domain\user string. 
    retVal = Page.User.Identity.Name.Split("\"C)(1) 
    Dim userEntry As New DirectoryEntry("WinNT://" + userName + ",User") 
    retVal = DirectCast(userEntry.Properties("fullname").Value, String) 
    Return retVal 
End Function 
 
 
 
Public Shared Sub PrintDirectoryEntryProperties(ByVal entry As System.DirectoryServices.DirectoryEntry, ByVal sComment As String) 
    ' loop through all the properties and get the key for each     
    For Each Key As String In entry.Properties.PropertyNames        
        Dim sPropertyValues As String = [String].Empty         
        ' now loop through all the values in the property;         
        ' can be a multi-value property   
        For Each Value As Object In entry.Properties(Key) 
            sPropertyValues += Convert.ToString(Value) + ";"        
        Next 
        ' cut off the separator at the end of the value list       
        sPropertyValues = sPropertyValues.Substring(0, sPropertyValues.Length - 1)         
        ' now add the property info to the property list
        Debug.WriteLine(Key + "=" + sPropertyValues) 
    Next 
End Sub 

Open in new window

0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
naspinskiCommented:
This functionality is all built in without any VB required.

I you just edit your web.config to use windows as your authentication:

<authentication mode="Windows"/>

Then use the LoginName Control:

<asp:LoginName ID="LoginName1" runat="server" />

It's just that simple to pull your AD name.
That way it takes no code-behind and is very simple/efficient.
0
 
dingirAuthor Commented:
Dhaest,
Thank's a lot! An error though..

Index was outside the bounds of the array.
Line 21:         retVal = Page.User.Identity.Name.Split("\"c)(1)

I've tried to response.write and response.end but only get an empty string.
Also I Understand this line "Dim userEntry As New DirectoryEntry("WinNT://" + userName + ",User")" means retval, not username?


naspinski,
Impressive. That's a sort of solution I was thinkinh about. However I can't get any output here neither. Than I though the problem could be that the aspx-page runs from a server outside AD (within same routed network). I placed the script and web.config in a new application pole on the SBS servers own IIS. Still no output.

Any ideas?
0
 
DhaestCommented:
1) retVal = Page.User.Identity.Name.Split("\"c)(1)

Is your current user in a domain ? Because I expected something like "myDomain\myusername"

2) You're right - Dim userEntry As New DirectoryEntry("WinNT://" + retval + ",User")"
0
 
dingirAuthor Commented:
Hi, thank's
Yes. My Access VBA function is identifying me correctly as DOMAIN\UserN in exactly same environment, except that there are a MDB File - not a web browser. I've tried with impersonate true, and without. I also have Authentication Windows. As I understand I would get at least a NT_AUTH or something if there was something with security.
0
 
DhaestCommented:
Are you sure that all your IIS-settings are correct ?
http://forums.asp.net/p/1261428/2404136.aspx
0
 
dingirAuthor Commented:
Finally!
Dhaest, your shortcut was usefull, i had the Anonymous user checked.
And with a lot's of googling and modifying,

    Private Function GetUserName() As String
        'retVal = DirectCast(userEntry.Properties("fullname").Value, String)

        Dim retVal As String = String.Empty
        Dim strDomain As String = "DOMAIN"
        retVal = Page.User.Identity.Name.Split("\"c)(1)
        Dim userEntry As New DirectoryEntry("WinNT://" + strDomain + "/" + retVal)

        For Each Key As String In userEntry.Properties.PropertyNames
            Dim sPropertyValues As String = [String].Empty
            ' now loop through all the values in the property;        
            ' can be a multi-value property  
            For Each Value As Object In userEntry.Properties(Key)
                sPropertyValues += Convert.ToString(Value) + ";"
            Next
            ' cut off the separator at the end of the value list      
            sPropertyValues = sPropertyValues.Substring(0, sPropertyValues.Length - 1)
            ' now add the property info to the property list
            Response.Write(Key + "=" + sPropertyValues & "<br>")
        Next

        Return retVal
    End Function

Now I've got all properties printed on screen. What's left now?
1. To specify one specific line of those properties
2. The user specific properties should be available. Like phone number, adress and so on.
0
 
DhaestCommented:
You can alter your procedure so that you only take the properties you want.
(I don't know the right names, that's the reason why I gave all the properties)

For example:

If userEntry IsNot Nothing Then 
    Response.Write("Name =" + userEntry.Properties("displayName").Value.ToString() & "<br>")
   
    If userEntry.Properties("companyName").Value.ToString() IsNot Nothing Then 
            Response.Write("CompanyName =" + userEntry.Properties("companyName").Value.ToString() & "<br>")
        
    End If 
    
    If userEntry.Properties("telephoneNumber").Value.ToString IsNot Nothing Then 
            Response.Write("telephoneNumber=" + userEntry.Properties("telephoneNumber").Value.ToString() & "<br>")
    End If 
    If userEntry.Properties("mail").Value.ToString() IsNot Nothing Then 
            Response.Write("mail=" + userEntry.Properties("mail").Value.ToString() & "<br>")
    End If 
End If 

Open in new window

0
 
naspinskiCommented:
0
 
dingirAuthor Commented:
Thank's! No problem with the loop.
I think that the problem is that this collection does not include any user specifik data!

If I try other variables like "givenname", "telephoneNumber" (i don't find a complete list of those variables yet) and gets that the "Object reference not set to an instance of an object". However it works if I use any of the variables listed by the loop.
0
 
DhaestCommented:
       Dim retVal As String = String.Empty
        Dim strDomain As String = "DOMAIN"
        strDomain = Page.User.Identity.Name.Split("\")(0)
        retVal = Page.User.Identity.Name.Split("\")(1)
        Dim userEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" + strDomain)
        Dim Dsearch As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(userEntry)
        Dsearch.Filter = "cn=" + retVal

        Dim oResults As System.DirectoryServices.SearchResultCollection = Dsearch.FindAll()
        Dim oResult As System.DirectoryServices.SearchResult
        For Each oResult In oResults
            Response.Write(oResult.Properties("givenname")(0).ToString() + "<br>")
            Response.Write(oResult.Properties("streetaddress")(0).ToString() + "<br>")
        Next
0
 
DhaestCommented:
You can define your own properties to load
 Private Function GetUserName() As String
       Dim retVal As String = String.Empty
        Dim strDomain As String = "DOMAIN"
        strDomain = Page.User.Identity.Name.Split("\")(0)
        retVal = Page.User.Identity.Name.Split("\")(1)
        Dim userEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" + strDomain)
        Dim Dsearch As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(userEntry)
        Dsearch.PropertiesToLoad.Add("sn")
        Dsearch.PropertiesToLoad.Add("givenName")
        Dsearch.PropertiesToLoad.Add("telephoneNumber")
        Dsearch.Filter = "cn=" + retVal
 
        Dim oResults As System.DirectoryServices.SearchResultCollection = Dsearch.FindAll()
        Dim oResult As System.DirectoryServices.SearchResult
        For Each oResult In oResults
            Response.Write(oResult.Properties("givenname")(0).ToString() + "<br>")
            Response.Write(oResult.Properties("streetaddress")(0).ToString() + "<br>")
        Next
end function

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 7
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now