简体   繁体   中英

Get username in WCF service using basic auth with IIS

I have a WCF service running in IIS Express on my local machine. I'm using HTTP Basic Authentication (without SSL at the moment). I have a test client that I'm using to call my server.

I need the name of the user that initiated the request (the username portion of the basic auth authentication). I realize that IIS is handling the authentication for me and is checking the username/password against Windows user accounts. That is fine for my purposes. My issue is that once my service is called I can't find the username anywhere. I assumed it would be in the Thread.CurrentPrincipal.Identity.Name , but that value is an empty string. Is there a way to access this value?

Here is binding in case it is relevant:

<basicHttpBinding>
<binding name="basicauth" closeTimeout="00:01:00" openTimeout="00:01:00" 
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" 
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
maxBufferSize="99999999" maxBufferPoolSize="524288" maxReceivedMessageSize="99999999" 
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" 
useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" 
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  <security mode="TransportCredentialOnly">
    <transport clientCredentialType="Basic" realm="" />
  </security>          
</binding>
</basicHttpBinding>

UPDATE: Thanks everyone. Figured out my issue. I had improperly associated my endpoint and my binding so the endpoint was defaulting to some dynamic binding. Even though I configured my binding for basic auth the endpoint was not setup to use it.

Once I fixed this issue the username was present in the

ServiceSecurityContext.Current.WindowsIdentity.Name

property like expected.

Thread.CurrentPrincipal.Identity.Name will normally retrieve the identity under which the WCF worker thread is being executed in IIS. This is not particularly useful information. Have you inspected ServiceSecurityContext.Current.PrimaryIdentity.Name to see if it contains the authentication information from the server?

This may work - it works for windows auth. Can't remember if it works for basic ... worth a try.

OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name

Since you are setting clientCredentialType = "Basic" , you will not get a Windows identity from WCF. If you use "Windows" instead of "Basic" and you configure WCF to support for impersonation as shown in this blog post , you should be able to get the identity user name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM