Category Archives: .NET

Common Windows Identity Foundation misconceptions

I am on crusade to get Windows Identity Foundation (WIF) adopted by the Microsoft .NET community at large. Why? Because maintaining a user store within an application as is propagated by ASP.NET Membership is just plain stupid these days. Yes, I may be a little harsh with that judgment, but sparing the rod spoils the child. Applications should no longer be islands, but should be working together. And if applications such as Spotify and Flickr can (re)use a user’s identity from Facebook, Twitter, LinkedIn, and so on, why can’t yours?

“A thousand mile journey begins with one step” – Lao Tze

In the past couple of years I’ve been speaking about WIF on many occasions, both at conference and with individual developers. Across the board I can say that WIF is largely misunderstood. Hence my first step is to address some of the misconceptions surrounding WIF, and more in general the concepts underlying WIF.

Misconception 1: WIF is Microsoft-only and not interoperable.

WIF actually implements the WS-Federation standard. Microsoft is an active participant in the standards commonly known as the WS-* specifications, a host of web services specifications for security, transactions, and reliable messaging. The WS-Federation standard is implemented by many other platforms, and WIF can interoperate with these just fine.

Misconception 2: WIF can only be used to secure web applications, not web services.

The WS-Federation protocol defines two profiles: Active and Passive. Passive federation is for browser based applications, because browsers don’t support the full cryptographic stack required for WS-Federation to work. Active federation is used for web services and can be used with clients that do support the needed cryptographic capabilities. I’ll get back to what this all means in another post.

Misconception 3: WIF can only be used to secure web services, not web applications.

See misconception #2.

Misconception 4: WIF is only for cloud (Azure) applications.

WIF works with any application written in .NET 3.5 and up. You can host that application anywhere you like, in the cloud or in your own data center. In fact, there is nothing that prevents you from creating applications with WIF for use in just the local network and for internal use only.

Misconception 5: You can’t do role-based security with WIF.

Quite the opposite is true. You can still do role-based security if you want to, but you can do much more. The underlying protocol is much more flexible, and you can implement security checks in your applications based on the information you get about a use any way you like.

Misconception 6: WIF only adds complexity.

It is indeed true that properly connecting a WIF enabled application to a security token service can be a challenge. You need to get the protocol settings to match and need certificates for encryption and signing. However, inside your applications WIF is just as easy as role-based security as you are used to. If you want to do more elaborate things, things obviously get more complex, but this is true for any type of security.

Misconception 7: To use WIF in an existing application I need to re-architect the whole application.

WIF extends the IIdentity and IPrincipal interfaces. This means that your existing application will keep working if you migrate to WIF to get authenticate and authorize the user. The only thing you need to be aware of is the fact that because you don’t have a local user directory anymore, you can’t do things for which you require information about another user. This means you may have to provide a different way to deal with such scenarios. If you use ASP.NET Profiles for this kind of information, a custom provider may be all you need.

Who is running my Workflow Service?

Workflow Services in .NET 4 allow you to do long running processes. But when you do that, there’s an interesting question: when a workflow has been suspended, under which user is the workflow running when it is active again. To answer this question I created a simple workflow that writes the user in the current thread to a log. On the initial call, the user making the call was logged (in this case I used Windows Identity Foundation to authenticate, but this should be the same for all types of authentication). After a Delay of a minute that user was gone, and instead the user in the current thread was unauthenticated. This means that any code you call from the workflow can’t rely on Thread.CurrentPrincipal to get the proper authorizations. You have to save the user, and somehow reinstate principal so it runs under the original context. Alternatively you can use some form of delegation.

Solving: Could not establish trust relationship for the SSL/TLS secure channel …

Working with Windows Identity Foundation can be quite a minefield. Solve one issue, and the next creeps up. Because it’s all these little tweaks to make it work, I often find myself thinking “How did I solve that last time?” One of those issues is the following exception:
Could not establish trust relationship for the SSL/TLS secure channel with authority ‘somesite.runningunder.ssl’
There are two reasons why you can run into this exception, each discussed below.

The certificate isn’t trusted and/or the URL doesn’t correspond with the URL in the certificate.

