Windows Store App demo with OAuth 1.x and OAuth 2.0

There are several demo’s online that connect a Windows Store App to Facebook, Twitter, etc. using OAuth 1.x and OAuth 2.0.  Although these demo’s show how this works, the code is hard to reuse across applications, because it is tightly coupled to the main app page. I’ve completely rewritten the code to make the code reusable, and to make the OAuth 1.x and OAuth 2.0 interface almost identical, so you can use a single codebase to connect with both protocols. You can download the OAuth demo (71 KB), which includes an OAuth 1.x library you can use in the same manner as with OAuth 2.0.

Book Review – Arduino Workshop: A Hands-On Introduction with 65 Projects

Before reading Arduino Workshop: A Hands-On Introduction with 65 Projects (John Boxall, No Starch Press) I knew what Arduino was, but other than that knew nothing about it. This book for me was the perfect starting point, because it not only tells you what Arduino is, but effectively demonstrates its capabilities. Along the way you get a crash course in electronics (resistors, transistors, switches etc.) and programming. I personally didn’t need the latter, but for people with no programming experience this book will do the trick. That said, I believe the learning curve is quite steep, so you may want to look at another book for the basics of programming (preferably in a language like C#, Java or Javascript), as that comes close to the language used with Arduino). Overall this book is a good read to get started with Arduino. It is written fairly well and the projects give you a good idea of the possibilities. You can also pick stuff from the projects to use in your own. Because some projects build on previous projects, you get a sense of how to build something with Arduino.

Migrated my blog to WordPress

I’ve been wanting to migrate my blog to WordPress for quite a while, and I finally did it.

Why?
Even though dasBlog is a nice blogging engine, it is not quite as feature rich and user friendly as WordPress. There are tons of plugins and templates for WordPress that make my life as a blogger easier, and give the reader a better user experience.

I also wanted my blog to be more than just my blog, and you’ll see some additional pages appear of the course of time. This too I could have done with dasBlog, but it is much easier with WordPress.

How?
Reeves Little has an awesome post on migrating from dasBlog to WordPress, which I followed to the letter. Many thanks to him. It took me about 4 hours to do with some trial and error, mainly because of my large BlogML file.

Now what?
As I just mentioned I will add some pages to the site. This will mostly be self gratified boasting of what I’ve done as an author. I will also be tinkering with the layout, in search of the ultimate look & feel. Last but not least, I will be checking all the posts for broken stuff and to clean up the code listings which are filled with formatting no longer needed, a few posts at a time. Feel free to drop me a line of you find a post with errors.

Book Review – Disruptive Possibilities: How Big Data Changes Everything

Even though this is just a little book (just 80 pages), Disruptive Possibilities: How Big Data Changes Everything (Jeffrey Needham, O’Reilly) is a very good and insightful read. Jeffrey Needham explains very well what Big Data is and how it differs from “traditional” computing. He effectively shows you need to approach Big Data differently, because the “old school” approach to data just doesn’t scale. In that sense he echo’s my view on the subject of data: not all data needs to be normalized and transactional and you can save a lot of effort and money (on expensive hardware and software) by picking the right requirements for types of data you are dealing with. For instance, you would need a pretty good reason to store a file in a RDBMS. Because most current IT staff has been brought up with in the RDMBS paradigm, it is often the tool of choice, without thinking about it. This book effectively breaks with that way of thinking, and I would encourage developers, architects, database administrators etc. to read this book to get a sense of perspective. It would greatly help us in not making the mistake of tackling “new world” problems with “old world” solutions. The book is very easy to read, with good examples, funny stories, and insightful comments. There’s also a side step into neuro science and the future of supercomputing, which is not only good to know, but interesting in itself.

Book Review: Quiet: The Power of Introverts in a World That Can’t Stop Talking

Quiet: The Power of Introverts in a World That Can’t Stop Talking by Susan Cain is a very insightful book into introversion and extroversion. Because we deal with people at different positions on the introversion-extroversion spectrum every day, the book may open your eyes to how certain people react to you or to specific situations. IMHO this especially helps to understand children, because they are no yet adapt at hiding their true nature. So if you’re a mother, father, teacher, coach etc. this book can really help you. The book is very thorough, with a lot of personal insights backed up by scientific research. It is also pretty easy to read because it is told around experiences of the author. The book starts of with exploring extroversion and introversion and how these traits are perceived in western culture, and continues with the discussing the (dis)advantages of both traits. It the continues with giving you deeper understanding of where these traits come from and how they affect the way people think. Finally, the book gives pointer on how to deal with people at different ends of the spectrum.

Automatically generate Federation Metadata for your ASP.NET application

After having to generate Federation Metadata for the umpteenst time I decided it was time to deal with it once and for all. A tool like Thinktecture’s WS-Federation Generation Wizard is nice, but even that gets old after a while. Especially if you need to sign the metadata and the certificate is only on the hosting server. Fortunately, creating Federation Metadata for a passive endpoint is fairly easy, as the code below demonstrates. The code reads the current configuration from the system.identityModel section in web.config, so all you need to do is ensure it reflects your host configuration for a particular deployment (dev, test, acceptance, production). Of course you can manage that in Visual Studio with build management and config transforms.

private const string Saml10TokenTypeIdentifier = “urn:oasis:names:tc:SAML:1.0:assertion”;
private const string WsFederation12ProtocolIdentifier = “http://docs.oasis-open.org/wsfed/federation/200706″;

public string GenerateMetadata()
{
    return CreateMetadataString(CreateEntityDescriptor());
}

private EntityDescriptor CreateEntityDescriptor()
{
    var entityDescriptor = new EntityDescriptor();
    var applicationServiceDescriptor = new ApplicationServiceDescriptor();
    var config = FederatedAuthentication.FederationConfiguration;
    entityDescriptor.EntityId = new EntityId(config.WsFederationConfiguration.Realm);
    if (config.ServiceCertificate != null)
    {
        entityDescriptor.SigningCredentials = new X509SigningCredentials(config.ServiceCertificate);
        applicationServiceDescriptor.Keys.Add(GetSingingKey(config.ServiceCertificate));
    }
    applicationServiceDescriptor.ProtocolsSupported.Add(new Uri(WsFederation12ProtocolIdentifier));
    applicationServiceDescriptor.PassiveRequestorEndpoints.Add(new EndpointReference(config.WsFederationConfiguration.Realm));
    applicationServiceDescriptor.TargetScopes.Add(new EndpointReference(config.WsFederationConfiguration.Realm));
    entityDescriptor.RoleDescriptors.Add(applicationServiceDescriptor);
    return entityDescriptor;
}

private static string CreateMetadataString(EntityDescriptor entityDescriptor)
{
    var serializer = new MetadataSerializer();
    var stream = new MemoryStream();
    serializer.WriteMetadata(stream, entityDescriptor);
    stream.Seek(0L, SeekOrigin.Begin);
    return Encoding.UTF8.GetString(stream.ToArray());
}

private KeyDescriptor GetSingingKey(X509Certificate2 certificate)
{
    var x509Token = new X509SecurityToken(certificate);
    var x509RawDataKeyIdentifierClause = x509Token.CreateKeyIdentifierClause();
    var securityKeyIdentifierClause = new SecurityKeyIdentifierClause[]
                                            {
                                                x509RawDataKeyIdentifierClause
                                            };
    return new KeyDescriptor(new SecurityKeyIdentifier(securityKeyIdentifierClause))
    {
        Use = KeyType.Signing
    };
}

Book Review: The Modern Web

After reading The Modern Web: Multi-Device Web Development with HTML5, CSS3, and JavaScript (Peter Gasston, No Starch Press) I am glad I am not a user interface developer. Over the years HTML has evolved into an entirely different beast from 5-10 years ago. That said, the book is excellent at explaining all the options you have in HTML5, CSS, and Javascript to create good looking, responsive, and adative web applications. Peter Gasston managed to make the book easy to read through the writing style and simple examples that effectively demonstrate what a feature is about and how it works. Despite the simplicity, the samples are very detailed.


Besides meticulous explanation of what a feature does and how it works, Peter Gasston also discusses the material at a higher level, giving you insight into why and when you would want to use certain features, and when there are multiple options which one to go for in your particular situation.


One thing I particularly like is the appendix at the end of every chapter pointing you to more reading material related to the chapter’s content. The book in itself is already very useful as a reference, but this makes it even more useful. Even though it works very well as a reference, I recommend reading it from cover-to-cover to get a good understanding of the possibilties. You can do that at high speed, and then later use parts as needed.

Fix: ClaimsAuthorizationManager.CheckAccess throws HttpException

While preparing a demo about Claims Based Authorization in .NET 4.5, I ran into an exception that initially had me dumbstruck. I created an ASP.NET MVC 4 application from the Internet template. Then I used the Identity and Access Tools for Visual Studio (downloadable from http://bit.ly/IDATVS2012) so users login through an external Identity Provider (for the demo LocalSTS). So far so good. Next I created a custom ClaimsAuthorizationManager class with a custom CheckAccess method to demonstrate how you can invoke this from code, essentially separating security checks from business logic. After hooking it up in web.config I run the code and after a wait I got an HttpException with the message Unable to connect to SQL Server database on a call to Principal.IsInRole, as you can see in the image below.

This had me puzzled to say the least. Why would a simple role check go to a database, especially because these are already in the Claims collection? First I tried commenting it out and just do a direct claim check… no dice. Why? The claims collection is empty. Huh? I have a page that lists the claims and they look fine. A closer look at the principal in the AuthorizationContext revealed it was actually of type System.Web.Security.RolePrincipal. That still inherits from ClaimsPrincipal, but it isn’t a normal ClaimsPrincipal, explaining the behavior. But now the big question: where did it come from? This took me a while to figure out with the help of a forum post (this one), ILSpy, and this blogpost by Phil Haack. As it turns out, the ASP.NET MVC 4 Internet template includes the WebMatrix.WebData DLL. This DLL, among other things contains classes used with the SimpleMembership API introduced by WebMatrix. SimpleMembership, which uses a database, is automatically enabled because the DLL uses PreApplicationStart method to initialize itself (as explained in Phil Haack’s blogpost). As soon as you place the WebMatrix.WebData DLL in your bin folder, it automatically registers itself. The result is that Thread.CurrentPrincipal yields a System.Web.Security.RolePrincipal instead of the ClaimsPrincipal associated with the user.

You could obviously remove the WebMatrix.WebData DLL, but there might be other functionality in there you want to use. A better option is to add the following key in web.config appSettings:

<addkey="enableSimpleMembership"value="false" />

ASP.NET OpenID/OAuth Login With ASP.NET 4.5 – Part 5

With ASP.NET 4.5 it is very easy to enable users to login to your site with their accounts from Facebook, Google, LinkedIn, Twitter, Yahoo, and Windows Live. In this 7 part series I’ll show you how for each of the identity providers.

Note: Out-of-the-box this only works with WebForms and MVC4. MVC3 is not supported by default.

Part 5: Logging in with Twitter

As is the case with Facebook and LinkedIn discussed in previous posts, you need to register with Twitter. This means you have to get a Twitter account. With that account you have to register your application.

  1. Go to https://dev.twitter.com/apps and login with your Twitter account.
  2. Click the Create new application button.
  3. Fill out the form below. To avoid problems later, it makes sense to provide a Callback URL, even though it is not required.

  4. Accept the terms of use (Developer Rules of the Road), enter the Captcha and click the Create your Twitter application button. This will show the Details page shown below.

  5. In the page above notice that Sign in with Twitter has the value No. If you would now try to login users into your application, your server would get a 401 Unauthorized exception. To change this, go to the Settings tab and scroll down to the Application Type section. There you can check the highlighted checkbox in the image below.

  6. Click the Update this Twitter application’s settings button.
  7. Open Visual Studio (if you don’t have already).
  8. Open the project created in Part 1 (or quickly create a project in the same manner).
  9. Find the App_Start folder and open AuthConfig.cs.
  10. Register the identity provider:
    1. In MVC go to the RegisterAuth method and uncomment the following line of code:
      OAuthWebSecurity.RegisterTwitterClient( consumerKey: "", consumerSecret: "");
    2. In WebForms go to the RegisterOpenAuth method and uncomment the following line of code:
      OpenAuth.AuthenticationClients.AddTwitter(
          consumerKey: "your Twitter consumer key",
          consumerSecret: "your Twitter consumer secret");
  11. Replace the place holder text with the Consumer key and Consumer secret shown on the Details page of your application in Twitter (see image under step 4).
  12. Save the file.
  13. Run the project.
  14. Click the Log in link. You will notice Twitter has automatically been added next to the other providers you added under Use another service to log in.
  15. Clicking the Twitter button will send you to Twitter to log in.
  16. Login with a Twitter account on the page shown below. Notice that it is telling the user which application wants you to log in with your Twitter account, and what the application can do once you logged in. Twitter recognizes the application from the Consumer key, and provides the user with the information you entered earlier.

  17. When you sign in you are automatically redirected to the application.