WIF Based Authentication Does Not Contact STS Issuer - c#

I am attempting to build an asp.net 4.7 (v4.5 WIF) using claims based authentication against our internal STS server. We have older working .Net apps (< 4.5) that can successfully get claims.
The issue is that the new app never contacts the STS server.
I surmise the failure is in how I am setting up the federation web.config vs the old. Here is my latest config, non working, followed by a config that works using the old identity process (WIF 3.5).
V4.0 WIF web.config (New 4.7 project)
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="urn:jabberwocky" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="{MyThumbprint}" name="https://{MyIssuerURL}" />
</trustedIssuers>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" />
<wsFederation passiveRedirectEnabled="true"
issuer="https://{MySTSUrl}"
realm="urn:jabberwocky"
reply="http://localhost:44301/"
requireHttps="true" />
</federationConfiguration>
</system.identityModel.services>
V3.5 WIF web.config (Old 4.0 project)
<microsoft.identityModel>
<service>
<audienceUris>
<add value="urn:Jabberwocky" />
</audienceUris>
<certificateValidation certificateValidationMode="None" />
<claimsAuthenticationManager type="{Namespace}.MyAuthenticationManager, {Namespace}" />
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true"
issuer="https://{MySTSUrl}"
requireHttps="true"
realm="urn:Jabberwocky" />
<cookieHandler requireSsl="true" />
</federatedAuthentication>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="{MyThumbprint}" name="https://{MyIssuerURL}" />
</trustedIssuers>
</issuerNameRegistry>
</service>
</microsoft.identityModel>
I know it does not hit the STS server because I use an invalid audienceUris value as a test, and I don't get rejected by the server as I would in the old project.
I sense it has something to do with the missing federatedAuthentication value in the old but not found in the new.

As for your current config, make sure both SAM and FAM modules are there.
If you want to control what's going on, I suggest switching to programmatic approach. Take a look at my tutorial.

I ended up having this in my web.config
<system.webServer>
<modules>
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</modules>
</system.webServer>

Related

Exception Thrown by the target of an invocation when accessing a 3rd party dll

