Db call executes under an anonymous user, when impersonation is on and DataPortal is local.

Db call executes under an anonymous user, when impersonation is on and DataPortal is local.

Old forum URL: forums.lhotka.net/forums/t/4181.aspx


xplinscott posted on Wednesday, January 16, 2008

The abstract of my problem is that after a user authenticates against active directory, with impersonation on, the calls to the database execute with the context of IIS's anonymous IUSR. What I don't get is why doesn't the thread execute under the security context of the authenticated user when there is no physical seperation, and because the DataPortal is running locally, I don't see cross thread calls that would cause a double hop?

The error itself:

Server Error in '/' Application.

Login failed for user 'LNGSEAL028596B\IUSR_LNGSEAL028596B'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'LNGSEAL028596B\IUSR_LNGSEAL028596B'.

Source Error:

Line 91:             using (SqlConnection dbConnection = new SqlConnection(Database.BillingConnection))
Line 92: {
Line 93: dbConnection.Open();

Line 94:
Line 95: ExecuteFetch(dbConnection, criteria);

Source File: C:\Projects\AppliedDiscovery\AppliedDiscovery.Billing.Business\ClientEntityList.cs    Line: 93
Stack Trace:

[SqlException (0x80131904): Login failed for user 'LNGSEAL028596B\IUSR_LNGSEAL028596B'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800131
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +172
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +381
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +181
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +173
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +357
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +30
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +494
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +105
System.Data.SqlClient.SqlConnection.Open() +111
AppliedDiscovery.Billing.Business.ClientEntityList.DataPortal_Fetch(FilterCriteria criteria) in C:\Projects\AppliedDiscovery\AppliedDiscovery.Billing.Business\ClientEntityList.cs:93

[CallMethodException: DataPortal_Fetch method call failed]
Csla.MethodCaller.CallMethod(Object obj, MethodInfo info, Object[] parameters) +128
Csla.Server.SimpleDataPortal.Fetch(Type objectType, Object criteria, DataPortalContext context) +229

[DataPortalException: DataPortal.Fetch failed (System.Data.SqlClient.SqlException: Login failed for user 'LNGSEAL028596B\IUSR_LNGSEAL028596B'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at AppliedDiscovery.Billing.Business.ClientEntityList.DataPortal_Fetch(FilterCriteria criteria) in C:\Projects\AppliedDiscovery\AppliedDiscovery.Billing.Business\ClientEntityList.cs:line 93)]
Csla.DataPortal.Fetch(Type objectType, Object criteria) +312
Csla.DataPortal.Fetch(Object criteria) +56
AppliedDiscovery.Billing.Business.ClientEntityList.GetClientEntityList() in C:\Projects\AppliedDiscovery\AppliedDiscovery.Billing.Business\ClientEntityList.cs:68

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +72
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +308
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +480
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1960
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +17
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +149
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +70
System.Web.UI.WebControls.GridView.DataBind() +4
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +50
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041



Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

Event Log Entries

    Event Type:	Warning
Event Source: ASP.NET 2.0.50727.0
Event Category: Web Event
Event ID: 1309
Date: 1/16/2008
Time: 7:19:31 AM
User: N/A
Computer: LNGSEAL028596B
Description:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 1/16/2008 7:19:31 AM
Event time (UTC): 1/16/2008 3:19:31 PM
Event ID: 17bfb1671e584064a96b6198f413d30c
Event sequence: 5
Event occurrence: 1
Event detail code: 0

Application information:
Application domain: /LM/W3SVC/1/ROOT-1-128449697688516508
Trust level: Full
Application Virtual Path: /
Application Path: c:\inetpub\wwwroot\
Machine name: LNGSEAL028596B

Process information:
Process ID: 2984
Process name: aspnet_wp.exe
Account name: LNGSEAL028596B\ASPNET

Exception information:
Exception type: TargetInvocationException
Exception message: Exception has been thrown by the target of an invocation.

Request information:
Request URL: http://localhost/Client/ClientList.aspx
Request path: /Client/ClientList.aspx
User host address: 127.0.0.1
User: Matthew.Linscott
Is authenticated: True
Authentication Type: Forms
Thread account name: LNGSEAL028596B\ASPNET

Thread information:
Thread ID: 1
Thread account name: LNGSEAL028596B\ASPNET
Is impersonating: False
Stack trace: at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance)
at System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments)
at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
at System.Web.UI.WebControls.GridView.DataBind()
at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()
at System.Web.UI.Control.EnsureChildControls()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