If this is the case, you get certificate warnings when you browse to the service WSDL with a browser. The best way to solve the former is to have your (development) environment work with certificates it trusts. This means setting up a Certificate Authority (Active Directory Certificate Services), placing the root CA certificate in the Trusted Root Certificates of the machine your clients (and services) run on, issuing the needed certificates from the CA, and placing these where they are needed. Alternatively, you can just add a
single line of code to your client so it ignores certificate issues before you do any service call:

System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

If after you’ve done the above you still get an exception, the above code is likely not even being hit. That means you (also) have the problem below.

You’ve setup identity trust in your client, and the certificate reference is incorrect.

This often happens when you copied some configuration from somewhere, and forgot to change the corresponding certificate reference. The red stuff in the client configuration below (which is much longer in a real configuration) is the culprit. It should contain the encoded certificate.

    <endpoint address="https://YourServer/Service1.svc"
        <certificate encodedValue="MIIF5jCCBM6gAwIBAgIKYSt2tQA..."/>

To solve this, you need to get the base64 encoded certificate string, and paste it in place of what’s in there now. To get it you can do the following:

  1. Browse to the endpoint with your browser.
  2. View the certificate information.
  3. Save the certificate to file.
  4. Open the certificate with notepad.
  5. Copy the encoded value between the —–BEGIN CERTIFICATE—– and —–END CERTIFICATE—– placeholders.

Solving: The provided URI scheme ‘https’ is invalid; expected ‘http’.Parameter name: via

I’ve been working with WCF for quite a while, and every so often I run into this exception:

ArgumentException: The provided URI scheme 'https' is invalid; expected 'http'.Parameter name: via

The problem is obvious. You’re trying to access a service under HTTPS, but it’s being called with HTTP. Under most bindings you can solve this by adding something like this to the client binding configuration:

<binding name="MyBinding"> 
  <security mode="Transport"> 
    <transport clientCredentialType="None" /> 
    <message clientCredentialType="None"
             establishSecurityContext="false" />

When you use a (custom) ws2007FederationHttp binding, for instance when working with Windows Identity Foundation, the above won’t work. In that case you need to look in the binding for the <httpTransport> element and replace it with <httpsTransport>.

Generic interfacing with Workflow Services

I’m currently working on a project where we have a lot of semi-independent moving parts. One aspect is that we communicate with different applications, in a BizTalk style manner. We do this using Workflow Services to ensure delivery and have fault tolerance when running inside Windows Server AppFabric (see my post What is Windows Server AppFabric and why should I use it?). However, we wanted to ensure that these Workflow Services all provide the same interface from out side of the application, so we can call into them generically. This by the way happens when a status changes occurs on some entity we use. Getting the Workkflow Services to expose the same contract (more or less) is relatively easy. You just ensure that all services use the name namespace, operation name, and parameters. However, calling those generically through WCF was a bigger challenge. Basically we have a table with state transitions, which can hold some string of information about what to do. The choice we made is to have this string be equivalent to the endpoint configuration in the web.config file. Now all we need is a correct WCF contract, and off we go. That took a little tweaking too, but with the help of the below two posts by Ron Jacobs, we were able to pull it off:

Thanks Ron!

How to get {get; set;} properties automatically from the Visual Studio Class Diagram

I sometimes use the Visual Studio Class Diagram when I’m designing a system. Because I like to test my assumptions in such a situation I want to be able to quickly create classes that just work. Unfortunately, when you add a property in a class, Visual Studio generates code like this:

public string SomeProperty
        throw new System.NotImplementedException();

In most cases what I need is:

public string SomeProperty { get; set; }

Fortunately, the PowerToys for the Class Designer and Distributed System Designer solve this problem. After installing these (and turning it on in the Add-In Manager), the right click menu is enhanced with a lot of new options. One of the is Add->Auto-Imlplemented Property, as shown below.

Tips on Finding Performance Issues in Your ASP.NET App – Part 2

Earlier I blogged about finding performance issues in an ASP.NET app “in the large” (see here). I’d like to reiterate that doing this for a web app is critical, because it not only shows you where the bottlenecks are, but also how these affect the entire application. I said I’d follow up on profiling, so here it is…

