Saturday, May 12, 2012

How to verify user credentials programmatically (Windows)

We may use LogonUser like in the following example:

{
  char user[] = "USERNAME";
  char pass[] = "PASSWORD";
  char domain[] = "DOMAIN";
  BOOL result;
  HANDLE token = NULL;

  result = LogonUser(user, domain, pass, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &token);
  if (result) {
    printf("user %s successfully logged on\n", user);
    CloseHandle(token);
  } else {
    printf("unable to logon: %d", GetLastError());
  }

  /* it is always good to call SecureZeroMemory. Even in the sample */
  SecureZeroMemory(pass, sizeof(pass) / sizeof(*pass));
}

It is possible to  pass domain as the second argument or provide username in the form username@domainname. In the later case the second argument must be NULL. The function cannot handle the form "DOMAINNAME\\USERNAME".

This is valid since Windows XP. In case of previous versions of Windows check the link http://support.microsoft.com/kb/180548

1 comment: