Java Impersonation using JNA and Waffle

Have you ever had the need to create a Java application that executes on behalf of a logged in Windows user?
You can!

    In this post we will use JNA and Waffle to:

  • Create a simple Java application to impersonate a Windows domain user.

In a future post, we will see how this can also be done in a servlet!

1. Create a Java application to impersonate a Windows domain user

Prequisites:

  • A windows system
  • A windows user, DOMAIN\userA with Administrator rights
  • A windows user, DOMAIN\userB

Let’s start off with the simple Java program.

public static void main(String[] args) throws Exception {
        // Create a provider that implements Windows authentication functions
        IWindowsAuthProvider prov = new WindowsAuthProviderImpl();
        
        // Logon using my UPN formatted Windows domain account. 
        IWindowsIdentity identity = prov.logonUser("userB@my.domain.com", "UserBPassword");

        // Impersonate as userB@my.domain.com
        IWindowsImpersonationContext ctx = identity.impersonate();
        
        // As the impersonated user, userB, create a new file
        writeFile("c:\\temp\\"+Advapi32Util.getUserName()+".txt");
        
        // Revert to the original user, userA
        ctx.revertToSelf();
        
        // As userA, create a new file
        writeFile("c:\\temp\\"+Advapi32Util.getUserName()+".txt");

        // Cleanup the Windows identity
        identity.dispose();
}

Let’s run the program and observe its behavior.

  1. Logon to the Windows system as userA. userA must have Administrator rights.
  2. Exeute the program as the logged on user e.g. userA
  3. Observe, that the program creates two new files
    • e.g.
    • c:\temp\userA.txt
    • c:\temp\userB.txt
  4. Inspect file properties and validate that userA.txt is owned by userA and userB.txt is owned by userB.
    • Right click c:\temp\userA.txt and select Properties
    • Choose the Details tab
    • Verify that Owner is userA (or Administrator)
    • Right click c:\temp\userB.txt and select Properties
    • Choose the Details tab
    • Verify that Owner is userB

As you can see, we have successfully constructed a Java application that impersonates Windows domain users!
Thank you!

You may also like...

Leave a Reply