WCF / Indigo Feed

Infos zu meinen Sessions & dem Workshop auf der BASTA! Spring 2013

Erst einmal nochmals vielen lieben Dank an alle, die in meine beiden Breakout Sessions und meinen Ganztages-Workshop in Darmstadt gekommen sind!

Da ich ja in meinen beiden Sessions keine "wirklichen" Foliensätze verwendet hatte sondern Demos und Code gezeigt habe, gibt es dieses Mal nix zum Downloaden ;) Beim Workshop war es ja genauso - interaktiv!

Hier aber die versprochenen Links zum Code & den Demos:

Danke und bis bald.

 


Running thinktecture IdentityServer v2 in a Windows Azure Web Role – from zero to hero (a walkthrough)

OK, I think a couple of you guys already did it successfully – others just look for something written. Here we go.

Let's start right away by browsing to GitHub and clone the IdentityServer.v2 repo:

After cloning we have the following code structure in Windows Explorer:

Open Thinktecture.identityServer.sln as an elevated admin (for the Windows Azure Compute Emulator to work correctly). Build the entire solution.

No, choose Add… New project… and add a new Cloud project to the solution.

In the Cloud Service dialog do not choose any new project, just hit OK.

We now add the existing IdSrv WebSite project as a Web Role to the Windows Azure project, just like so:…

For now, the solution should look something like this:

Alright. On to some essential Cloud stuff now.

We need an SSL certificate. I am going to use an existing self-issued cert from my local machine. This of course needs to be a 'real' certificate if you deploy IdSrv as a production STS to Windows Azure – of course

Please head over to WebSite role configuration and the Certificates tab. Specify your desired certificate:

Based on this certificate we now create an SSL endpoint:

OK, this should be it for now.

Let's attack the database side of things. We need a SQL database for our identity configuration and data. I am going to create a new one via the Windows Azure management portal:

Please make a note of the connection string for your SQL database as we still need to change the connection strings inside IdentityServer's configuration files.

Then open up connectionString.config in the Configuration folder inside the WebSite project and adjust the connection strings to point to your SQL database in the Cloud:

 

<connectionStrings>
    <add name="IdentityServerConfiguration"
    connectionString="Server=tcp:….database.windows.net,1433;
    Database=idsrvcloud;User ID=christian@…;Password=...;
    Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
    providerName="System.Data.SqlClient" />

    <add name="ProviderDB"
    connectionString="Server=tcp:….database.windows.net,1433;
    Database=idsrvcloud;User ID=christian@…;Password=...;
    Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
    providerName="System.Data.SqlClient" />
</connectionStrings>

… drum roll …

F5 (with the Cloud project as the startup project) and pray …

Enter the basic setup information you need to enter and you should be good to go. This locally running instance inside Windows Azure Compute Emulator already uses the Cloud SQL database – just for the records.

Done… well almost … I am spilling the beans already now so that we can save some cycles.

There is an issue with the Membership hash algorithm type on Cloud VMs.

  • Locally: HMACSHA256
  • Azure Cloud Emulator: HMACSHA256
  • Published to Cloud Service: SHA1

So it looks like there must some machine.config setting in Cloud Service images – Microsoft is investigating this.

For us it means we need to set the keys explicitly in web.config (you can use a tool like this):

<system.web>
    <machineKey
        decryptionKey="46CD6B691..."
        validationKey="EC4752081..."
        decryption="AES"
        validation="HMACSHA256" />
...

OK.

After that we need to export the SSL cert, anyways, so that we can upload it to the Cloud Service , e.g. via the management portal.

And then, we finally can publish & deploy to Windows Azure:

After approx. 8 to 10 minutes we have our thinktecture IdentityServer v2 running up in the Cloud.

Hope this helps.


You thought identity management is ‘done’? Think twice: thinktecture IdentityServer v2 Beta is here

The Beta version of our open source IdentityServer STS has been released today:

http://leastprivilege.com/2012/10/12/thinktecture-identityserver-v2-beta/

 

