In the previous write-up on LightSwitch, we discussed about how to build screens and navigations and build an application. Taking a step forward, using LightSwitch I want to build a web application which supports features like Authentication and Authorization out of box. What is the catch?! Yes, the catch is, still, ZERO CODE written! J.
A quick recap on creating a Web application using LightSwitch, your mandatory pre-requisite is Visual Studio LightSwitch 2011. First step, obviously, to create a new LightSwitch Application (C#) project.
From Now on to the basic entity model, I’m going to skip, (refer to my previous write-up for details). For the sake of simplicity, we’ll use the good old PUBS sample database for the demo purpose. We’ll play around entities like Authors & Titles.
Using Add screen wizards, let us add a new List Detail screen for entities, Authors & Titles. During the addition, let us also enable the dependency relationship details for AuthorsTitles & TitleAuthors to be included in the screen.
After necessary Screen designs, Get down to the properties page of LightSwitch Project to define key properties for Access Control, Application type Publish the application into a host environment.
The Publishing Wizard of LightSwitch can help in hosting the web application in a Windows Azure (Cloud) or host the application services on a separate IIS Server. For the sake of this demo, let us focus on hosting the app in IIS. Select the option for client & Application Server as in the setting below:
Before we hit on Publish button, we’ve one more step to complete, to set the access control. In the properties page, click on Access Control to set the type of Authentication
By default, the Authentication type is not enabled. The web application can either select Windows Authentication or use Forms based authentication. Let us select Forms authentication for this example and Windows Authentication works the same way, as usual.
LightSwitch has a built-in permission called Security Administration, and any user who receives this permission becomes a security administrator. The Security Administration permission allows the logged-on user to access the Security Administration screens in the running LightSwitch client application, which will show automatically for users who have been granted this privilege. If you are curious to know if LightSwitch do provide us with any default screen to manage User & Roles, please click on Screen Navigation to find a separate Menu group, ‘Administration’ with tasks Roles & User under them. This group of screens is visible only for those roles with ‘SecurityAdministration’ permission. When a user logs in with Security Administration privilege, the client application screen will have additional task menu on the left side.
We are almost done with other settings in the property page, we could go back to Application type property page and select the publish Wizard for finishing details on security settings. Publish step will build the LightSwitch application, bundle them with all required resources and then take us through a set of wizard screens to define properties to host the output files into the target environment.
Publish Wizard begins with Client configuration. We had earlier marked this as a Web Application and this choice is reflected in the Wizard.
Next step is to define the Application Server. Again, we opted to host this on an IIS Server; this option is reflected in the wizard. However, before we move on to next step, need to ensure that IIS server has LightSwitch pre-requisites installed on the application server. The LightSwitch server prerequisites are installed by using Web Platform Installer. You can download Web Platform Installer from the Microsoft Download Site. Once the pre-requisites on the IIS server are confirmed, the next step is to ‘Specify Publishing Reference’. The wizard can create an MSDeploy package or remotely deploy on IIS server directly
The next step is to define Database connection to the DB where Authentication information to be persisted. For this demo, I set it to a SQL DB where ASPNET user tables are created and stored.
During the Publishing wizard, in order for the LS app to work with access control, the wizard themselves provides an entry to create Application Administrator User at this time. And other users can be created through application User management screens.
Next step is to specify application Data Source connection strings in the ‘Other Connections’ page. The Wizard auto-populates the connection string based on the initial definition we provided during the Entity data source definition. Post this step, we have an optional step to specify Certificate for SSL (which are self-explanatory), final page in the wizard is the Publish Summary Page as below.
Once we click on the publish button, the MsDeploy package is remotely deployed into the IIS Server (Localhost in this case) under Default Web site\WebAppAuth Application. You’ll see the status update of ‘Published Successfully’ in the visual studio status bar, once it is published.
One point to note about authentication is, this works only on deployed environment and does not work during the Debug mode. So to test Authentication, you need to deploy them in the hosting environment.
Unlike the debug mode, when the application is launched from the hosted environment, the initial page is a Login Page. In the login page, use the ‘Admin’ user credential that was specified during the Publish Wizard. We could additionally see two more tasks on the left menu, viz., Roles, Users.
Till this point of time, we’ve not written a line of code, however, we’ve accomplished a Web application with a login page, Authentication and Authorization capability.
Securing Data on the Logic Tier
As we get to next stage, we might have functionality to enable or disable screens for certain role permissions alone.
The logic tier includes two major groups of components where you apply permissions checking: entities and queries.
Entities are the general mechanism for accessing and working with application data. There are four main actions you can carry out with entities: read, insert, update and delete. LightSwitch gives developers a hook-point to verify a user’s permissions as each action is carried out, and it also provides a simple API for checking if the current user has a specific permission defined in the application. The following code shows an example of the permissions check and the various gate methods the API provides to allow a developer to check permissions:
partial void Employee_CanUpdate
(ref bool result)
result = Application.Current.User.HasPermission
partial void Employee_CanInsert…
partial void Employee_CanRead…
partial void Employee_CanDelete…
partial void SaveChanges_CanExecute…
A couple of things should be noted. First, these methods, with the exception of SaveChanges_CanExecute, are implemented on the entity set as a whole and not on the specific entity instances. Therefore, any checks performed can’t be related to data values on a specific entity instance. The SaveChanges_CanExecute method controls access to changes in the entire data source and therefore can’t contain entity- or entity-set-specific logic. Second, if the Employee_CanRead method returns false, the Employee_CanUpdate and Employee_CanDelete methods will not be called, as they would be implicitly false as well. A user is not allowed to update or delete an entity if she isn’t allowed to read it.
The “Can” methods are the basic way to do coarse-grained security. They support basic data access-control policies. However, they have some limitations. When more fine-grained control for reading data is needed, you can implement access-control logic on queries. To control the writing of data at a more granular level, you must do so in the Save Pipeline.
Queries are also secured on the logic tier. Each query has a method that allows you to control access. LightSwitch automatically generates three queries for each entity that exists: an All query to return all of the entity instances, and Single and SingleOrDefault queries to return one entity instance by key. Each of these built-in queries has a CanExecute method that can be used to implement access control:
partial void Employees_All_CanExecute(ref bool result)
result = Application.Current.User.HasPermission
partial void Employees_Single_CanExecute…
partial void Employees_SingleOrDefault_CanExecute…
It’s important to note that LightSwitch queries are composable, meaning new queries can be based on an existing query. When applying access-control logic to queries, the permission requirements on the initial query serve as input to queries composed on that query. The Single and the SingleOrDefault queries are composed on the ‘All’ query, so securing the All query also secures these queries if no specific permissions are specified for the derived query. However, if you like, you can specify permissions on the derived query that are less restrictive than those on the composing query. Also, the CanRead method on the entity set will be applied before CanExecute for any queries of that type.
You may also see the logged in user name on the bottom right corner of the screen. You’ll be curious to note that, there’s no Sign out option by default.
Indeed, it is little tricky to implement the Sign Out option. Since these buttons are on the Silverlight application pages, they need to rely on the server side of the application to perform ‘FormsAuthentication.SignOut()’ operation. This part is not straightforward. To accomplish a Sign-out functionality, create a Separate ASP.NET web project and name it as same project name as LightSwitch application, WebAppAuth. Add a Web Page, LogOut.aspx like the following:
<form id=”form1″ runat=”server”>
And for the code-behind file:
public partial class LogOutForm : System.Web.UI.Page
protected void Page_Load
(object sender, EventArgs e)
Build this Web project and copy the LogOff.aspx from your ASPX project to the root location of your published LightSwitch app, right next to web.config and default.htm. And Copy the WebAppAuth.dll from the ASPX bin folder into the to the bin directory of your published LightSwitch app.
The next step is to wire up the ASPX page with the LightSwitch App. The easiest way, is to introduce a button on the LS App Screen and place the Button_Execute code
partial void LogOut_Execute()
HtmlPage.Window.Navigate(new Uri(“LogOff.aspx”, UriKind.Relative));
The above code needs reference to System.Windows.Browser assembly in the client. And after this wire-up, don’t forget to build your LS app and publish it to the remote host server.
This work around can be attached directly through the publishing process automatically by manually editing the WebAppAuth.lsproj file to manually include the Logoff pages automatically while you publish changes to your LS application. For steps to manually doing this, refer to this link.