May 2012

Volume 27 Number 05

Leading LightSwitch - Logging in to a LightSwitch Application Using Social Media Credentials

By Jan Van der Haegen | May 2012

More and more Web sites are outsourcing the process of authenticating a user to a third-party Web site such as Windows Live ID, Yahoo!, Google or Facebook. These social media sites fulfill the role of an identity provider and grant the requestor with a signed token, a key that proves the user is who he says he is. 

LightSwitch shipped with three possible authentication modes: None, Windows credentials and Forms authentication. With LightSwitch, choosing an authentication mode is as easy as selecting one from the application’s properties. LightSwitch then sets up the database and guides the user through the selected login process without any additional effort from the developer. The authentication is fast and convenient—but in no supported or obvious way open for extensibility.

Not supported and not obvious don’t always mean impossible, however. A developer with a bit of knowledge about LightSwitch internals can find ways to bypass the built-in LightSwitch authentication. In this article, I'll show you how I have made it possible for users of my LightSwitch applications to log in using their social media credentials of choice.

Before talking specifically about LightSwitch, I want to provide a brief recap on—or an introduction to, if you’re new to the topic—Security Token Services. 

Understanding Security Token Services

Not too long ago, each application, Web site or Web service was a silo that had its own way to authenticate and authorize users. A couple years back, I had about a dozen username–password combinations for different sites, and more often than not I clicked the “Forgot password?” link more than any other. This problem inconvenienced site maintainers as well as regular users. Even if company A forged an alliance with company B so that the 100,000 users from company B had access to company A’s software, those users had to be duplicated and maintained across the two sites.

The answer to this duplication problem was as simple as taking the elements that authenticate and authorize users out of the application, Web site or Web service and putting them in a separate service called a Security Token Service (STS). Figure 1 shows how a classic, simple STS system works.

A simple STS scenario
Figure 1 A simple STS scenario

Instead of maintaining a custom login mechanism itself, the service the user interacts with trusts the STS to do the authentication and authorization, and focuses solely on the business logic. The flow now goes like this:

  1. The user’s browser or application requests a security token from the STS by passing a valid username–password combination.  
  2. The STS validates the username and password.
  3. The STS sends back a security token, which is a key with the following characteristics:
    • Is signed, to prove that it comes from the STS.
    • Proves that the user is authenticated—that is, who she claims to be.
    • Contains authorization claims, which can be considered simple strings that represent the user’s permissions and properties—that is, what the user is allowed to do or is denied from doing.
  4. The user uses this security token as a key to unlock the service.
  5. The service verifies that the security token is genuine by checking the certificate used to sign the token.
  6. The service serves the client’s request.

Separating the authentication and authorization process from the Web site, Web service or application by setting up STS offers some benefits because of the configurability of this setup:

  • Multiple applications owned by company A can now trust the same STS, meaning that multiple applications can use one login service.
  • One STS can authenticate users in multiple ways: by username–password combination, by Windows credentials or even by trusting tokens signed by a third party.
  • Using third-party tokens helps solve the duplication problem between two companies (A and B) in an alliance, as illustrated in Figure 2. This third-party STS then becomes an identity provider to the original STS. For example, the STS from company A can now trust tokens from the STS from company B. An employee from company B can then authenticate with STS B, using the Windows credentials stored in company B’s Active Directory. The user’s browser or application uses security token B to authenticate to STS A. STS A recognizes that STS B has signed the token and trusts STS B to know that the token genuinely means that the user is who he says he is. Using simple mapping, claims from domain B are mapped to claims from domain A. For example, if the token has the claim B\helpdesk, STS A issues a security token with claim A\admin. The user, an employee from company B, can now use that token to access company A’s software. Observe that company A’s software didn’t have to be modified for this use; the company A STS has to trust only the company B STS, which is a matter of configuration.

A more advanced STS scenario
Figure 2 A more advanced STS scenario

Switching from in-application authentication to STS architecture might seem like a lot of work, but the benefits definitely outweigh the effort, which is why most large companies, including Microsoft (Windows Live ID STS), Facebook, Google and Yahoo!, currently use this architecture.

Azure Access Control Service

