BASTA! Spring 2014: Unterlagen

Die BASTA! Spring ist rum, und wieder einmal war es super. Danke an die Organisierer und natürlich an die Teilnehmer!

Hier sind die Folien zu meinen Vorträgen:

Zu den Ganztages-Workshops am Montag und Freitag gibt es naturgemäß keine Folien Winking smile

Für den Freitags-Workshop “End-to-End-Implementierung einer Cross-Platform Modern Business Application” gibt es hier das “laufende” GitHub-Repository, in das Ingo Rammer und ich während des Tages immer hinein ge-psuhed haben.


Viel Spaß!

Hands-On Course: "ASP.NET Web API & SignalR: lightweight web-based architectures for you!"

Come and join me Oct 30-31, 2013 in Oslo for a two days hands-on course organized by ProgramUtvikling.

ASP.NET Web API & SignalR: lightweight web-based architectures for you!"

Time for change: whether it is a classic desktop application, a public or internal web site or a variety of mobile apps - customers and end-users long for multiple ways to access and work with data and processes. Web-based architectures, patterns and techniques can make the life of software architects and developers considerably easier in the face of these requirements.

Let's face it! The current trends and developments especially in the area of mobile platforms & devices and cloud computing will cause a re-thinking in architectural aspects for many software projects and products. If you ignore this today you may be in big trouble tomorrow. How can I reach a plethora of users and client devices? How can I integrate my systems and application parts in a lightweight and interoperable manner? How am I able to push data in near-real-time fashion from my services to my clients?
This course tries to answer these and more questions. Christian Weyer will show you in a pragmatic way how to face the new challenges. See all of this coming to life by using technologies and frameworks like ASP.NET Web API, SignalR, .NET- and HTML5/JavaScript-based clients - mobile or not.


More information at the ProgramUtvikling web site.
See you there!


New ebook chapter published: Properly integrating SignalR hubs with your AngularJS applications

Ingo and I just published a new book chapter of our online (continuously deployed) ebook.
The topic this time is about properly integrating SignalR hubs with your AngularJS applications to realize near realtime push communication. For web browser, desktop or mobile apps.

"Pushing Data: Integrating With ASP.NET SignalR Hubs"

In modern applications the end users want to get their data. They want it now, they want it up-to date. In fact it does not matter whether these are pure web application, native desktop installations or mobile apps: everybody wants his data now!

For .NET-minded developers there are a numbers of options to implement near-real-time push style communication from the server/the services to the clients/consumers. You can choose plain HTTP or the super-new WebSockets features available in .NET 4.5 together with Windows 8 and Windows Server 2012. But the coolest and increasingly popular approach is to use a new framework: ASP.NET SignalR.

While it is not intended- and surely beyond the scope of this ebook - to give an introduction or even deep dive into SignalR, we need to have a look at some concepts and code in order to realize a smooth integration of SignalR and AngularJS.

The final goal of this chapter is to have an AngularJS-style integration of calling and listening to server-side SignalR push services.



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.


Ain’t no IIS: Self-hosting thinktecture IdentityServer v2 – a simple proof-of-concept

There have been a couple of people asking for a sample how to host the ‚non-visual' parts of thinktecture IdentityServer v2 outside of IIS & ASP.NET. E.g. in a Windows or a Console (no, not really…) application.

Here on GitHub you will find a very simple simple PoC which hosts the OAuth2 token endpoint. That said, it is obviously by no means feature complete.
This endpoint uses ASP.NET Web API and thus self-hosting is kinda piece of cake.

namespace SelfHostConsoleHost


    internal class SelfHostServer


        private HttpSelfHostServer selfHost;



        public IConfigurationRepository ConfigurationRepository { getset; }


        public async void Start(string baseAddress)


            var httpConfig = new HttpSelfHostConfiguration(baseAddress);


            Database.SetInitializer(new ConfigurationDatabaseInitializer());


            Container.Current = new CompositionContainer(new RepositoryExportProvider());



            ProtocolConfig.RegisterProtocols(httpConfig, ConfigurationRepository);


            selfHost = new HttpSelfHostServer(httpConfig);

            await selfHost.OpenAsync();



        public async void Stop()


            if (selfHost != null)


                await selfHost.CloseAsync();






