Sometimes ADFS exception: ID1032 "At least one 'audienceUri' must be specified..." - c#

I have a project which uses ADFS authentication in some cases. The configuration is read from a database and the URLs are different from customer to customer, so there are many configuration options which I can't hard-code in my Web.config.
The problem is that I get the following error:
ID1032: At least one 'audienceUri' must be specified in the SamlSecurityTokenRequirement when the AudienceUriMode is set to 'Always' or 'BearerKeyOnly'
But I don't get it always, and I can't reproduce it. This is pretty annoying since I can't really debug it as long as I can't reproduce it. And I'm not sure whether I did everything correct. Maybe some ADFS expert can have a look at it.
(Trusts between my relying parties and their corresponding ADFS servers have been established, of course.)
Here is my code (only interesting parts of it), please ask if anything is missing or unclear.
Some snippets from my Web.config:
<system.webServer>
<modules>
<add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<add name="ClaimsPrincipalHttpModule" type="Microsoft.IdentityModel.Web.ClaimsPrincipalHttpModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<!-- ... -->
</modules>
<!-- ... -->
</system.webServer>
<microsoft.identityModel>
<service>
<securityTokenHandlers>
<remove type="Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler" />
<add type="MyProject.MachineKeySessionSecurityTokenHandler" />
</securityTokenHandlers>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="false"
issuer="https://fail/IssuerEndpoint"
realm="https://fail/FederationResult"
homeRealm="https://fail"
requireHttps="true" />
</federatedAuthentication>
</service>
</microsoft.identityModel>
Those fail values will be overridden per request (see my Login() method below), but I have to specify something in my Web.config, so I chose to specify a valid URI at least. The default SessionSecurityTokenHandler had to be replaced because my service runs on multiple machines with DNS Round-Robin (sharing the same machine key).
Then I have a class I called AdfsTrustFilter which implements IAuthorizationFilter. I know it's bit of overhead, but due to the project structure, this filter is used as a global filter on every request (order is the least value in the whole project). In the OnAuthorization method, I complete the configuration as follows:
public sealed class AdfsTrustFilter : IAuthorizationFilter
public void OnAuthorization(AuthorizationContext filterContext)
// ...
var fam = FederatedAuthentication.WSFederationAuthenticationModule;
fam.ServiceConfiguration = new ServiceConfiguration
{
AudienceRestriction = new AudienceRestriction(AudienceUriMode.Always),
CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust,
// MyIssuerNameRegistry checks whether a fingerprint is known and some other stuff
IssuerNameRegistry = new MyIssuerNameRegistry()
};
// config.OwnPath contains something like "https://my.app.com/AppRoot/"
fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(config.OwnPath));
}
}
This is the code that starts the authentication:
public ActionResult Login()
{
// ...
// again something like "https://my.app.com/AppRoot/"
string baseUrl = Config.OwnPath.TrimEnd('/') + "/";
// adfs endpoint for this customer: i.e. "https://identity.provider.net/adfs/ls/"
string endpoint = Config.AdfsConfig.IdentityProvider.Endpoint;
// the code behind FederationResult is shown below
var signIn = new SignInRequestMessage(new Uri(endpoint), baseUrl + "/Adfs/FederationResult")
{
Context = baseUrl
};
var url = signIn.WriteQueryString();
return Redirect(url);
}
And finally the FederationResult callback:
public ActionResult FederationResult()
{
WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule;
HttpRequest request = System.Web.HttpContext.Current.Request;
if (fam.CanReadSignInResponse(request, true))
{
var id = (IClaimsIdentity) User.Identity;
// do something
}
// ...
}
P.S.: The ADFS server was recently upgraded from 2008 R2 to 2012, but this didn't change anything. ADFS version was always 2.0.

Since the exception says that you need the audienceUri, I would start by adding one under
<microsoft.IdentityModel>
<service>
<audienceUris>
<add value="https://yourdomain/theaudienceuri" />
The audienceUri is the Uri adfs returns to your application. You can override the engine to accept arbitrary return results which doesn't change the fact that indeed you need at least one uri in the config.

Related

