Search code examples
delphiwinapiwindows-server-2000

Check user credential against a workgroup server


My app will be used on LAN on a client desktop computer. In this LAN, there is one dedicated Windows 2k server. There is no AD.

The user have to fill in a server's user account informations so the app can then do some remote operations with this account (Map network drives)

How can I check the user credentials against this server?

When mapping drivers, I will have the error if the user account authentication is not ok, but I would like to have this information before trying to map.

Something like LogonUser API function, but working on a remote computer.

Thanks,


Solution

  • You can use the WNetUseConnection function with CONNECT_INTERACTIVE and CONNECT_PROMPT flags. That will in combination with empty user ID and password parameters invoke the credentials dialog and connect to a network resource when you enter correct credentials:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      BufferSize: DWORD;
      ResultFlag: DWORD;
      NetResource: TNetResource;
    begin
      NetResource.dwType := RESOURCETYPE_DISK;
      NetResource.lpLocalName := nil;
      NetResource.lpRemoteName := '\\MySuperSecret\Place';
      NetResource.lpProvider := nil;
      if WNetUseConnection(Handle, NetResource, nil, nil, CONNECT_INTERACTIVE or
        CONNECT_PROMPT, nil, BufferSize, ResultFlag) = NO_ERROR
      then
        ShowMessage('Connected!');
    end;
    

    To connect to a network resource without prompting for credentials remove the flags specified above as it's shown in the following function, which should return True, when the connection succeed, False when it fails. Here's the parameter description:

    • RemoteName (string) - remote network name
    • UserName (string) - user name used to connect to a network resource
    • Password (string) - password used to connect to a network resource

    function TryConnect(const RemoteName, UserName, Password: string): Boolean;
    var
      BufferSize: DWORD;
      ResultFlag: DWORD;
      NetResource: TNetResource;
    begin
      NetResource.dwType := RESOURCETYPE_DISK;
      NetResource.lpLocalName := nil;
      NetResource.lpRemoteName := PChar(RemoteName);
      NetResource.lpProvider := nil;
      Result := WNetUseConnection(0, NetResource, PChar(UserName), PChar(Password),
        0, nil, BufferSize, ResultFlag) = NO_ERROR;
    end;