As said, it just offers one endpoint:

namespace SelfHostConsoleHost


    public class ProtocolConfig


        public static void RegisterProtocols(HttpConfiguration httpConfiguration, IConfigurationRepository configuration)


            // necessary hack for now - until the DI implementation has been changed

            var a = Assembly.Load("Thinktecture.IdentityServer.Protocols");


            var clientAuthConfig = CreateClientAuthConfig();


            httpConfiguration.MessageHandlers.Add(new RequireHttpsHandler());


            if (configuration.OAuth2.Enabled)



                    name: "oauth2token",

                    routeTemplate: Thinktecture.IdentityServer.Endpoints.Paths.OAuth2Token,

                    defaults: new { controller = "OAuth2Token" },

                    constraints: null,

                    handler: new AuthenticationHandler(clientAuthConfig, httpConfiguration)





        public static AuthenticationConfiguration CreateClientAuthConfig()


            var authConfig = new AuthenticationConfiguration


                InheritHostClientIdentity = false,

                DefaultAuthenticationScheme = "Basic",



            // accept arbitrary credentials on basic auth header,

            // validation will be done in the protocol endpoint

            authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);


            return authConfig;





Again: the code is here: Self-Hosted IdentityServer v2 PoC

Hope this helps.

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:

1: <connectionStrings>

2: <add name="IdentityServerConfiguration"

3: connectionString="Server=tcp:…,1433;

4: Database=idsrvcloud;User ID=christian@…;Password=...;

5: Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"

6: providerName="System.Data.SqlClient" />


8: <add name="ProviderDB"

9: connectionString="Server=tcp:…,1433;

10: Database=idsrvcloud;User ID=christian@…;Password=...;

11: Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"

12: providerName="System.Data.SqlClient" />

13: </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):
   1:  <system.web>

2: <machineKey

3: decryptionKey="46CD6B691..."

4: validationKey="EC4752081..."

5: decryption="AES"

6: validation="HMACSHA256" />

7: ...


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.

OAuth2 in thinktecture IdentityServer v2: Implicit Grant Flow with JavaScript

Our thinktecture IdentityServer version 2 will be a very different and very powerful identity beast!

Dominick already talked quite a bit about the features and how to use them. And Brock is surely at it as well.

Today I will show how to use IdentityServerv2 to implement the OAuth2.0 implicit grant flow as outlined in the official OAuth2 spec – and we are going to use a JavaScript client for that.

For the sake of a little bit of mobile-ness I am going to use KendoUI Mobile to have a native looking mobile UI (which you could then combine e.g. with Cordova/PhoneGap to create a native app).

We are going to look to secure a super novel and world overtaking… TODO app Smile


Admittedly, this is only the basic gist of what an app should look like and feature-wise we will focus on the OAuth part today.
First let’s head to IdentityServer an create a new OAuth Client like this:


One important part of the configuration is the callback/redirect URI. This is where the IdP sends us the token to.

In addition, we need a relying party/resource we can use to create tokens for and which will accept these tokens coming from our JavaScript clients.


Alright, time to jump on to the client side.
I try to encapsulate my JS code as much as possible. One nice pattern to get a basic structure is MVVM and KendoUI has good support for that.

The page above for the Start tab has a viewmodel which does just fire up the OAuth process (in this case the authentication):

   1:  var startViewModel = kendo.observable({
   2:      openLoginView: function () {
   3:          oauth2ViewModel.openAuthWindow(
   4:             endpoints.IdpOauthEndpointUrl);
   5:      }
   6:  });