Check out the short intro video to get a quick start:

http://leastprivilege.com/2012/10/12/setup-thinktecture-identityserver-v2-in-7-minutes/

 

Any feedback is always welcome and highly appreciated! Dominick and Brock (and a little bit of myself will hang out there…)
https://github.com/thinktecture/Thinktecture.IdentityServer.v2/issues

 

Thanks.


Unterlagen & Demos von der BASTA! 2012

Wie in meinen Vorträgen, in der Keynote und im Panel versprochen, hier nun die Slides und Demos zu meinen Auftritten auf der BASAT! 2012.

  • Für jedermann: Leichtgewichtige Services-Architekturen mit Web-APIs
  • Leicht gemacht: Push-Kommunikation mit SignalR
  • Messaging mit .NET für jedermann – in der Cloud und lokal: Windows [Azure | Server] Service Bus
  • Mobile und Cloud: Apps und Devices mit, in und über Windows Azure verbinden

 

Vielen Dank an alle, die in den Vorträgen waren – und Danke an die Organisatoren der BASTA!


Federating Windows Azure Service Bus & Access Control Service with a custom STS: thinktecture IdentityServer helps with more real-world-ish Relay and Brokered Messaging

The Windows Azure Service Bus and the Access Control Service (ACS) are good friends – buddies, indeed.

Almost all official Windows Azure Service Bus-related demos use a shared secret approach to authenticate directly against ACS (although it actually is not an identity provider), get back a token and then send that token over to the Service Bus. This magic usually happens all under the covers when using the WCF bindings.

All in all, this is not really what we need and seek for in real projects.
We need the ability to have users or groups (or: identities with certain claims) authenticate against identity providers that are already in place. This IdP needs to be federated with the Access Control Service which then in turn spits out a token the Service Bus can understand.

Wouldn’t it be nice to authenticate via username/password (for real end users) or via certificates (for server/services entities)?

Let’s see how we can get this working by using our thinktecture IdentityServer. For the purpose of this blog post I am using our demo IdSrv instance at https://identity.thinktecture.com/idsrv.

The first thing to do is to register IdSrv as an identity provider for the respective Service Bus ACS namespace. Each SB namespace has a so called buddy namespace in ACS. The buddy namespace for christianweyer is christianweyer-sb. You can get to it by clicking the Access Control Service button in the Service Bus portal like here:

image

In the ACS portal for the SB buddy namespace we can then add a new identity provider.

image

image

thinktecture IdentityServer does support various endpoints and protocols, but for this scenario we are going to add IdSrv as a WS-Federation-compliant IdP to ACS. At the end we will be requesting SAML token from IdSrv.

image

The easiest way to add it to ACS is to use the service metadata from https://identity.thinktecture.com/idsrv/FederationMetadata/2007-06/FederationMetadata.xml

Note: Make sure that the checkbox is ticked for the ServiceBus relying party at the bottom of the page.

image

Next, we need to add new claims rules for the new IdP.

Let’s create a new rule group.

image

I am calling the new group IdSrv SB users. In that group I want to add at least one rule which says that a user called Bob is allowed to open endpoints on my Service Bus namespace.

image

In order to make our goal, we say that when an incoming claim of (standard) type name contains a value Bob then we are going to emit a new claim of type net.windows.servicebus.action with the Listen value. This is the claim the Service Bus can understand.
Simple and powerful.

image

We could now just add a couple more rules here for other users or even X.509 client certificates.

Before we can leave the ACS configuration alone we need to enable the newly created rule group on the ServiceBus relying party:

image

… and last but not least I have to add a new relying party configuration in Identity Server for my SB buddy namespace with its related WRAP endpoint:

image

Done.

For using the external IdP in my WCF-based Service Bus applications I wrote a very small and simpler helper class with extension methods for the TransportClientEndpointBehavior. It connects to the STS/IdP requesting a SAML token which is then used as the credential for the Service Bus.

 

