Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Windows Azure, PHP, ...

About the author

Maarten Balliauw is currently employed as .NET Technical Consultant at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP and the Windows Azure cloud platform.
More about me More about me
Send mail E-mail me


ASP.NET MVC Quickly Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn
View Maarten Balliauw's MVP profile

Search

Latest Twitter

    Follow me on Twitter...

    Archive

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2012


    Authenticate Orchard users with AppFabric Access Control Service

    From the initial release of Orchard, the new .NET CMS, I have been wondering how difficult (or easy) it would be to integrate external (“federated”) authentication like Windows Azure AppFabric Access Control Service with it. After a few attempts, I managed to wrap-up a module for Orchard which does that: Authentication.Federated.

    After installing, configuring and enabling this module, Orchard’s logon page is replaced with any SAML 2.0 STS that you configure. To give you a quick idea of what this looks like, here are a few screenshots:

    Orchard Log On link is being overriddenOrchard authentication via AppFabricOrchard authenticated via SAML - Username is from the username claim

    As you can see from the sequence above, Authentication.Federated does the following:

    • Override the default logon link
    • Redirect to the configured STS issuer URL
    • Use claims like username or nameidentifier to register the external user with Orchard. Optionally, it is also possible to configure roles through claims.

    Just as a reference, I’ll show you how to configure the module.

    Configuring Authentication.Federated – Windows Azure AppFabric side

    In my tests, I’ve been using the AppFabric LABS release, over at https://portal.appfabriclabs.com. From there, create a new namespace and configure Access Control Service with the following settings:

    Identity Providers

    • Pick the ones you want… I chose Windows Live ID and Google

    Relying Party Applications

    Add your application here, using the following settings:

    • Name: pick one :-)
    • Realm: The http(s) root URL for your site. When using a local Orchard CMS installation on localhost, enter a non-localhost URL here, e.g. https://www.examle.org
    • Return URL: The root URL of your site. I chose http://localhost:12758/ here to test my local Orchard CMS installation
    • Error URL: anything you want
    • Token format: SAML 2.0
    • Token encryption: none
    • Token lifetime: anything you want
    • Identity providers: the ones you want
    • Rule groups: Create new rule group
    • Token signing certificate: create a Service Namespace token and upload a certificate for it. This can be self-signed. Ensure you know the certificate thumbprint as we will need this later on.

    Edit Rule Group

    Edit the newly created rule group. Click “generate” to generate some default rules for the identity providers chosen, so that nameidentifier and email claims are passed to Orchard CMS. Also, if you want to be the site administrator later on, ensure you issue a roles claim for your Google/Windows Live ID, like so:

    Add a role claim for your administrator

    Configuring Authentication.Federated – Orchard side

    In Orchard, download Authentication.Federated from the modules gallery and enable it. After that, you’ll find the configuration settings under the general “Settings” menu item in the Orchard dashboard:

    Authentication.Federated configuration

    These settings speak for themselves mostly, but I want to give you some pointers:

    • Enable federated authentication? – Enables the module. Ensure you’ve first tested the configuration before enabling it. If you don’t, you may lose access to your Orchard installation unless you do some database fiddling…
    • Translate claims to Orchard user properties? – Will use claims values to enrich user data.
    • Translate claims to Orchard roles? – Will assign Orchard roles based on the Roles claim
    • Prefix for federated usernames (e.g. "federated_") – Just a prefix for federated users.
    • STS issuer URL – The STS issuer URL, most likely the root for your STS, e.g. .accesscontrol.appfabriclabs.com">https://<account>.accesscontrol.appfabriclabs.com
    • STS login page URL – The STS’ login page, e.g. .accesscontrol.appfabriclabs.com:443/v2/wsfederation">https://<account>.accesscontrol.appfabriclabs.com:443/v2/wsfederation
    • Realm – The realm configured in the Windows Azure AppFabric Access Control Service settings
    • Return URL base – The root URL for your website
    • Audience URL – Best to set this identical to the realm URL
    • X509 certificate thumbprint (used for issuer URL token signing) – The token signing certificate thumbprint

    Categories: ASP.NET | C# | General | ICT | MVC | Orchard | Projects | Security

    BlogEngine.NET comment spam filtering

    SpamIt’s been a month or three since I was utterly fed up with comment spam on my blog. Sure, I did turn on comment moderation so you, as a visitor, would not notice this spam if I did not approve it as a valid comment. However, I found myself cleaning up comment spam from in between legitimate comments in the BlogEngine.NET admin interface.

    In an effort of trying to reduce comment spam, I tried the following:

    • Close comments after 90 days – This effort worked for a few days, but afterwards I was just seeing more comment spam on the topics that were still open to comments.
    • Use a CAPTCHA – This effort reduced some comment spam, but not all. Which makes me believe there are people actually making a living by just sending out comment spam and filling out CAPTCHA’s out there.
    • Whining and cursing while again cleaning out comments manually – This effort worked, until I found out that this was what I’ve been doing before the other 2 efforts. Back to start…

    Luckily, the latest version of BlogEngine.NET (and also earlier version if you go down the hacky road) featured a new comment system, including spam filtering. After using it for a few months, I must say I’m very close to zero comment spam!

    The results

    I have configured BlogEngine.NET as follows:

    • Comments enabled, never closed
    • Comment moderation: “on” and “automatic”
    • Whitelisting rules enabled (if you have 5 legitimate comments, you are probably OK)
    • Spam filters enabled: AkismetFilter, StopForumSpam and TypePadFilter

    Now if you look at the results, there’s an interesting difference between the spam filter services being used:

    image

    The accuracy of the spam filters is mostly > 90%, for Akismet it’s even 97.30 %. Which I also feel: a small check every week on whether there are spam filter mistakes is quite enough. Only the TypePadFilter is letting me down there, and I will probably disable this one and rely on only two filters.


    Simplified access control using Windows Azure AppFabric Labs

    Windows Azure ApFabric Access ControlEarlier this week, Zane Adam announced the availability of the New AppFabric Access Control service in LABS. The highlights for this release (and I quote):

    • Expanded Identity provider support - allowing developers to build applications and services that accept both enterprise identities (through integration with Active Directory Federation Services 2.0), and a broad range of web identities (through support of Windows Live ID, Open ID, Google, Yahoo, Facebook identities) using a single code base.
    • WS-Trust and WS-Federation protocol support – Interoperable WS-* support is important to many of our enterprise customers.
    • Full integration with Windows Identity Foundation (WIF) - developers can apply the familiar WIF identity programming model and tooling for cloud applications and services.
    • A new management web portal -  gives simple, complete control over all Access Control settings.

    Wow! This just *has* to be good! Let’s see how easy it is to work with claims based authentication and the AppFabric Labs Access Control Service, which I’ll abbreviate to “ACS” throughout this post.

    kick it on DotNetKicks.com

    What are you doing?

    In essence, I’ll be “outsourcing” the access control part of my application to the ACS. When a user comes to the application, he will be asked to present certain “claims”, for example a claim that tells what the user’s role is. Of course, the application will only trust claims that have been signed by a trusted party, which in this case will be the ACS.

    Fun thing is: my application only has to know about the ACS. As an administrator, I can then tell the ACS to trust claims provided by Windows Live ID or Google Accounts, which will be reflected to my application automatically: users will be able to authenticate through any service I configure in the ACS, without my application having to know. Very flexible, as I can tell the ACS to trust for example my company’s Active Directory and perhaps also the Active Directory of a customer who uses the application

    Prerequisites

    Before you start, make sure you have the latest version of Windows Identity Foundation installed. This will make things easy, I promise! Other prerequisites, of course, are Visual Studio and an account on https://portal.appfabriclabs.com. Note that, since it’s still a “preview” version, this is free to use.

    In the labs account, create a project and in that project create a service namespace. This is what you should be seeing (or at least: something similar):

    AppFabric labs project

    Getting started: setting up the application side

    Before starting, we will require a certificate for signing tokens and things like that. Let’s just start with creating one so we don’t have to worry about that further down the road. Issue the following command in a Visual Studio command prompt:

    MakeCert.exe -r -pe -n "CN=<your service namespace>.accesscontrol.appfabriclabs.com" -sky exchange -ss my

    This will create a certificate that is valid for your ACS project. It will be installed in the local certificate store on your computer. Make sure to export both the public and private key (.cer and .pkx).

    That being said and done: let’s add claims-based authentication to a new ASP.NET Website. Simply fire up Visual Studio, create a new ASP.NET application. I called it “MyExternalApp” but in fact the name is all up to you. Next, edit the Default.aspx page and paste in the following code:

    1 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 2 CodeBehind="Default.aspx.cs" Inherits="MyExternalApp._Default" %> 3 4 <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 5 </asp:Content> 6 <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 7 <p>Your claims:</p> 8 <asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"> 9 <Columns> 10 <asp:BoundField DataField="ClaimType" HeaderText="ClaimType" ReadOnly="True" /> 11 <asp:BoundField DataField="Value" HeaderText="Value" ReadOnly="True" /> 12 </Columns> 13 </asp:GridView> 14 </asp:Content>

    Next, edit Default.aspx.cs and add the following Page_Load event handler:

    1 protected void Page_Load(object sender, EventArgs e) 2 { 3 IClaimsIdentity claimsIdentity = 4 ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities.FirstOrDefault(); 5 6 if (claimsIdentity != null) 7 { 8 gridView.DataSource = claimsIdentity.Claims; 9 gridView.DataBind(); 10 } 11 }

    So far, so good. If we had everything configured, Default.aspx would simply show us the claims we received from ACS once we have everything running. Now in order to configure the application to use the ACS, there’s two steps left to do:

    • Add a reference to Microsoft.IdentityModel (located somewhere at C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll)
    • Add an STS reference…

    That first step should be easy: add a reference to Microsoft.IdentityModel in your ASP.NET application. The second step is almost equally easy: right-click the project and select “Add STS reference…”, like so:

    Add STS reference

    A wizard will pop-up. Here’s a secret: this wizard will do a lot for us! On the first screen, enter the full URL to your application. I have mine hosted on IIS and enabled SSL, hence the following screenshot:

    Specify application URI

    In the next step, enter the URL to the STS federation metadata. To the what where? Well, to the metadata provided by ACS. This metadata contains the types of claims offered, the certificates used for signing, … The URL to enter will be something like https://<your service namespace>.accesscontrol.appfabriclabs.com:443/FederationMetadata/2007-06/FederationMetadata.xml:

    Security Token Service

    In the next step, select “Disable security chain validation”. Because we are using self-signed certificates, selecting the second option would lead us to doom because all infrastructure would require a certificate provided by a valid certificate authority.

    From now on, it’s just “Next”, “Next”, “Finish”. If you now have a look at your Web.config file, you’ll see that the wizard has configured the application to use ACS as the federation authentication provider. Furthermore, a new folder called “FederationMetadata” has been created, which contains an XML file that specifies which claims this application requires. Oh, and some other details on the application, but nothing to worry about at this point.

    Our application has now been configured: off to the ACS side!

    Getting started: setting up the ACS side

    First of all, we need to register our application with the Windows Azure AppFabric ACS. his can be done by clicking “Manage” on the management portal over at https://portal.appfabriclabs.com. Next, click “Relying Party Applications” and “Add Relying Party Application”. The following screen will be presented:

    Add Relying Party Application

    Fill out the form as follows:

    • Name: a descriptive name for your application.
    • Realm: the URI that the issued token will be valid for. This can be a complete domain (i.e. www.example.com) or the full path to your application. For now, enter the full URL to your application, which will be something like https://localhost/MyApp.
    • Return URL: where to return after successful sign-in
    • Token format: we’ll be using the defaults in WIF, so go for SAML 2.0.
    • For the token encryption certificate, select X.509 certificate and upload the certificate file (.cer) we’ve been using before
    • Rule groups: pick one, best is to create a new one specific to the application we are registering

    Afterwards click “Save”. Your application is now registered with ACS.

    The next step is to select the Identity Providers we want to use. I selected Windows Live ID and Google Accounts as shown in the next screenshot:

    Identity Providers

    One thing left: since we are using Windows Identity Foundation, we have to upload a token signing certificate to the portal. Export the private key of the previously created certificate and upload that to the “Certificates and Keys” part of the management portal. Make sure to specify that the certificate is to be used for token signing.

    Signing certificate Windows Identity Foundation WIF

    Allright, we’re almost done. Well, in fact: we are done! An optional next step would be to edit the rule group we’ve created before. This rule group will describe the claims that will be presented to the application asking for the user’s claims. Which is very powerful, because it also supports so-called claim transformations: if an identity provider provides ACS with a claim that says “the user is part of a group named Administrators”, the rules can then transform the claim into a new claim stating “the user has administrative rights”.

    Testing our setup

    With all this information and configuration in place, press F5 inside Visual Studio and behold… Your application now redirects to the STS in the form of ACS’ login page.

    Sign in using AppFabric

    So far so good. Now sign in using one of the identity providers listed. After a successful sign-in, you will be redirected back to ACS, which will in turn redirect you back to your application. And then: misery :-)

    Request validation

    ASP.NET request validation kicked in since it detected unusual headers. Let’s fix that. Two possible approaches:

    • Disable request validation, but I’d prefer not to do that
    • Create a custom RequestValidator

    Let’s go with the latter option… Here’s a class that you can copy-paste in your application:

    1 public class WifRequestValidator : RequestValidator 2 { 3 protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) 4 { 5 validationFailureIndex = 0; 6 7 if (requestValidationSource == RequestValidationSource.Form && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal)) 8 { 9 SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(context.Request) as SignInResponseMessage; 10 11 if (message != null) 12 { 13 return true; 14 } 15 } 16 17 return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex); 18 } 19 }

    Basically, it’s just validating the request and returning true to ASP.NET request validation if a SignInMesage is in the request. One thing left to do: register this provider with ASP.NET. Add the following line of code in the <system.web> section of Web.config:

    <httpRuntime requestValidationType="MyExternalApp.Modules.WifRequestValidator" />

    If you now try loading the application again, chances are you will actually see claims provided by ACS:

    Claims output from Windows Azure AppFabric Access Control Service

    There', that’s it. We now have successfully delegated access control to ACS. Obviously the next step would be to specify which claims are required for specific actions in your application, provide the necessary claims transformations in ACS, … All of that can easily be found on Google Bing.

    Conclusion

    To be honest: I’ve always found claims-based authentication and Windows Azure AppFabric Access Control a good match in theory, but an ugly and cumbersome beast to work with. With this labs release, things get interesting and almost self-explaining, allowing for easier implementation of it in your own application. As an extra bonus to this blog post, I also decided to link my ADFS server to ACS: it took me literally 5 minutes to do so and works like a charm!

    Final conclusion: AppFabric team, please ship this soon :-) I really like the way this labs release works and I think many users who find the step up to using ACS today may as well take the step if they can use ACS in the easy manner the labs release provides.

    By the way: more information can be found on http://acs.codeplex.com.

    kick it on DotNetKicks.com


    Categories: Azure | C# | General | Security

    ASP.NET MVC - Upcoming preview 4 release

    ScottGu just posted that there's an upcoming preview 4 release of the ASP.NET MVC framework. What I immediately noticed, is that there are actually some community concepts being integrated in the framework, yay! And what's even cooler: 2 of these new features are things that I've already contributed to the community (the fact that it these are included in the MVC framework now could be coincidence, though...).

    Thank you, ASP.NET MVC team! This preview 4 release seems like a great step in the evolution of the ASP.NET MVC framework. Thumbs up!

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | General | MVC | Projects | Security

    To all BlogEngine.NET users... Go patch!

    image This morning, I read about a serious security issue in BlogEngine.NET. The security issue is in the JavaScript HTTP handler, which lets all files pass trough... In short: if you open http://your.blog.com/js.axd?path=app_data\users,xml, anyone can see your usernames/passwords! None of the other HttpHandlers are affected by this security hole.

    My recommendation: if you are using BlogEngine.NET: go patch!

    (and yes, I patched it Cool  http://blog.maartenballiauw.be/js.axd?path=app_data\users.xml)

    kick it on DotNetKicks.com


    Categories: General | Software | Security