Restricting Access to a LightSwitch Screen
In this lesson, you’ll learn how to apply a permission to restrict access to a screen in a LightSwitch application.
To write code to set permissions for a query
In Solution Explorer, open the shortcut menu for the CurrentProducts.lsml node, and then choose Open.
On the toolbar, open the Write Code list, and then choose CurrentProducts_CanExecute.
The Code Editor opens and displays the CurrentProducts_CanExecute method.
In the Code Editor, enter the following code in the CurrentProducts_CanExecute method:
To write code to set permissions for a screen
In Solution Explorer, open the shortcut menu for the Home.lsml node, and then choose Open.
In the Screen Designer, on the toolbar, choose the Add Data Item button.
In the Add Data Item dialog box, choose the Query option button. In the list, choose NorthwindEntitiesData.CurrentProducts, and then choose the OK button.
On the toolbar, open the Write Code list, and then choose created.
In the Code Editor, add the following code to the created method:
In Solution Explorer, open the shortcut menu for the Screens node, and then choose Edit Screen Navigation.
Open the shortcut menu for the Products node, and then choose Delete.
Run the application. Notice that the Products button is disabled. This is because the Test User account doesn’t have the Can_View_Products permission. You’ll learn how to grant permission in the next lesson.
In this lesson, you learned how to apply a permission to restrict access to a screen. For HTML client screens, this is a two-part process: setting permissions to run a query on the server, and then checking for permission from the client.
Every query has a CanExecute method that can be used to check for permissions. In this case, the code runs the HasPermission method, and checks to see whether the Can_View_Products permission is assigned to the current user. If it is, the method returns a result of true; if not, the method returns a result of false.
In this example you deleted the Products menu item to prevent the user from launching the Products screen from the menu. It’s also possible to disable menu items dynamically, but the process is much more involved. See Using LightSwitch ServerApplicationContext and WebAPI to Get User Permissions.
This is just one example of the code that you could write to check for permissions and restrict access. On the server, you can use any of the entity can methods such as canRead, canInsert, or canDelete to check for permissions. On the client, you can apply permissions to specific screen elements, and you can use the isVisible method to hide an element instead of disabling it.
In the next lesson, you’ll learn how to use debug permissions to test code.
Next lesson: Using Debug Permissions to Test LightSwitch Code