using System;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Security;
using Microsoft.IdentityModel.Protocols.WSTrust;
using Microsoft.IdentityModel.Protocols.WSTrust.Bindings;
using Microsoft.ServiceBus;

namespace ServiceBus.Authentication
{
    public static class TransportClientEndpointBehaviorExtensions
    {
        public static string GetSamlTokenForUsername(
           this TransportClientEndpointBehavior behavior, string issuerUrl, string serviceNamespace, 
           string username, string password)
        {
            var trustChannelFactory =
                new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress(new Uri(issuerUrl)));

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
            trustChannelFactory.Credentials.UserName.UserName = username;
            trustChannelFactory.Credentials.UserName.Password = password;

            try
            {
                var tokenString = RequestToken(serviceNamespace, trustChannelFactory);
                trustChannelFactory.Close();

                return tokenString;
            }
            catch (Exception ex)
            {
                trustChannelFactory.Abort();
                throw;
            }             
        }       

        public static string GetSamlTokenForCertificate(
           this TransportClientEndpointBehavior behavior, string issuerUrl, string serviceNamespace, 
           string certificateThumbprint)
        {
            var trustChannelFactory =
                new WSTrustChannelFactory(
                    new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress(new Uri(issuerUrl)));

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
            trustChannelFactory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                certificateThumbprint);

            try
            {
                var tokenString = RequestToken(serviceNamespace, trustChannelFactory);
                trustChannelFactory.Close();            

                return tokenString;
            }
            catch (Exception ex)
            {
                trustChannelFactory.Abort();
                throw;
            }                
        }

        private static string RequestToken(string serviceNamespace, WSTrustChannelFactory trustChannelFactory)
        {
            var rst =
                new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue, 
                   WSTrust13Constants.KeyTypes.Bearer);
            rst.AppliesTo = new EndpointAddress(
                String.Format("https://{0}-sb.accesscontrol.windows.net/WRAPv0.9/", serviceNamespace));
            rst.TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11;

            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
            var token = channel.Issue(rst) as GenericXmlSecurityToken;
            var tokenString = token.TokenXml.OuterXml;

            return tokenString;
        }
    }
}

 

Following is a sample usage of the above class.

static void Main(string[] args)
{
    var serviceNamespace = "christianweyer";
    var usernameIssuerUrl = 
       "https://identity.thinktecture.com/idsrv/issue/wstrust/mixed/username";

    var host = new ServiceHost(typeof(EchoService));

    var a = ServiceBusEnvironment.CreateServiceUri(
        "https", serviceNamespace, "echo");
    var b = new WebHttpRelayBinding();
    b.Security.RelayClientAuthenticationType =
        RelayClientAuthenticationType.None; // for demo only!
    var c = typeof(IEchoService);

    var authN = new TransportClientEndpointBehavior(); 
            
    var samlToken = authN.GetSamlTokenForUsername(
        usernameIssuerUrl, serviceNamespace, "bob", ".......");
                        
    authN.TokenProvider =
        TokenProvider.CreateSamlTokenProvider(samlToken);

    var ep = host.AddServiceEndpoint(c, b, a);
    ep.Behaviors.Add(authN);
    ep.Behaviors.Add(new WebHttpBehavior());

    host.Open();
    Console.WriteLine("Service running...");

    host.Description.Endpoints.ToList()
        .ForEach(enp => Console.WriteLine(enp.Address));

    Console.ReadLine();
    host.Close();
}

 

And the running service in action (super spectacular!)

image


Hope this helps!


Measuring performance of your HTTP-based .NET applications: Performance Counters for HttpWebRequest

Just found this and thought to share it with you: Network Class Library Team (System.Net): New Performance Counters for HttpWebRequest

 

Each of the seven green circles represents one of the six performance counters (there are two ‘5’ items because 5 is the average lifetime, and there are two code paths that will affect that counter).

 

Note: Be aware that ‘new’ means new in .NET 4.0 (the blog post is from Aug 2009).


