Search code examples
javaimpersonation

User impersonation in java


Using impersonation I tried to read a file located on the network in a shared folder. But I got the error "Access is denied". My source code is given below ...

This works fine for local resources. But gives error when access network resources. line \sever\shared\abc.txt

    // Create a provider that implements Windows authentication functions
    IWindowsAuthProvider prov = new WindowsAuthProviderImpl();

    // Login using different user
    IWindowsIdentity identity = prov.logonDomainUser("abc.jim","abc.com", "Xyz@123");
    IWindowsImpersonationContext context = identity.impersonate();

    // Reading file using new user
    readFile(); // It gives error - Access is denied

    // Revert back to original logged user 
    context.revertToSelf();

    readFile(); // It is working properly

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

Solution

  • Finally i am able to solve this problem by creating one native C library using JNI.

    Native windows API used are

     LogonUser : http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
     ImpersonateLoggedOnUser  : http://msdn.microsoft.com/en-us/library/windows/desktop/aa378612(v=vs.85).aspx
     RevertToSelf  :  http://msdn.microsoft.com/en-us/library/windows/desktop/aa379317(v=vs.85).aspx