Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Windows Authentication in Windows Application?

How to use windows authentication (local machine administrator user) in windows application written in C#.

Need is whenever user opens my windows application GUI, it should authenticate local administrator credentials even if User is logged in as Administrator there.

Is this windows Impersonation?

like image 343
Jango Avatar asked May 25 '10 14:05

Jango


2 Answers

You can call the LogonUser API method to check a username and password.
You can see the [DllImport] here.

If you want to show a standard username/password prompt, you can call the CredUIPromptForCredentials API function; see also here

EDIT

To check whether the user is an administrator, you can call CheckTokenMembership and check whether the user is in the Administrators group.

Alternatively, you can call NetUserGetInfo level 1 and check whether usri1_priv is USER_PRIV_ADMIN.

You can also use WMI or DirectoryServices.

like image 149
SLaks Avatar answered Oct 25 '22 21:10

SLaks


May be a bit late but to achieve Window Authentication Functionality to a C# Desktop Application, there are two steps accomplish with below steps.

Step 1: Get currently logged in user details:

This is pretty straight forward. we can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity. Bellow is the code you can use to get the current logged in user details.

Step 2: Validate windows credentials provided by user:

Need to ask domain name, user name, password from user to pass these values to interop service. This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.

bool issuccess = false;
string username = GetloggedinUserName();
if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()) && username.ToLowerInvariant().Contains(txtDomain.Text.Trim().ToLowerInvariant()))
    {
        issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
    }

if (issuccess)
    MessageBox.Show("Successfuly Login !!!");
else
    MessageBox.Show("User Name / Password / Domain is invalid !!!");
like image 24
Ali Avatar answered Oct 25 '22 21:10

Ali