You think WCF needs more of ‘you’? Go and vote for your most desired features now

The WCF team has set up a uservoice page for voting on WCF v-Next features. Go ahead and influence WCF!


Slides for my sessions at DevWeek 2012

And here we go – as promised to all of you nice people attending one of my sessions last week in London.

 

If you have questions, please feel free to send my an email!

See you next year at DevWeek.


Light-weight web-based architectures: Web APIs & Services (or: ASP.NET vs. WCF?) – a personal view

As much as I like WCF (and as much as I made money with it in the past years) – I think it is now time to re-think some approaches and some architectural ideas. What is ahead of a lot of us is what I call ‘light-weight architectures for reach’.

Just to give you some scope: I am one of the original Digerati board members of Indigo (WCF). Some people say I know WCF inside-out - I have given several dozens of introductions to WCF in seminars, conference and user group sessions world-wide and did numberless consulting gigs in Europe with WCF (and no, I did not really find time to write a book – besides a chapter here).

OK, so here goes...

There is currently a shift - or rather a new focus - in distributed application architecture. And no, I am not going to call it REST and I am not saying it is the one and only true thing from now on. But we have new drivers like application mash-ups, mobile devices and cloud computing which force us to move away from the good old feature-rich (and somehow heavy-weight) SOAP-based approaches. This development and this need is non-discussable and undeniable. One possible solution to these new needs is the use of light-weight Web APIs (which can be evolved into a REST-ful API or be used 'just' in an RPC-ish way).

So, which technology framework should we as .NET developers choose to build Web APIs? One choice is to leverage WCF's WebHttp model. After working with it for some years I quickly noticed a number of shortcomings (testability/mockability, serializers, ...) and wished that Redmond would come up with something better. *Of course* it had to be WCF, it had to be part of the overall "let's abstract away communication 'details'". And so it happened that they announced WCF Web API (and I was lucky enough to be part of the advisory board, again). All was fine in my world. It seemed.

Fine until I again realized that it has shortcomings when building some more flexible and advanced Web APIs. But this time it was actually the fact that the limitations were in WCF itself. The 'SAOP message' model of WCF just does not fit at all into this world. Everything the team tried to accomplish and to provide features for a web-based paradigm was just trying to put the round into the rectangle (and vice versa). For a web-based base framework maybe WCF is not the right choice.
And it turned out that there is a very good framework that can deal with the web and HTTP in a fantastic way. So, the decision to build a .NET web API framework on ASP.NET (and ASP.NET MVC, to be more precise) was somehow natural.
I personally had one very strong wish - something I have learned in the past years is invaluable for a lot of our customers... self-hosting! So, the advisors pushed hard to get self-hosting, and here it is: we can perfectly build our own host processes and host the exact same Web API implementation either there or in IIS/ASP.NET.

Today, I am quite happy with what happened. The only issue I still have is the name: I would definitely have not called it ASP.NET Web API, but rather .NET Web API. If you are working in my geographical area then you may understand why.

Anyway... talking a bit about application architecture (.NET server-side):
I would build a WCF service and an ASP.NET Web API (at least with the RPC-ish approach) as a facade only - the actual logic (business logic or data/resource access) is hidden beyond that facade. With this simple pattern it is no problem to have both WCF SOAP services and ASP.NET Web APIs sitting right next to each other happily ever after. I am doing it all the time. And you are then actually in the power to leverage the full power of each framework - get the most out of SOAP/XSD/WSDL/WS-* and the best out of web APIs/REST/whatever.

Fact is, I am using Web APIs quite a lot these days as we are building cloud-based systems in an increasing number and also cross-device mobile apps.

My 2 services cents.
Flame away.


Slides von der BASTA! Spring 2012

Vielen Dank an alle, die in meine Sessions (inklusive der Keynote) und die Sessions der anderen thinktecture-Experten gekommen sind – war mal wieder eine prima BASTA!

Bis zum nächsten Mal!