The OAuth viewmodel holds the token and offer methods to kick off the login process and parse the token from the return URL.

   1:  var oauth2ViewModel = kendo.observable({
   2:      token: "",
   4:      openAuthWindow: function () {
   5:          var url = endpoints.IdpOauthEndpointUrl + "?" 
   6:             + $.param(oAuthConfig);
   7:, "Login", "height=500,width=350");
   8:      },
  10:      loginCallback: function (params) {
  11:          this.token = params["access_token"];
  12:          window.kendoMobileApplication.navigate("#todosPage");
  13:      }
  14:  });

In order to craft the correct URL for IdentityServer we need a couple of parameters which need to correspond to what we previously set up in IdSrv for the OAuth client and the RP (see the IdSrv screenshots above):

   1:  var endpoints = {
   2:      IdpOauthEndpointUrl: "https://localhost/idsrv/issue/
   3:         oauth2/authorize"
   4:  };
   6:  var oAuthConfig = {
   7:      client_id: "tt_tudus",
   8:      scope: "",
   9:      response_type: "token",
  10:      redirect_uri: "http://localhost/simpletudus/
  11:         oauthcallback.html"
  12:  }

Alright. Let’s look at the flow now.
Once we clicked on Login a new window pops up which loads the IdentityServer login page:


After loging into IdSrv we get the resource consent page and choose to allow access:


IdSrv will now send the token to callback URL specified earlier in the IdSrv config.

This URL looks something like this:


The code of the oauthcallback.html page is pretty simple. It parses the token from the hash (#) part of the URL and fires an event on the calling page to pass over the token (see the Google OAuth developers page for more details on the process):

   1:  <script src="js/libs/jquery-1.7.1.min.js" type="text/javascript"></script>
   2:  <script src="js/libs/" type="text/javascript"></script>
   4:  <script type="text/javascript">
   5:      //var params = {}, queryString = location.hash.substring(1),
   6:      //    regex = /([^&=]+)=([^&]*)/g, m;
   8:      //while (m = regex.exec(queryString)) {
   9:      //    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  10:      //}
  12:      var params = $.deparam.fragment(
  13:         location.hash.substring(1));
  15:      window.opener.oAuthCallback(params);
  16:      window.close();    
  17:  </script>

: I am using jQuery BBQ in the above code to parse the URL, the commented code shows how to do it without any external library.

In the main page we have some kind of a proxy event handler which just passes the token on to the above shown OAuth viewmodel:

   1:  <script>
   2:      function oAuthCallback(params) {
   3:          oauth2ViewModel.loginCallback(params);
   4:      }
   5:  </script>

In the OAuth viewmodel login callback method we then simply set the token and trigger navigation to the TODO items page.

When hitting the refresh button in the upper left side of the Items view the actual call to the resource is made with standard jQuery. This happens in the loadTodos call:

   1:  var todosViewModel = kendo.observable({
   2:      todosSource: new
   3:         { sort: { field: "title", dir: "asc" } }),
   5:      loadTodos: function () {
   6:          var self = this;
   8:          dataservices.getTodos(oauth2ViewModel.token)
   9:              .done(function (data) {
  10:        ;
  11:              });
  12:      }
  13:  });

The data services logic is embedded in its own ‘class’ and simply uses the token acquired before to set the appropriate Bearer Authorization header before making the jQuery GET request against the TODO items resource (which is implemented with ASP.NET Web API, BTW):…

   1:  var dataservices = (function () {
   2:      function beforeSend(xhr, token) {
   3:          xhr.setRequestHeader("Authorization", 
   4:             createBearerHeader(token));
   5:      }
   7:      function createBearerHeader(token) {
   8:          var header = "Bearer " + token;
   9:          return header;
  10:      }
  12:      return {
  13:          getTodos: function (token) {
  14:              return $.ajax({
  15:                  url: endpoints.ServiceEndpointUrl,
  16:                  type: "get",
  17:                  dataType: "json",
  18:                  beforeSend: function (xhr) { beforeSend(xhr, token); }
  19:              });
  20:          }
  21:      };
  22:  }());

And voila…:


So please head to GitHub and get the IdSrv bits and give us feedback – thanks!

The entire code for this complete end-to-end sample can be found on GitHub.

Hope this helps.