Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Here i'm using
1) WCF service(Windows Authenticated and Impersonation)
2) Sql server(Windows Authentication)
3) Console Application(Client)
All Are in Same Domain

I'm consuming windows authenticated WCF service from console Application(Client) so when i'm trying to access SQL server from console application using WCF service it's showing me error :
Exception In Account Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.


My scenario is
my WCF service and SQL server is in one system (Suppose system A) and my console application (My Client) is in another system(Suppose System B).
when my client(System B) send request it hit my service successfully but when service try to access SQL server it shows error:
Exception In Account Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.


What I have tried:

MY Client Side Code:

static void Main(string[] args)
       {
           try
           {
               ServiceClient obj = new ServiceClient();
               obj.ClientCredentials.Windows.AllowedImpersonationLevel =
                       System.Security.Principal.TokenImpersonationLevel.Impersonation;
               obj.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                  AccModel objAccModel = new AccModel();
                  objAccModel.ACC_No = "jkh90";
                  objAccModel.Remark = "dsdsadasd";
                  objAccModel.ACC_Code = "AA";
                  var strflight = obj.Acc_Validate(objAccModel);
           }
           catch (Exception ex)
           {

               Console.Write(ex.Message);
           }

       }


MY Server Side Code(WCF Service)

public string Acc_Validate(ACCModel objACCModel)
       {
               try
               {

                   using (WindowsImpersonationContext ctx = WindowsIdentity.GetCurrent().Impersonate())
                   {
                     SqlParameter[] parameter = {
                                          new SqlParameter("@CMD","ACCVALIDATE"),
                                          new SqlParameter("@ACC_No",objACCModel.ACC_No),
                                          new SqlParameter("@ACC_Code",objACCModel.ACC_Code),
                                          new SqlParameter("@PNRIDOUT", SqlDbType.NVarChar,800) {Direction = ParameterDirection.Output}
                                          };
               strStatus = SQLHelper.ExecuteNonQueryTwoOutputResult(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, DBConstants.PRIU_ACC_DETAILS,  "@PNRIDOUT", parameter);
                   }
               }
               catch (Exception ex)
               {
                   ClsLogging.writefile("Errorrrrrrrrrrr " + ex.Message, ClsLogging.LogType.BTA_Service_Exception);
               }

               }


WCF Service(Web Config File)

XML
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <pages controlRenderingCompatibilityVersion="4.0"/>
    <httpCookies httpOnlyCookies="true"/>
    <authentication mode="Windows">
    <identity impersonate="true"/>
  
  <connectionstrings> 
    <add name="Connection" connectionString="Initial Catalog=ACCDB;Data Source=*****;Integrated Security=True;"/>
  
  <system.servicemodel>
    <services>
      <service name="Service.Service" behaviorConfiguration="ServiceBehavior">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="TransportSecurity" contract="Service.IService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      
    
    <bindings>
      <basichttpbinding>
        <binding name="TransportSecurity">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"/>
            
          
        
      
    
    <behaviors >
      <servicebehaviors>
        <behavior name="ServiceBehavior">
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <serviceMetadata httpGetEnabled="true"/>
          <serviceAuthorization impersonateCallerForAllOperations="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceSecurityAudit auditLogLocation="Application" suppressAuditFailure="false" serviceAuthorizationAuditLevel="SuccessOrFailure" messageAuthenticationAuditLevel="SuccessOrFailure"/>
          <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances="100" maxConcurrentSessions="200"/>
        
      
    
    <serviceHostingEnvironment multipleSiteBindingsEnabled="false"/>
  
  <system.webserver>
    <validation validateIntegratedModeConfiguration="false" />
    <httpprotocol>
      <customheaders>
        <add name="X-Content-Type-Options" value="nosniff"/>
      
    
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
Posted
Updated 19-Feb-17 3:32am
v2

Look at the error message:
Exception In Account Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
Your WCF service does not run as a "normal user" - it runs under a special anonymous login. So when you try to use Integrated Security as part of your connection string, it fails because it won't permit anonymous users access to the DB (and quite right too!)

Use an SQL username / password combination (not the sa login though, for gawd's sake) and change your connection string to reflect that. It should then connect without problems.
 
Share this answer
 
Comments
Member 12923802 18-Feb-17 7:24am    
I Cant use Sql Authentication(Username and Password) for my Database. Requirement is for windows authentication for my Database
OriginalGriff 18-Feb-17 7:37am    
Then you will have to run your Service under a user account that the database will accept.
Member 12923802 18-Feb-17 7:49am    
we already running with user account which haves rights to SQL but still its getting pass as 'NT AUTHORITY\ANONYMOUS' while SQL
OriginalGriff 18-Feb-17 8:02am    
Your WCF service isn't. It's possible your console app is, but your service does not run under a user account.
Looks like you've forgotten to add the OperationBehavior attribute to your service method:
When impersonating for all operations, the Impersonation property of the OperationBehaviorAttribute applied to each method must also be set to either Allowed or Required.

C#
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string Acc_Validate(ACCModel objACCModel)

Based on that article, you shouldn't need the WindowsImpersonationContext.
 
Share this answer
 
Change your code with following stuffs

C#
//client
                ServiceClient obj = new ServiceClient();
              
  obj.ClientCredentials.Windows.AllowedImpersonationLevel = 
     System.Security.Principal.TokenImpersonationLevel.Delegation; // other stuff remove which you did for Test purpose
              
                   AccModel objAccModel = new AccModel();
                   objAccModel.ACC_No = "jkh90";
                   objAccModel.Remark = "dsdsadasd";
                   objAccModel.ACC_Code = "AA";
                   var strflight = obj.Acc_Validate(objAccModel);


its will solve your issue
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900