Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Current user Active Directory

Posted on 2008-06-17
14
347 Views
Last Modified: 2010-05-19
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
Comment
Question by:dingir
  • 7
  • 5
  • 2
14 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 21800706
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
 
LVL 1

Author Comment

by:dingir
ID: 21800812
Hi,

 Thank's for answer. I forgot to tell that I need a VB Solution. Possible?
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 21800860
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

 
LVL 21

Expert Comment

by:naspinski
ID: 21800967
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
 
LVL 1

Author Comment

by:dingir
ID: 21801116
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 21801203
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
 
LVL 1

Author Comment

by:dingir
ID: 21801231
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 21819796
Are you sure that all your IIS-settings are correct ?
http://forums.asp.net/p/1261428/2404136.aspx
0
 
LVL 1

Author Comment

by:dingir
ID: 21820195
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 21820245
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
 
LVL 21

Expert Comment

by:naspinski
ID: 21820298
0
 
LVL 1

Author Comment

by:dingir
ID: 21820348
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 21820623
       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
 
LVL 53

Accepted Solution

by:
Dhaest earned 500 total points
ID: 21820645
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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C# LINQ ForEach() question 6 54
edit .asp files 5 31
Please explain purpose of GZIP 4 34
asp.net open new page without popup blocker 8 18
I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question