Search code examples
javawmijna

COAUTHIDENTITY with CoSetProxyBlanket using JNA


I am trying to write a Java API which uses JNA to communicate with WMI with remote machine (provided username and password).
For this I want to create COAUTHIDENTITY object and use it with CoSetProxyBlanket in Java.
The code I am trying to port is here.
Any help with this would be appreciated.


Solution

  • You can map the COAUTHIDENTITY structure in an interface class. It looks like WTypesBase which extends WTypes may be a good class name although you can put it anywhere.

    The type mappings are simple: what you see as unsigned long can be NativeLong but since this is Windows-only code you can use int as we know it's 32-bit. The unsigned short * pointers are character arrays of 2-byte (wide) characters. Just use a Pointer for those.

    So your structure heading should be:

    class COAUTHIDENTITY extends Structure {
      public Pointer User;
      public int UserLength;
      public Pointer Domain;
      public int DomainLength;
      public Pointer Password;
      public int PasswordLength;
      public int Flags;
    }
    

    (Field order mappings are left as an exercise for the reader.)

    Then to create it:

    COAUTHIDENTITY auth = new COAUTHIDENTITY();
    
    String user = "username"; // or get from the user
    // Allocate memory for user including null terminator
    auth.User = new Memory(Native.WCHAR_SIZE * (user.length() + 1));
    // Set the widestring in memory
    auth.User.setWideString(0, user);
    auth.UserLength = user.length();
    
    // Do the same for domain and password
    
    auth.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
    // Note: SEC_WINNT_AUTH_IDENTITY_ANSI = 1