I have been working on a C# console application which uses a number of 3rd party dlls which are referenced in the project.
Everything was working fine but one day my windows 7 operating system updated because of automatic windows update and after that this application code started crashing at the code where a call is made to a 3rd party dll which actually accessing the database.
I restored my system to a previous state and the application started working fine again but once again the windows update ran and application started crashing again at the same location.
I can not stop windows update as its a company provided laptop and I can not change setting so that windows update do not happen again. And I do not have the code for this 3rd party dll.
I can provide you the app.config here...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<section name="databaseSection" type="Cognizant.CAFE.FoundationServices.Data.Configuration.DatabaseSection,Cognizant.CAFE.FoundationServices.Data"/>
<section name="cafe.frameworks.foundationAbstraction" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.Configuration.FoundationAbstractionSectionHandler, Cognizant.CAFE.Frameworks.FoundationAbstraction.AdapterFactory"/>
<section name="loggingConfiguration" type="Cognizant.CAFE.FoundationServices.Logging.Configuration.LoggingConfigurationSection, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<section name="exceptionManagement" type="Cognizant.CAFE.FoundationServices.ExceptionManagement.Configuration.ExceptionManagementSection, Cognizant.CAFE.FoundationServices.ExceptionManagement, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<!--<databaseSection performanceCountersEnabled="false" />
<exceptionManagement performanceCountersEnabled="false" />-->
<databaseSection defaultDatabase="Sql" dbCommandTimeOut="3000">
<databases>
<add name="Sql" type="Cognizant.CAFE.FoundationServices.Data.SqlHelper,Cognizant.CAFE.FoundationServices.Data" connectionStringName="Sql"/>
</databases>
</databaseSection>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="C:\ApplicationLogs\BGTs\AA\v1.0\AABackgroundTask\Files\Log\AABLog.txt"/>
<appendToFile value="true"/>
<maximumFileSize value="1500KB"/>
<maxSizeRollBackups value="20"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFile"/>
</root>
</log4net>
<connectionStrings>
-----deleted
</connectionStrings>
<appSettings>
<!--Production-->
<!-- PROCESS DELAY SECTION -->
<add key="ProcessDelay" value="0"/>
<!-- INBOUND -->
<add key="IB_GlobalVarCreation" value="GlobalVarCreation"/>
<add key="IB_RoutingScript_In" value="RoutingScript_In"/>
<!-- OUTBOUND -->
<add key="OB_CampaignCreation" value="CampaignCreation"/>
<add key="OB_RoutingScript_Out" value="RoutingScript_Out"/>
<add key="OB_AdminScript_Agent" value="AdminScript_Agent"/>
<add key="OB_DisableCampaign" value=" DisableCampaign"/>
<!-- INBOUND & OUTBOUND -->
<add key="IB_OB_EnterpriseSkillGroup" value="EnterpriseSkillGroup"/>
<add key="IB_OB_SkillGroupCreation" value="SkillGroupCreation"/>
<add key="IB_OB_EnterpriseSkillGroupMap" value="EnterpriseSkillGroupMap"/>
<add key="IB_OB_CallType" value="CallType"/>
<add key="IB_OB_DialNumberMapping" value="DialNumberMapping"/>
<!--NORAML OPERATIONS-->
<add key="OPS_UserCreation" value="UserCreation"/>
<add key="OPS_AgentSupervisor" value="AgentSupervisor"/>
<add key="OPS_Rehire" value="Rehire"/>
<add key="OPS_AgentTeamCreation" value="AgentTeamCreation"/>
<add key="OPS_AgentSkillGroup" value="AgentSkillGroup"/>
<add key="OPS_AgentTeam" value="AgentTeam"/>
<add key="OPS_SupervisorTeam" value="SupervisorTeam"/>
<add key="OPS_AgentTeamUpdate" value="AgentTeamUpdate"/>
<!--Active Directory INFORMATION -->
<add key="adURL" value="IQOR.QOR.COM"/>
<add key="adUser" value="IQOR\ERP.IQ.QATCH"/>
<add key="adPassword" value="+loS96bB8jNKv1JWXVLb0w=="/>
<!--Others-->
<add key="OTH_TeamUpdateEnable" value="true"/>
<add key="OTH_ProgarmPoolIndEnable" value="false"/>
</appSettings>
<cafe.frameworks.foundationAbstraction>
<authorization>
<adapters>
<add name="CafeProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE.AuthorizationAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" default="True"/>
<add name="EnterpriseLibraryProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary.AuthorizationAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</adapters>
</authorization>
<caching>
<adapters>
<add name="EnterpriseLibraryProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary.CacheAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" default="True"/>
</adapters>
</caching>
<dataAccess>
<adapters>
<add name="CafeProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE.DataAccessAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" default="True"/>
</adapters>
</dataAccess>
<exceptionManagement>
<adapters>
<add name="CafeProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE.ExceptionManagerAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" default="True"/>
<add name="EnterpriseLibraryProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary.ExceptionManagerAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</adapters>
</exceptionManagement>
<logging>
<adapters>
<add name="CafeProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE.LoggingAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" default="True"/>
<add name="EnterpriseLibraryProvider" type="Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary.LoggingAdapter, Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.EnterpriseLibrary, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</adapters>
</logging>
</cafe.frameworks.foundationAbstraction>
<loggingConfiguration>
<commonSettings loggingEnabled="true" logToTrace="true" useAdditionalParameters="true">
<loggingMode asynchronous="False"/>
<filters>
<allowedLogLevels>
<add name="Error"/>
<add name="Fatal"/>
<add name="Information"/>
<add name="Trace"/>
<add name="Warning"/>
</allowedLogLevels>
<allowedLogCategories>
<add name="Category"/>
</allowedLogCategories>
</filters>
<publishers>
<add name="DBLog" type="Cognizant.CAFE.FoundationServices.Logging.DBPublisher, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<add name="EventLog" type="Cognizant.CAFE.FoundationServices.Logging.EventLogPublisher, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<add name="MSMQLog" type="Cognizant.CAFE.FoundationServices.Logging.MSMQPublisher, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<add name="TextLog" type="Cognizant.CAFE.FoundationServices.Logging.TextFilePublisher, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<add name="XMLLog" type="Cognizant.CAFE.FoundationServices.Logging.XMLFilePublisher, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</publishers>
<formatters defaultFormatter="Text">
<add name="Text" type="Cognizant.CAFE.FoundationServices.Logging.TextFormatter, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<add name="Xml" type="Cognizant.CAFE.FoundationServices.Logging.XMLFormatter, Cognizant.CAFE.FoundationServices.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</formatters>
</commonSettings>
<logSettings defaultCategory="Category">
<categories>
<add categoryName="Category">
<categorySettings>
<add levelName="Error">
<sinks>
<add publisherName="TextLog" formatterName="Text" fileName="AABLog.txt" maxFileSize="1MB"/>
</sinks>
</add>
</categorySettings>
</add>
</categories>
</logSettings>
</loggingConfiguration>
<exceptionManagement>
<policies defaultPolicy="UI Policy">
<add name="UI Policy" type="">
<exceptions>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="None">
<handlers>
<add name="Log Handler" type="Cognizant.CAFE.FoundationServices.ExceptionManagement.LogHandler, Cognizant.CAFE.FoundationServices.ExceptionManagement, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</handlers>
</add>
</exceptions>
</add>
</policies>
<messageSources defaultSource="Xml">
<add name="Xml" type="Cognizant.CAFE.FoundationServices.ExceptionManagement.XmlMessageSource, Cognizant.CAFE.FoundationServices.ExceptionManagement, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" source="D:\Cognizant\CAFE.NET 2.0\Foundation Services\QuickStart\Web\ExceptionMessages.xml"/>
</messageSources>
</exceptionManagement>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri=""/>
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/>
</providers>
</roleManager>
</system.web>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
The code where my application is crashing or giving exception is below:
public DataSet GetData(string statementId, string parameter)
{
object[] param = null;
DataSet ds = null;
try
{
if (parameter != null)
{
param = new object[1];
param[0] = parameter;
ds = DataAccessFaçadeAdapter.ExecuteStatementForDataSet(statementId, param);
}
else
{
ds = ExecuteStoredProcedure(statementId);
}
}
catch (Exception ex)
{
Tracer.Trace(TraceLevel.Error, "GetData() Exception is" + ex.Message);
}
return ds;
}
here the following line is where I get exception as this method is written in 3rd party dll for which I do not have any code
ds = DataAccessFaçadeAdapter.ExecuteStatementForDataSet(statementId, param);
And the Exceptions details are as below:
- InnerException {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
Message "Object reference not set to an instance of an object." string
Stack Trace as below:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at Cognizant.CAFE.Frameworks.FoundationAbstraction.AdapterFactory.GetAdapter[T]()
at IQOR.QATCH.IntegrationServices.DataAccessFaçadeAdapter.ExecuteStatementForDataSet(String StatementID, Object[] parameters)
at IQOR.AA.BackgroundTask.Exporter.GetData(String statementId, String parameter) in C:\\AutomationAnywhere_OLD_CODE\\AutomationAnywhere_OLD\\IQOR.AA.BackgroundTask - Copy\\IQOR.AA.BackgroundTask\\Exporter.cs:line 433
Stack Trace of 3rd Party dll is as below:
at Cognizant.CAFE.FoundationServices.Data.AdoHelperFactory.GetConnectionString(String providerName)
at Cognizant.CAFE.FoundationServices.Data.AdoHelperFactory.CreateHelper(String providerName)
at Cognizant.CAFE.FoundationServices.Data.AdoHelperFactory.CreateHelper()
at Cognizant.CAFE.Frameworks.FoundationAbstraction.Adapters.CAFE.DataAccessAdapter..ctor()
Please advise on how to resolve.
Determine if the third party DLL has an update. Usually system updates target discovered security holes and this targeted dll may have some issue related.
Otherwise you may want to implement a different method of data access or even move the application to .Net 4 which may have the latest methodology.

Issue with Claims after migrating project to MVC5, unexpected call to GetRolesForUser

A project has been updated from MVC 4 to MVC 5 because of new the use of Visual Studio 2015 which was not compiling razor views properly (which is something that's documented by Microsoft and not the issue).
We use an utility class accross projects to retrieve values stored in Identity Claims.
In that class, someone did a call to:
System.Security.Claims.ClaimsPrincipal.Current.Claims.ToList()
which was working in the previous MVC4 version, but after migrating all the Nuget packages required for MVC5, this specific call throws the following error:
An exception of type 'System.ArgumentNullException' occurred in System.Web.Providers.dll but was not handled in user code
Value cannot be null.
Parameter name : username
System.Web.Providers.DefaultRoleProvider.GetRolesForUser(String
username) +183 System.Web.Security.RolePrincipal.GetRoles() +215
System.Web.Security.d__1.MoveNext() +58
System.Security.Claims.d__1.MoveNext() +253
System.Security.Claims.d__1.MoveNext() +209
System.Collections.Generic.List1..ctor(IEnumerable1 collection) +445
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
I did a foreach() on that collection instead, and it's like after all custom defined Claims it's reaching to an unexpected end, or it's trying to retrieve things from the GetRoleForUser and I don't know why.
If anyone has a hint, I can give more details if needed.
Setup of the Web.Config of that MVC project:
<modules>
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="ClaimsAuthorizationModule" type="System.IdentityModel.Services.ClaimsAuthorizationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<remove name="FormsAuthentication" />
</modules>
....
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="http://localhost:58663/" />
</audienceUris>
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
<certificateValidation certificateValidationMode="None" />
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="QuadraSTS">
<keys>
<add thumbprint="XXXHIDDENXXX" />
</keys>
<validIssuers>
<add name="QuadraSTS" />
</validIssuers>
</authority>
</issuerNameRegistry>
<claimsAuthorizationManager type="ClaimsBasedAuthorization.AuthorizationManager,QuadraBox" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" persistentSessionLifetime="1.0:0:0" path="/" />
<wsFederation passiveRedirectEnabled="true" persistentCookiesOnPassiveRedirects="true" issuer="http://something:97/QuadraSTSBeta/" realm="http://localhost:58663/" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
The problem was mainly caused by WebMatrix Data which was improperly trying to load user roles.
Because it was not used in the project, and there was no reason of its presence in this project, I decided to remove it.
Uninstalling the WebMatrix nuget, and removing ALL the references of WebMatrix inside the project resolved the issue.

How do I update my web.config for sending error through email in C#?

I am using Visual Studio 2013, the web server is running .NET 4, and I am getting a error on a web form on the live server, that works fine running on localhost.
It is currently emailing errors when I debug my web application through localhost and I would like it to send me errors when it is live (and if possible, on my localhost as well). It used to send me errors from the production server but when I started debugging, it changed some settings and now it doesn't anymore.
I am assuming that the problem is a setting somewhere, can anyone give some general ideas on where to look for the problem? Here is some code from my web.config for exception handling, is there some other code that could help clarify the problem?
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add toAddress="cynthiat#myurl.com" fromAddress="sysadmin#myurl.com" subjectLineStarter="" subjectLineEnder="" smtpServer="###.###.###.###" smtpPort="##" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Email TraceListener" />
<add source="Enterprise Library Logging" formatter="Text Formatter" log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds5" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Formatted EventLog TraceListener" />
</listeners>
<formatters>
<add template="Extended Properties: {dictionary({key} - {value}
)}
Message: {message}
Timestamp: {timestamp}
Severity: {severity}
Machine: {machine}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="Email TraceListener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="Global Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
We can't help too much with your specific question without seeing more of your config file(s) and/or error handling code that sends e-mail notifications. However, another solution to your problem may be an error hanndling/logging/notification framework, such as:
ELMAH
ELMAH: Error Logging Modules and Handlers for ASP.NET (and MVC too!)
NuGet package - https://www.nuget.org/packages/elmah/
Source - https://code.google.com/p/elmah/
Cloud logging - https://elmah.io
Enterprise Library
Microsoft Enterprise Library
Logging application block
Exception Handling application block