Custom event details:

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
    Event Type:	Failure Audit
Event Source: MSSQLSERVER
Event Category: (4)
Event ID: 18456
Date: 1/16/2008
Time: 7:20:06 AM
User: LNGSEAL028596B\IUSR_LNGSEAL028596B
Computer: LNGSEAL028596B
Description:
Login failed for user 'LNGSEAL028596B\IUSR_LNGSEAL028596B'. [CLIENT: 10.65.20.71]

My Configuration

Extract from Global.asax

        protected void Application_AcquireRequestState(object sender, System.EventArgs e)

        {

            if (System.Web.HttpContext.Current.Session == null)

                return;

 

            Csla.ApplicationContext.User = new ADBB.Security.MembershipPrincipal(HttpContext.Current.User);

        }

Web.config

<?xml version="1.0"?>

<configuration>

    <configSections>

        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>

                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

                </sectionGroup>

            </sectionGroup>

        </sectionGroup>

    </configSections>

    <appSettings>

        <add key="CslaAuthentication" value="Windows"/>

    </appSettings>

    <connectionStrings>

        <clear/>

        <add name="LocalSqlServer" connectionString="Data Source=.\;User ID=zzzAdmin;Password=zzzYYY;Initial Catalog=zzzSecurityDatabase;"/>

        <add name="BillingConnection" connectionString="Data Source=.\;Integrated Security=SSPI;Initial Catalog=zzzBillingDatabase;"/>

        <add name="zzzDomainConnectionString" connectionString="LDAP://zzzServer/OU=Employees,DC=zzzDomain,DC=com" />

    </connectionStrings>

    <system.web>

        <pages>

            <controls>

                <add tagPrefix="csla" namespace="Csla.Web" assembly="Csla" />

                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            </controls>

        </pages>

        <authentication mode="Forms">

            <forms name=".ADAuthCookie" timeout="10" />

        </authentication>

 

        <authorization>

            <deny users="?"/>

            <allow users="*"/>

        </authorization>

 

        <identity impersonate="true"/>

 

        <membership defaultProvider="ADIClientADMembershipProvider">

            <providers>

                <add name="ADIClientADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="zzzDomainConnectionString"  attributeMapUsername="sAMAccountName" connectionUsername="zzzDomain\zzzAdmin" connectionPassword="zzzPath" />

            </providers>

        </membership>

 

        <roleManager enabled="true" defaultProvider="BillingRoleProvider" cacheRolesInCookie="true" cookieName=".RolesCookie" cookieTimeout="30" cookieSlidingExpiration="true" cookieProtection="All">

            <providers>

                <add name="BillingRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="zzzWeb" description="Sql Role Provider"/>

            </providers>

        </roleManager>

        <!--

          Set compilation debug="true" to insert debugging

          symbols into the compiled page. Because this

          affects performance, set this value to true only

          during development.

    -->

        <compilation debug="true">

            <assemblies>

                <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            </assemblies>

        </compilation>

        <httpHandlers>

            <remove verb="*" path="*.asmx"/>

            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

        </httpHandlers>

        <httpModules>

            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

        </httpModules>

    </system.web>

    <system.webServer>

        <validation validateIntegratedModeConfiguration="false"/>

        <modules>

            <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

        </modules>

        <handlers>

            <remove name="WebServiceHandlerFactory-Integrated"/>

            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

        </handlers>

    </system.webServer>

</configuration>

MembershipPrincipal.cs - essentially from Rocky's book Expert C# 2005 Business Objects

using System;

using System.Collections.Generic;

using System.Text;

 

namespace AppliedDiscovery.Billing.Business.Security

{

    [Serializable()]

    public class MembershipPrincipal : Csla.Security.BusinessPrincipalBase

    {

        private System.Security.Principal.IPrincipal _principal;

 

        public MembershipPrincipal(System.Security.Principal.IPrincipal principal) : base(principal.Identity)

        {

            _principal = principal;

        }

 

        public override bool IsInRole(string role)

        {

            return _principal.IsInRole(role);

        }

    }

}

xplinscott replied on Wednesday, January 16, 2008

Nevermind, i'll attribute this to my stupidy and an incorrectly configured IIS, after disabling anonymous access in Directory Security and enabling Windows Authentication, and doing a quick iisreset, all is well.

Copyright (c) Marimer LLC