Once you know what the bottlenecks or “hot spots” are, you can dive into figuring out what the problem is with these pages. This is where profiling comes in. Profiling lets you know what is happening inside your code. It shows you how long a method call is taking and how often a call is made. Both of these are interesting, because performance bottlenecks can be caused by calls taking long, but also by too many calls to a method. Now, I won’t get into the details of how to profile with Visual Studio 2010 (you can read Beginners Guide to Performance Profiling for that), but when you use this tooling, you should focus on one page at a time. The profiler will throw a heap of information at you, so dealing with one page is hard enough. Once you have this information you have to determine what’s really going on. Is this somehting you can fix by changing a few lines of code, or is there a more structural problem you need to solve? Pages that under no load take 10 seconds or more likely have a structural problem, so you need to check if there is a lot of code being executed that is just waste. Also, be sure to focus on big fish first. You can worry about micro-optimizations (such as a different string compare mechanism) later. That said, you should try to make such optimizations part of your coding  guidelines, rather than looking at that afterwards. Micro-optimizations are only really interesting for very high performance apps. A 10th of a second loss here and there isn’t going to make a lot of difference apart from maybe needing to scale-out a little earlier.

lPeriodically calling a function in your web app

A recurring theme in web programming is calling a function periodically and/or at a specific date and time. This has two aspects:

  • Calling a function on a scheduled basis
  • Making sure time-outs don’t interfere

Calling a function on a scheduled basis

To be able to call a function on your web app, you first need an endpoint (a URL) that you can call to kick the function off. In ASP.NET you can do this in several ways:

  1. Create a page that calls the function.
  2. Create a handler (ASHX) that calls the function (more efficient than a page).
  3. Create a WCF service that allows calls with HTTP GET, as discussed in this blog post by Sasi Suryadevara.

With your endpoint in place, you can use the Windows Task Scheduler to invoke the function at any given time and at intervals as low as one minute. With the Windows Task Scheduler you have several options again:

  1. Create a VB Script that calls the URL, as discussed in this blog post by Steve Schofield.
  2. Create a PowerShell script that calls the URL (same as option 1, but more modern).
  3. Have the Windows Task Scheduler open Internet Explorer and open the specified URL (e.g. C:\PROGRA~1\INTERN~1\iexplore.exe -extoff, which starts IE without extensions). If you do this, you also need to specify that the Task Scheduler closes IE after 1 minute, which you can do in the Settings tab of the task (Windows 2003), or in the Trigger configuration (Windows 2008), as shown below. NOTE: I’ve found that IE sometimes doesn’t close, even if you tell Windows to close it. Eventually this will cripple your scheduled task.

Task Settings in Windows 2003

Trigger configuration in Windows 2008

Note: In Windows 2008 the dropdowns governing duration and interval show 30 minutes as lowest value. You can in fact change this to 1 minute by editing the text.

Making sure time-outs don’t interfere

A web based call is bound to time-out after a few minutes. If you task takes longer than that, this may abort the call depending on how you programmed it, and what webserver settings are used with regards to disconnected clients. To ensure a time-out does not interfere, you can spawn a new thread and have it call the function. That way the thread handling the request can return a response to the client, and the function is carried out regardless. One issue that may arise there is that the function itself hangs or takes too long. You may want to add logic to ensure that it’s aborted after a certain time, and add logging to notify you of this, and possibly also ensure that the function can only be run by one caller at a time.

System.IdentityModel.Claims.ClaimTypes vs. Microsoft.IdentityModel.Claims.ClaimTypes

Windows Identity Foundation introduces a new ClaimTypes class. It contains predefined claim type URIs for claims defined by OASIS and Microsoft. In the WIF SDK project templates for a custom STS this ClaimTypes class is mixed with the one already in System.IdentityModel.Claims, which is rather confusing. So, what’s the difference?

Functionally: None. All claim type URIs in Microsoft.IdentityModel.Claims.ClaimTypes are identical to corresponding types in System.IdentityModel.Claims.ClaimTypes. That said, Microsoft.IdentityModel.Claims.ClaimTypes adds a few new claim types.

Technically: Claim types in System.IdentityModel.Claims.ClaimTypes are defined as static read only string properties, whereas in Microsoft.IdentityModel.Claims.ClaimTypes the claim types are string constants.

My advice: for clarity always use Microsoft.IdentityModel.Claims.ClaimTypes.