WCF & Castle Windsor - Looks like you forgot

We have recently started migrating to Castle Windsor and i'm having some issues getting our WCF service running. It is a regular windows service NOT HOSTED IN IIS where we serve up SSL material and use a custom X509CertificateValidator to verify the client's presented certificate.
Below is the code i'm using to create the WCF service. It is in a separate project to the WCF service which references it.
public IWindsorContainer RegisterService<T,K>(
IServiceBehavior customBehavior,
Action<ServiceHost> onCreate = null,
Action<ServiceHost> onOpen = null,
Action<ServiceHost> onClose = null,
Action<ServiceHost> onFault = null) where T : class where K : T
{
var facility = this.AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero);
var serviceModel = new DefaultServiceModel()
.OnCreated(onCreate)
.OnOpened(onOpen)
.OnClosed(onClose)
.OnFaulted(onFault);
var service = Component.For<T>()
.ImplementedBy<K>()
.AsWcfService<T>(serviceModel)
.LifestylePerWcfOperation<T>();
if (customBehavior != null)
facility.Register(Component.For<IServiceBehavior>().Instance(customBehavior));
facility.Register(service);
return facility;
}
The service starts as expected (i can navigate to the service using chrome with no issues) and the service is presenting and validating the SSL material (i.e. hits the custom validator) but after that, the client gets this in a FaultException:
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
To fix this add
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
to the <httpModules> section on your web.config.
If you plan running on IIS in Integrated Pipeline mode, you also need to add the module to the <modules> section under <system.webServer>.
Alternatively make sure you have Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 assembly in your GAC (it is installed by ASP.NET MVC3 or WebMatrix) and Windsor will be able to register the module automatically without having to add anything to the config file.
Below is a chunk of my App.Config, i have tried to place the module in all areas that were suggested through googles and through some guesswork:
...
<system.web>
<httpModules>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</httpModules>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</modules>
<handlers>
<add name="PerRequestLifestyle" verb="*" path="*.castle" preCondition="managedHandler" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Microkernel"/>
</handlers>
</system.webServer>
<system.serviceModel>
<extensions>
<endpointExtensions>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</endpointExtensions>
<bindingExtensions>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</bindingExtensions>
<behaviorExtensions>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</behaviorExtensions>
<bindingElementExtensions>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
</bindingElementExtensions>
</extensions>
...
Im pretty much out of ideas. Does anyone know what could be the cause? If not, could anyone explain abit more about the error i'm getting?
Any help would be much appreciated!
Once again i'm answering my own question (the next day after posting, oh dear) :P
This error message is being thrown here (thank god for open source!):
https://github.com/castleproject/Windsor/blob/016730de012f15985410fb33e2eb907690fe5a28/src/Castle.Windsor/MicroKernel/Lifestyle/PerWebRequestLifestyleModule.cs
tldr - see below:
public class PerWebRequestLifestyleModule : IHttpModule
{
...
private static void EnsureInitialized()
{
if (initialized)
{
return;
}
var message = new StringBuilder();
message.AppendLine("Looks like you forgot to register the http module " + typeof(PerWebRequestLifestyleModule).FullName);
message.AppendLine("To fix this add");
message.AppendLine("<add name=\"PerRequestLifestyle\" type=\"Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor\" />");
message.AppendLine("to the <httpModules> section on your web.config.");
if (HttpRuntime.UsingIntegratedPipeline)
{
message.AppendLine(
"Windsor also detected you're running IIS in Integrated Pipeline mode. This means that you also need to add the module to the <modules> section under <system.webServer>.");
}
else
{
message.AppendLine(
"If you plan running on IIS in Integrated Pipeline mode, you also need to add the module to the <modules> section under <system.webServer>.");
}
#if !DOTNET35
message.AppendLine("Alternatively make sure you have " + PerWebRequestLifestyleModuleRegistration.MicrosoftWebInfrastructureDll +
" assembly in your GAC (it is installed by ASP.NET MVC3 or WebMatrix) and Windsor will be able to register the module automatically without having to add anything to the config file.");
#endif
throw new ComponentResolutionException(message.ToString());
}
...
}
From this I quickly gathered that the issue was that the PerWebRequestLifestyleModule was not being initialized, which was ok for me as i did not need it for this service!
Looking further into my own code, some of my repositories that were being loaded for this service were set to use LifestylePerWebRequest from when they were being used in our web console, bingo!
After adjusting them to something else (in this case 'LifestylePerWcfOperation`) all was working fine.

claimsResponse Return Null

hello i have a following code in asp.net. i have used DotNetOpenAuth.dll for openID. the code is under
protected void openidValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
// This catches common typos that result in an invalid OpenID Identifier.
args.IsValid = Identifier.IsValid(args.Value);
}
protected void loginButton_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid)
{
return; // don't login if custom validation failed.
}
try
{
using (OpenIdRelyingParty openid = this.createRelyingParty())
{
IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text);
// This is where you would add any OpenID extensions you wanted
// to include in the authentication request.
ClaimsRequest objClmRequest = new ClaimsRequest();
objClmRequest.Email = DemandLevel.Request;
objClmRequest.Country = DemandLevel.Request;
request.AddExtension(objClmRequest);
// Send your visitor to their Provider for authentication.
request.RedirectToProvider();
}
}
catch (ProtocolException ex)
{
this.openidValidator.Text = ex.Message;
this.openidValidator.IsValid = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.openIdBox.Focus();
if (Request.QueryString["clearAssociations"] == "1")
{
Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore");
UriBuilder builder = new UriBuilder(Request.Url);
builder.Query = null;
Response.Redirect(builder.Uri.AbsoluteUri);
}
OpenIdRelyingParty openid = this.createRelyingParty();
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
// This is where you would look for any OpenID extension responses included
// in the authentication assertion.
var claimsResponse = response.GetExtension<ClaimsResponse>();
State.ProfileFields = claimsResponse;
// Store off the "friendly" username to display -- NOT for username lookup
State.FriendlyLoginName = response.FriendlyIdentifierForDisplay;
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
break;
case AuthenticationStatus.Canceled:
this.loginCanceledLabel.Visible = true;
break;
case AuthenticationStatus.Failed:
this.loginFailedLabel.Visible = true;
break;
// We don't need to handle SetupRequired because we're not setting
// IAuthenticationRequest.Mode to immediate mode.
////case AuthenticationStatus.SetupRequired:
//// break;
}
}
}
private OpenIdRelyingParty createRelyingParty()
{
OpenIdRelyingParty openid = new OpenIdRelyingParty();
int minsha, maxsha, minversion;
if (int.TryParse(Request.QueryString["minsha"], out minsha))
{
openid.SecuritySettings.MinimumHashBitLength = minsha;
}
if (int.TryParse(Request.QueryString["maxsha"], out maxsha))
{
openid.SecuritySettings.MaximumHashBitLength = maxsha;
}
if (int.TryParse(Request.QueryString["minversion"], out minversion))
{
switch (minversion)
{
case 1: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V10; break;
case 2: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20; break;
default: throw new ArgumentOutOfRangeException("minversion");
}
}
return openid;
}
for above code I am always getting
var claimsResponse = response.GetExtension<ClaimsResponse>();
I am always getting claimsResponse == null. What is the reason why it happen. Is there any requirement which is required for openid like domain validation for RelyingParty?? please give me answer as soon as possible.
Also make sure that you have registered the information on your OpenID-account on the provider website, and allowed the information to be sent during the login process. I had the same problem using DotNetOpenAuth but it turned out the I hadn't entered the information on my myOpenID-account. Thought that the email address is always sent, but that is not the case even though the OpenID account is connected to a email address.
So on myOpenID make sure that you have a Registration Persona (Your Account->Registration Personas)
It looks like you're doing everything right. At this point it depends on the Provider you're using. Which one are you testing against? Some don't support Simple Registration (ClaimsRequest) at all. Others only support it for whitelisted RPs. Then others don't support it when your RP is at "localhost".
My advice: test against myopenid.com, as that seems to have good, consistent behavior and support for the Simple Registration extension. But your RP must always be prepared to receive null for ClaimsResponse, since you're never guaranteed the OP will give you anything.
Even if you get a non-null result, individual fields that you asked for (even if you marked them required) may be null or blank.
I dont know if you have solved the problem or not, but I found the solution after many hours of struggle. Actually you need to change your web.config file to claim email and fullname
here is web.config which works for me. I downloaded it from nerddinner project. Actually I copied everything except web.config and I was not getting the email field. So later on I found something else is wrong. I copied web.config from nerddinner project and everything was working.
here is the file, if you dont want to go to nerddinner project.
<?xml version="1.0" encoding="utf-8"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="elmah">
</sectionGroup>
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
</configSections>
<connectionStrings configSource="connectionStrings.config">
</connectionStrings>
<dotNetOpenAuth>
<openid>
<relyingParty>
<behaviors>
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
</behaviors>
</relyingParty>
</openid>
</dotNetOpenAuth>
<system.web>
<!--
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" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Forms">
<forms loginUrl="~/Account/Logon" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
<customErrors mode="RemoteOnly" defaultRedirect="/Dinners/Trouble">
<error statusCode="404" redirect="/Dinners/Confused" />
</customErrors>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Globalization" />
<add namespace="System.Linq" />
<add namespace="System.Collections.Generic" />
</namespaces>
</pages>
<httpHandlers>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</httpHandlers>
<httpModules>
</httpModules>
<trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
</system.web>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
</modules>
<handlers>
<remove name="MvcHttpHandler" />
<remove name="UrlRoutingHandler" />
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<appSettings>
<add key="microsoft.visualstudio.teamsystems.backupinfo" value="8;web.config.backup" />
<!-- Fill in your various consumer keys and secrets here to make the sample work. -->
<!-- You must get these values by signing up with each individual service provider. -->
<!-- Twitter sign-up: https://twitter.com/oauth_clients -->
<add key="twitterConsumerKey" value="" />
<add key="twitterConsumerSecret" value="" />
</appSettings>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</configuration>

Categories

Resources