简体   繁体   中英

How to get username, password and domain of current user

I develop a windows service to interop with reporting service and so i need to form NetworkCredential to pass to SSRS. The question is - how can i get username, SecureString and domain of user that runs the service?

I'll be gratefull for any help!

You can get the current user by:

System.Security.Principal.WindowsIdentity.GetCurrent().Name;

If I remember correctly, this also has a prefix of the domain on the form domain\\username

You cannot retrieve the password for the current logged in user. What you can do however, is to specify which user the windows service runs as. That way you will know the password, and be able to link that account, and grant the appropriate access throughout your domain.

Note that if you sometime in the future decide to change password to the user account, you will manually have to update the credentials on the service.

To have a complete answer including FirstName, LastName and Domain we can use below code:

var domain = Environment.UserDomainName;
UserPrincipal userPrincipal = UserPrincipal.Current;
var firstname = userPrincipal.GivenName;
var lastname = userPrincipal.SurName
var username_id = userPrincipal.SamAccountName;

You need to add System.DirectoryServices.AccountManagement as assembly reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM