Solved

Current user Active Directory

Posted on 2008-06-17
14
344 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
 
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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now