Cannot get NServiceBus to not throw exceptions (MessageQueueException, SqlException, TimeoutPersisterReceiver)

I have a very frustrating NServiceBus problem that I cannot seem to figure out. I am hoping that you guys can shed some light on the situation.
I am currently using NServiceBus.Core v5.0 and NServiceBus.Host v6.0 and running it in Unobtrusive Mode.
It seems that no matter what configuration I use, I always get some kind of error. I will start with the configuration that produces the least problems:
Case 1 - Using custom assembly scanning:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.SetUniqueHostId(endpointName);
configuration.UseSerialization<JsonSerializer>();
configuration.UsePersistence<NHibernatePersistence, StorageType.Outbox>();
configuration.AssembliesToScan(new List<Assembly>
{
GetType().Assembly,
typeof(ICustomCommand).Assembly
});
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
The issues I have noticed here are the following:
When starting the NServiceBus host application and the persistence SQL database does not yet exist, no exception is thrown saying that the database cannot be found (it does in case 2).
I keep getting the following exception:
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver Failed to fetch timeouts from the timeout storage
Which ultimately results in the application crashing because when this error occurs too many times, ServiceBus decides that enough is enough and just throws a fatal exception.
Besides the issues above, the application runs perfectly receiving and processing messages... until the fatal exception occurs
Now, this one is a bit more difficult:
Case 2 - Using default assembly scanning:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.SetUniqueHostId(endpointName);
configuration.UseSerialization<JsonSerializer>();
configuration.UsePersistence<NHibernatePersistence, StorageType.Outbox>();
// !! DISABLED !!
// configuration.AssembliesToScan(new List<Assembly>
// {
// GetType().Assembly,
// typeof(ICustomCommand).Assembly
// });
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
In this case the following issues occur:
When the persistence SQL database does not yet exist:
When starting the NServiceBus host application and the SQL database does not exist, an exception is throw - Expected behavior (This is positive)
After creating the persistence SQL database:
ServiceControl.Plugin.Nsb5.Heartbeat.Heartbeats|Unable to send heartbeat to ServiceControl:
NServiceBus.Unicast.Queuing.QueueNotFoundException: Failed to send message to address: [Particular.ServiceControl#MYPCNAME]
Exception thrown: 'System.Messaging.MessageQueueException' in System.Messaging.dll
Additional information: External component has thrown an exception.
2017-09-15 16:25:45.6743|Warn|NServiceBus.Unicast.Messages.MessageMetadataRegistry|Message header 'SharedTemp.Interfaces.ICustomCommand'
was mapped to type 'SharedTemp.Interfaces.ICustomCommand' but that type was not found in the message registry [...]
Exception thrown: 'System.Exception' in NServiceBus.Core.dll
Additional information: Could not find metadata for 'Newtonsoft.Json.Linq.JObject'.
Now, exceptions 3 and 4 are particularly (no pun intended) odd since the NServiceBus documentation states:
By default all assemblies in the endpoint bin directory are scanned to find types implementing its interfaces so that it can configure them automatically.
And the "Newtonsoft.Json" and my "SharedTemp dll's" are indeed in the BIN folder, but NServiceBus does not seem to find them. As for point 1: NServiceBus does not create that queue for me, but it creates all the other queues that I need.
Finally the always requested app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="MasterNodeConfig" type="NServiceBus.Config.MasterNodeConfig, NServiceBus.Core"/>
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
<section name="AuditConfig" type="NServiceBus.Config.AuditConfig, NServiceBus.Core"/>
</configSections>
<appSettings>
<add key="NServiceBus/Persistence/NHibernate/dialect" value="NHibernate.Dialect.MsSql2012Dialect"/>
<add key="NServiceBus/Outbox" value="true"/>
</appSettings>
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error"/>
<UnicastBusConfig>
<MessageEndpointMappings />
</UnicastBusConfig>
<AuditConfig QueueName="audit"/>
<connectionStrings>
<add name="NServiceBus/Persistence" connectionString="Server=(LocalDB)\v11.0;Initial Catalog=NServiceBus;Integrated Security=true"/>
</connectionStrings>
<system.web>
<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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<MasterNodeConfig Node="localhost"/>
</configuration>
Does anyone have an idea about any of this?
After a lot of searching I finally found the problem!
First of all I was using a in-house NuGet package that was supposed to help me with configuring NServiceBus. The package worked fine for other projects, but for mine not so well, since I was using JsonSerialization instead of the default XML serialization.
The first problem with the package is that it used the "INeedInitialization" interface to configure NServiceBus. In my code I would then call "IConfigureThisEndpoint" to enable the JsonSerialization. The issue here was, that when starting the NServiceBus host, it would fail to find the NewtonSoft.Json library. If I then added custom assembly scanning to my own configuration code, it would not trigger "INeedInitialization", causing an incomplete/incorrect configuration.
I assume it could not load the NewtonSoft.Json library because scanning was triggered in the code/namespace of the package? Maybe #Sean Farmer can answer this?
The second problem with the package is that it would add connection strings to the app.config, one for "NServiceBus/Persistence" and one for "NServiceBus/Persistence/NHibernate/Saga". I am not using Saga, so the connection string for that was not needed. Initially this was not a problem since I caught it the first time, but I completely forgot about it after reinstalling the package. Removing this again also seemed to make NServiceBus happier.
So, what ended up working? I removed the package and did the configuration myself with the following result:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.UniquelyIdentifyRunningInstance().UsingCustomIdentifier(endpointName);
configuration.EnableOutbox();
configuration.UsePersistence<NHibernatePersistence>();
configuration.Transactions().DefaultTimeout(TimeSpan.FromMinutes(5.0));
configuration.UseSerialization<JsonSerializer>();
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
#Sean: Thank you for allowing me to contact you. Luckily it was not necessary
#Mike: Thank you for the input

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.

MySqlProfileProvider can't connect to my DB

I'm working on a website in ASP.NET and unfortunately I have to use MySql to store the site's data.
I'm really struggling to get MySql work with the CreateUserWizard functionality, and I'm just losing it.
Until I defined custom properties in the Web.Config, everything was fine, and I actually managed to register some fake users. Then I wanted to add some other properties, like address, gender, and so on. I added those properties in the Web.Config like this:
Web.Config
<profile enabled="true" defaultProvider="MySqlProfileProvider">
<providers>
<clear/>
<add name="MySqlProfileProvider" autogenerateschema="True" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D" conectionStringName="connMySql" applicationName="/"/>
</providers>
<properties>
<add name="Nome" type="string"/>
<add name="Cognome" type="string"/>
<add name="Sesso" type="string"/>
<add name="DataNascita" type="datetime"/>
<add name="Indirizzo" type="string"/>
<add name="Citta" type="string"/>
<add name="Provincia" type="string"/>
<add name="CAP" type="int"/>
</properties>
</profile>
Please note that my Connection String is correct, since I used it in other parts of my Web.Config and runs just fine.
Later on, in my sign up page, I wrote this code (after validating the input, of course), to update the created user.
register.aspx.cs
protected void wizard1_CreatedUser(object sender, EventArgs e)
{
ProfileCommon p = (ProfileCommon)ProfileCommon.Create(wizard1.UserName, true);
p.Nome = ((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Nome")).Text;
p.Cognome = ((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Cognome")).Text;
p.Sesso = ((DropDownList)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Sesso")).SelectedValue;
p.DataNascita = System.Convert.ToDateTime(((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("DataNascita")).Text);
p.Indirizzo = ((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Indirizzo")).Text;
p.Citta = ((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Citta")).Text;
p.Provincia = ((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("Provincia")).Text;
p.CAP = System.Convert.ToInt32(((TextBox)wizard1.CreateUserStep.ContentTemplateContainer.FindControl("CAP")).Text);
p.Save();
}
All the controls are well positioned into the .aspx page.
So, when I run the page, I can see the form and type the data in. Then my code validates the input, and if it's all correct, it creates the user and gets into the wizard1_CreatedUser function, where it stops at the p.Nome = ... part, which actually is the first instruction that makes use of the MySqlProfileProvider.
It just says Host 'Hostname' is not allowed to connect to this MySQL server BUT MySqlRoleProvider and MySqlMembershipProvider work just fine. In fact, the user is created, but my custom profile data aren't, since the code stops there.
I'm using a DB User with all the privileges.
I'm probably missing something, but I don't really know what.
Thank you.
Turns out that I needed to enable Full Trust.
Also, some files were mispositioned (they were not in the very root of the website).

How to handle log out and redirect

Created a SPA application with .NET Framework 4.5 that will use AngularJS. I implemented the System.IdentityModel per instructions to point to a third party authentication.
Web.config edits:
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
...
<system.web>
<authorization>
<deny users="?" />
</authorization>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime requestValidationType="ourcustomvalidator, ourcustomnamespace" />
<pages controlRenderingCompatibilityVersion="4.0" validateRequest="false" />
</system.web>
....
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
<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" />
</modules>
...
So on initial launch of the Single Page Application, the site redirects to the authorization site. From there you login, authorize and you're redirected back to the application.
Now I have a WebAPI Restful section being a part of the solution as well to log client errors and also to handle logging out within our application. This has lead me to a few problems that I am not grasping:
1) If I make a /api/logoff call to my WebApi, I can call FederatedAuthentication.SessionAuthenticationModule.SignOut(); and I am signed out behind the scenes. Using angular, how should I go about redirecting the user? I noticed after I issue this command, if I hit F5, my site is refreshed but I am automatically logged back in. I would prefer this go back to the login screen I get on initial page load.
2) If I make a /api/custom call to my WebApi and I was logged out behind the scenes, how do I capture that and redirect the user? Right now I am getting an error message along the lines of:
XMLHttpRequest cannot load https://mycustomloginurl.com/?wa=wsignin1.0&wtrealm=http%3a%2f%2flocalhost%3a561…%3dpassive%26ru%3d%252fwebapi%252fims%252ftesting&wct=2014-02-21T21%3a47%3a09Z.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:56181' is therefore not allowed access.
Sorry if this confusing, I am trying to wrap my head around all of this.
Thanks to some more research, this post: Prevent XmlHttpRequest redirect response in .Net MVC WS-Federation Site helped me get to the right answer.
Basically I followed the same code but added the following:
resp.Clear(); // cleared the response
var fa = FederatedAuthentication.WSFederationAuthenticationModule;
var signInRequestMessage = new SignInRequestMessage(new Uri(fa.Issuer), fa.Realm);
var signInURI = signInRequestMessage.WriteQueryString();
resp.Write(signInURI);
So I cleared the response and made the body of the response contain the Sign-In URL for the authentication. In angular, I have a HTTP interceptor that checks for status code 401 and then uses the above data to redirect to the login.
app.config([
'$httpProvider', function($httpProvider) {
var interceptor = ['$rootScope', '$q','$window', function (scope, $q, $window) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
$window.location.href = response.data.replace(/"/g, "");
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}
]);

webservices trace / log

I have set of web services and I want to add a trace layer.
I don't want to modify each web service since I have many.
I would like to write log every entering to a web service: name of web service and parameters.
What is the best way to do so?
P.S. I am using asp.net and C#.
EDIT:
I only want to wrap the web services as each one will have log(..) at the beginning.
A common way to achieve this is to inject a SOAP extension. From there you can intercept every request/response packet in raw SOAP. The sample shows how to implement one, and the explanation describes how it works and how to configure it.
Sample:
http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx
Explanation:
http://msdn.microsoft.com/en-us/library/esw638yk(vs.71).aspx
Configuration:
http://msdn.microsoft.com/en-us/library/b5e8e7kk(v=vs.71).aspx
<configuration>
<system.web>
<webServices>
<soapExtensionTypes>
<add type="{Type name}, {Assembly}" priority="1" group="0" />
</soapExtensionTypes>
</webServices>
</system.web>
</configuration>
Add a Global Application Class Global.asax file to your project and add the logging logic to the Application_BeginRequest() method. The sender object will contain the HTTP Request and parameters. You can filter for just .asmx requests and log those.
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
EDIT--
Give PostSharp a try. It's the easiest way to get this functionality. For posterity I will leave my posting below but just ignore it and use PostSharp.
If your web services are WCF then you should check out http://msdn.microsoft.com/en-us/magazine/cc163302.aspx.
At each step along the way they provide extensibility points that you can plug into. You can use these extensibility points to implement a wide variety of custom behaviors including message or parameter validation, message logging, message transformations.
No doubt this is the way to go for WCF services. Otherwise, if they are just web services then you can use the Unity framework and hookup and Interceptor to do the same thing.
If the progamming language is not important, you may put Apache Synapse as proxy in front of your services. Your clients will then send the requests to Synapse, which will delegate the requests to your original services. The proxy can be configured to do something with the requests in between, such as logging.
Please see the following links for more information:
http://synapse.apache.org/Synapse_Configuration_Language.html#proxy,
http://synapse.apache.org/Synapse_Configuration_Language.html#send,
http://synapse.apache.org/Synapse_Configuration_Language.html#log
A combination of the following examples could work for you:
http://synapse.apache.org/Synapse_Samples.html#Sample0
http://synapse.apache.org/Synapse_Samples.html#ProxyServices
e.g.:
<definitions xmlns="http://ws.apache.org/ns/synapse"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
<proxy name="StockQuoteProxy">
<target>
<endpoint>
<address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
</endpoint>
<outSequence>
<!-- log all attributes of messages passing through -->
<log level="full"/>
<!-- Send the message to implicit destination -->
<send/>
</outSequence>
</target>
<publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
</proxy>
How about writing your own HttpModule? That would negate the need to touch the existing web service code. You would just need to add your module to each web.config file.
I maintain an Open source web services framework that lets you simply achieve this by having all web services inherit from a base class and do your own logging.
Here is an example of a base-class where I maintain a distributed rolling log for all exceptions in redis - a very fast NoSQL data store:
public object Execute(TRequest request)
{
try
{
//Run the request in a managed scope serializing all
return Run(request);
}
catch (Exception ex)
{
return HandleException(request, ex);
}
}
protected object HandleException(TRequest request, Exception ex)
{
var responseStatus = ResponseStatusTranslator.Instance.Parse(ex);
if (EndpointHost.UserConfig.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = GetRequestErrorBody() + ex;
}
Log.Error("ServiceBase<TRequest>::Service Exception", ex);
//If Redis is configured, maintain rolling service error logs in Redis (an in-memory datastore)
var redisManager = TryResolve<IRedisClientsManager>();
if (redisManager != null)
{
try
{
//Get a thread-safe redis client from the client manager pool
using (var client = redisManager.GetClient())
{
//Get a client with a native interface for storing 'ResponseStatus' objects
var redis = client.GetTypedClient<ResponseStatus>();
//Store the errors in predictable Redis-named lists i.e.
//'urn:ServiceErrors:{ServiceName}' and 'urn:ServiceErrors:All'
var redisSeriviceErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, ServiceName)];
var redisCombinedErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, CombinedServiceLogId)];
//Append the error at the start of the service-specific and combined error logs.
redisSeriviceErrorList.Prepend(responseStatus);
redisCombinedErrorList.Prepend(responseStatus);
//Clip old error logs from the managed logs
const int rollingErrorCount = 1000;
redisSeriviceErrorList.Trim(0, rollingErrorCount);
redisCombinedErrorList.Trim(0, rollingErrorCount);
}
}
catch (Exception suppressRedisException)
{
Log.Error("Could not append exception to redis service error logs", suppressRedisException);
}
}
var responseDto = CreateResponseDto(request, responseStatus);
if (responseDto == null)
{
throw ex;
}
return new HttpResult(responseDto, null, HttpStatusCode.InternalServerError);
}
Otherwise for normal ASP.NET web services frameworks I would look at the Global.asax events, specifically the 'Application_BeginRequest' event which Fires each time a new request comes in.
I don't know if this is what you are looking for ,just add this to you WCF config file after the ""
It will create very extensive logging that you will be able to read using the Microsoft Service Trace Viewer
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelMessageLoggingListener">
<filter type="" />
</add>
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Warning, ActivityTracing"
propagateActivity="true">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelTraceListener">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\ServiceLog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
<add initializeData="C:\Tracelog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
</sharedListeners>
</system.diagnostics>

Categories

Resources