Search code examples
wcf-security

how to get current windows user in wcf


I already tried link from stackoverflow

I have a silverlight client and wcf service. The application has 3 authentication modes

  1. Active Directory
  2. Windows Pass Through
  3. Proprietary - I don't have a problem with this one obviously. (I really don't know what is the difference between active directory and Window Pass Through. I just use the same code for both, except for windows pass through I get the current user and for AD the app prompts for username password)

.

private string GetCurrentUser()
{
    try
    {
        string result = WindowsIdentity.GetCurrent().Name;
        WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        result = wp.Identity.Name;
        if (result.Contains(@"\"))
        {
            int position = result.LastIndexOf(@"\") + 1;
            result = result.Substring(position);
        }
        return result;
    }
    catch (Exception ex)
    {
        return "";
    }
}

Both WindowsIdentity and WindowsPrincipal returns 'DefaultAppPool' or whatever the AppPool the current thread runs. Even Environment.UserName returns the same.

When I turn on <identity impersonate ="true"/> in web.config the silverlight client fails to connect to wcf. It gets a 'Not Found' error. So, I need to keep <identity impersonate ="false"/>

All I need is the current logged on user, I didn't know that it's this difficult.


Solution

  • I changed the identity on the Application Pool to my own user account and it worked.

    1. Open IIS Console
    2. Select Application Pools.
    3. Select the AppPool (in my case it was DefaultAppPool).
    4. On the right pane click Advanced Settings.
    5. There are different categories of settings like General, CPU, Process Model.
    6. Under Process Model -> Identity click the right side input box, a button shows up, click it.
    7. It opens a dialog box with 2 radio buttons (Built-in account and Custom account).
    8. Select custom account and hit Set.
    9. Set Credentials dialog box opens.
    10. Enter your credentials and hit okay. You may have to enter [domain][user name]
    11. Hit Ok to all the dialog boxes to close everything.
    12. Now test your app, WindowsIdentity.GetCurrent().Name should return the username associated with the Application Pool.