If you’re interested, you can find some excellent documentation about STS on the Microsoft Patterns & Practices site ( However, I suggest you resist the urge to use the Patterns & Practices framework to code a custom STS yourself and instead use the Azure Access Control Service (ACS). Azure ACS is an inexpensive, easy-to-configure security token service hosted in the cloud. It has built-in support to trust other STSs as an identity provider, including those from Windows Live ID, Facebook, Google and Yahoo!.

If you have an Azure account and download the Windows Identity Foundation SDK (, in the first lab (Exercise 1, at you’ll find out how to create an ASP.NET Web site where users can authenticate with their Windows Live ID, Google or Yahoo! account in 30 minutes or less, as shown in Figure 3.

Logging in to an ASP.NET application using social media credentials
Figure 3 Logging in to an ASP.NET application using social media credentials

The resulting ASP.NET “Hello social world” application, shown in Figure 4, is the first corner piece of the puzzle of how we can enable authentication using social media credentials for users of LightSwitch applications.

“Hello social world” ASP.NET application created in Windows Identity Foundation SDK lab
Figure 4 “Hello social world” ASP.NET application created in Windows Identity Foundation SDK lab

Extending the Azure ACS Sample

If you have an existing (or new) LightSwitch application with its authentication mode set to Forms and you followed the ACS lab, you can now combine the ASP.NET and LightSwitch applications. In the ASP.NET application you created, remove all visual controls and add an IFrame instead. Then replace the code behind with this code:

public partial class _Default : System.Web.UI.Page
    public static readonly string LightSwitchApplication = 
    protected void Page_Load(object sender, EventArgs e)
        MyFrame.Attributes["src"] = LightSwitchApplication 
            + "default.htm?UserName="
            + Thread.CurrentPrincipal.Identity.Name.Replace(" ", "");

The result is an ASP.NET application that hosts the LightSwitch application, which in turn shows the LightSwitch login screen, as you can see in Figure 5

A simple, clean and totally undesirable LightSwitch login screen
Figure 5 A simple, clean and totally undesirable LightSwitch login screen

You now have an ASP.NET page that requires the user to log in using her social media credentials and then takes the authenticated user’s name (from Thread.CurrentPrincipal) and passes it to the LightSwitch application via the URL. Once the LightSwitch application starts, the user is again presented with a login screen. Obviously, since the user already provided credentials, the next and most challenging step is to rip out the LightSwitch login screen and replace it with an automated process.

The LightSwitch View

In my April Leading LightSwitch article (, I explained the LightSwitch MVVM architecture, concluding that the View doesn’t have any XAML. (This notion that there’s no XAML in a LightSwitch application comes from John Rivard and Karol Zadora-Przylecki, from their blog post series about the LightSwitch architecture: Obviously, it isn’t quite true that no XAML is used in the LightSwitch View, but it is true that there is no XAML you need to worry about—unless you want to customize your application.  

If you’re a professional developer or you just want to do some graphical modifications to your LightSwitch application, chances are you’ll need a good understanding of and access to the View layer. Let’s start with a brief summary of how this View layer is composed to see where and how the login screen is displayed. With this knowledge, we can try to replace the login screen with a component that takes the social media credentials, passed via the URL, into account.

In-browser LightSwitch application
Figure 6 In-browser LightSwitch application

A standard LightSwitch application, like the example in Figure 6, has various components that form the View layer:

  1. ASP.NET page that hosts the Silverlight application  If you select your LightSwitch application in Solution Explorer and then select Logical View, you can find this page, default.htm, in the ServerGenerated project (Visual Studio 2010) or at the root of your LightSwitch project (Visual Studio 11 beta). Being able to find this page in Solution Explorer implies that the developer can modify it.
  2. LightSwitch “application bootstrapper” A Silverlight application that loads the metadata handles the login if necessary (depending on the chosen login mode) and navigates to the Shell page. The implementations are found mainly in the assemblies Microsoft.LightSwitch.dll, Microsoft.LightSwitch.Client.dll and Microsoft.LightSwitch.Client.Internal.dll. (Read more about metadata in MVVM architecture in my April Leading LightSwitch article, at
  3. Shell page This Silverlight page gives a visual representation to the commands (visible at the top in the default LightSwitch 1.0 shell) and the navigation menu (visible at the left), and it has a placeholder for the screens. The implementations for the default shell are in the same assemblies mentioned in the preceding entry, although you can use custom shells instead if you like.
  4. Screens The screens are made up of Silverlight controls that are laid out as defined in the metadata (explained in my April Leading LightSwitch article). The ControlTemplates, or the XAML that defines how the controls should look, are defined by the theme. The implementations for the default theme are in the same assemblies mentioned earlier, although you can use custom controls and custom themes if you prefer.

Contrary to what most professional developers believe, a LightSwitch application is not a generated and closed box. Yes, a LightSwitch application is partly generated, but it’s definitely not a closed box. The ASP.NET page can be modified to fit your needs (see entry 1 in the preceding list) and to use Shell extensions (entry 3), theme extensions (entries 3 and 4), Control extensions (entry 4) or Silverlight Custom controls (entry 4). A developer can take fine-grained control over any visual part of a LightSwitch application—any visual part, that is, except for the application bootstrapper (entry 2), which contains the login page we want to replace. 

When the LightSwitch application bootstrapper navigates to the login page, Silverlight fires an event. By adding an event handler to this event, you can bypass the entire LightSwitch login logic. It isn’t possible to prevent the login logic from happening, so you’re not replacing the login page—rather, you’re acting on the event that the LightSwitch bootstrapper is trying to navigate to the login page to take control of the application flow.

The code in Figure 7 should be placed in the Application_Initialize extension point (“write code”). It’s the only LightSwitch extension point that occurs before the login page is shown.

using System; 
using System.Linq; 
using System.IO; 
using System.IO.IsolatedStorage; 
using System.Collections.Generic; 
using Microsoft.LightSwitch; 
using Microsoft.LightSwitch.Framework.Client; 
using Microsoft.LightSwitch.Presentation; 
using Microsoft.LightSwitch.Presentation.Extensions; 
using System.Windows.Controls; 
using Microsoft.LightSwitch.Runtime.Shell.Internal.Implementation; 
using Microsoft.LightSwitch.ApplicationInfrastructure.Utilities.Internal; 
using Microsoft.LightSwitch.Runtime.Shell.ViewModels.Login; 
using Microsoft.VisualStudio.ExtensibilityHosting; 
namespace LightSwitchApplication 
    public partial class Application 
        Frame rootFrame = null; 
        partial void Application_Initialize(){ 
        Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() => { 
                rootFrame = 
                              .Content).Content as Frame; 
                if (rootFrame != null) 
                    rootFrame.Navigated += new 
        void rootFrame_Navigated(object sender, 
            System.Windows.Navigation.NavigationEventArgs e) 
            if (e.Content is LoginPage) { 
                rootFrame.Navigated -= rootFrame_Navigated;   
                string userName = null; 
                if (QueryStringHelper.TryGetValue("UserName", 
                    out userName)) 
                    ILoginViewModel vm = 
                    vm.UserName = userName; 
                    vm.Password = "RandomPassword"; 

Figure 7 Bypassing the LightSwitch login screen

In the Application_Initialize method, find the Silverlight root frame and add an event handler to its navigated event. Do this on the LightSwitch main dispatcher to avoid threading issues.

Once this event fires, check whether the page being navigated to is LoginPage. If it is, the best practice is to remove the event handler to avoid the small memory leak where the garbage collector won’t collect the event handler. Use the LightSwitch QueryStringHelper class to get the UserName that the ASP.NET page passed in the URL. If this information is available, utilize the LightSwitch ILoginViewModel implementation to handle the login by passing the UserName and a random password, and executing the LoginCommand on that ViewModel.

A Short Technical Recap

We have set up an ASP.NET Web application that delegates the login process to Azure ACS. Thanks to simple configuration, we can now delegate this application to the social media network we want to access. The ASP.NET application passes the credentials to the LightSwitch application that contains some custom code to use these credentials instead of the default login screen.

Words to the Wise

Although LightSwitch doesn’t have out-of-the-box support for this scenario, you can offer the user the ability to log on using his social media platform of choice by making a couple small hacks, as demonstrated in this article. If you’re going to try this, be sure to heed the words of caution in the following paragraphs.

Bypassing the LightSwitch LoginPage isn’t officially supported and uses LightSwitch internal implementations. Because of this, the code is highly dependent on parts of the LightSwitch framework that aren’t included in the public API and thus could change if in a future release the LightSwitch team sees any need for it. Strictly speaking, using the internals could even be considered a violation of the EULA. Actually, you shouldn’t even be reading this article; your browser will self-destruct in five seconds.

This article is not a step-by-step guide but rather tries to lay out the crucial pieces of the puzzle of how to create a LightSwitch application that provides users with a familiar, consistent login screen whether they are at work, at home or using social media. Your next step should be to think about the security of your implementation. For example, you can encrypt the UserName instead of sending it in the URL as plain string, preferably including some notion of the time so that the URL can’t be hijacked and reused by others. Consider using a hash of the original username instead of a hardcoded RandomPassword.

If you use LightSwitch 2.0 (in Visual Studio 11 beta), you’re exposing your domain data as OData endpoints, which could be consumed in different clients than the Silverlight client, such as a Windows Phone application. (See my March article on how to consume a LightSwitch OData service from a Windows Phone application: These services are not secured by the Azure ACS but instead are secured by the LightSwitch authentication you choose (None, Windows credentials or Forms).

If you investigate the mapping of the social media security token to the Azure ACS security token, you’ll notice that the Windows Live ID security token doesn’t contain a claim for “name.” Depending on the identity providers (social media platforms) you choose, you’ll want to find a specific claim that fits your needs. Figure 8 shows that the “nameidentifier” claim would make a valid candidate if you opt to use Google, Yahoo! and Windows Live ID as your identity providers.

The ACS rule map
Figure 8 The ACS rule map

If you read and understand the preceding cautions, welcome to the wonderful world where STS, claim-based security and LightSwitch are blended together. Recent studies show that employees are up to five times more careful about giving out their social media credentials than they are about sharing the username and password they use at work. Besides that, it’s simply more convenient for users to remember only a few username–password combinations and use them to log in to a variety of applications. I have used this single-sign-on technique since LightSwitch 1.0, including in MyBizz Portal, an award-winning LightSwitch network ( I have received some great feedback from users since I made it possible for them to use their social media credentials to log in to their business applications.

Jan Van der Haegen* *is a green geek who turns coffee into software. He’s a loving husband, he’s proud to be part of an international team at Centric Belgium, and so addicted to learning about any .NET technology—Visual Studio LightSwitch in particular—that he maintains a blog on his coding experiments.

Thanks to the following technical expert for reviewing this article:Paul Patterson.