locked
AD current user username RRS feed

  • Question

  • User-1379762086 posted

    I am developing a window service application, i have the below code in C# to get the active directory username of the current user

    public string GetUserID() 
    {
        using(var domainContext = new PrincipalContext(ContextType.Domain, "IPaddress", "username", "password")) 
        {
            UserPrincipal user = UserPrincipal.Current;
    
            if (user != null) {
                userid = user.SamAccountName; // or whatever you mean by "login name"
            }
        }
        return userid;
    }

    The above code worked well in a console application but when used it in a window service application i got the below error

    Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.

    Thursday, January 16, 2014 4:57 AM

Answers

All replies

  • User220175380 posted

    Hi,

    Use below namespaces,

    Imports System.DirectoryServices.AccountManagement
    Imports System.DirectoryServices
    Imports System.Security
    Imports System.Security.Permissions

    Thursday, January 16, 2014 5:42 AM
  • User-1379762086 posted

    Thank you for your reply but i already have those namespaces

    Thursday, January 16, 2014 7:14 AM
  • User1508394307 posted

    Why don't you use WindowsIdentity.GetCurrent()?

    string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    Thursday, January 16, 2014 8:44 AM
  • User-1379762086 posted

    Thanks for your reply, i used your code but am getting userName as NT AUTHORITY\\SYSTEM

    Thursday, January 16, 2014 9:17 AM
  • User1508394307 posted

    The difference between console application and web service is that console is running with user account and web service is with service account. So, current user of the service is NT AUTHORITY\SYSTEM because it is a service. The service itself does not have any direct access to the user logged.  

    http://social.msdn.microsoft.com/Forums/vstudio/en-US/3be119b0-88b4-442e-9613-6856cbb27adb/how-can-i-get-current-username-in-windows-service

    This forum is for ASP.NET. However you can at least indicate here why service needs to get the name of user.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 16, 2014 9:29 AM
  • User-734925760 posted

    Hi,

    According to your description and the error message, it want to tell us we should use the current user. We should get the current thread's user.

    So I suggest to using WindowsPrincipal to get the user.

    For more information, please refer to the links below:

    http://forums.iis.net/t/1159960.aspx

    http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal(v=vs.110).aspx

    Hope it's useful for you.

    Best Regards,

    Michelle Ge

     

     

    Thursday, January 16, 2014 9:56 PM