LightSwitch Tip: A Simple Way to Check User Permissions from the HTML Client

LightSwitch Tip: A Simple Way to Check User Permissions from the HTML Client

  • Comments 9

UPDATE 4/17: If you’re not afraid to write some code, here’s a more robust way to get all the user permissions with one database call into the HTML client and use via JavaScript on any screen: Using LightSwitch ServerApplicationContext and WebAPI to Get User Permissions

----------------

Those of you that have been working with LightSwitch know that we support a robust permissions system that allows developers to define certain permissions and then check them in code. LightSwitch provides numerous “CanExecute” hooks on entities and queries that can be used for checking permissions around data & query actions.

For instance, if you have defined a permission “CanAddCustomer” you can check if a user has this permission before allowing Inserts on the Customer entity on the server. First define the permissions on the Access Control tab of the project properties:

image

Then in the data designer, select the Server perspective and then drop down the “Write Code” button and select the Customers_CanInsert access control method:

image

Then you write code like this to allow or disallow the insertion of customers:

Private Sub Customers_CanInsert(ByRef result As Boolean)
    result = Me.Application.User.HasPermission(Permissions.CanAddCustomer)
End Sub

You always want to secure the server-side this way in order to protect the data in your system. However, sometimes we also want to use a permission check in the UI in order to hide/unhide (or enable/disable) elements on a screen.

In the Silverlight desktop client this is a very easy thing to do because we make use of portable assemblies that allows LightSwitch to share code between the client and the server side. You have a User object available to you at all times from any screen. In the HTML client this isn’t the case but all is not lost!

Define a Query

If we want to check permissions on the HTML client screens, the easiest thing to do is add a query and secure the query on the server-side. For example, add a query based on Customer called CanAddCustomer:

image

 

Then add the code in the CanAddCustomer_CanExecute method to check the permission:

Private Sub CanAddCustomer_CanExecute(ByRef result As Boolean)
    result = Me.Application.User.HasPermission(Permissions.CanAddCustomer)
End Sub

Because this will hit the database if a user does have permission, we can make the query as efficient as possible by not returning any actual results. Select the CanAddCustomer_PreprocessQuery method and write a query that won’t return results.

Private Sub CanAddCustomer_PreprocessQuery(
            ByRef query As System.Linq.IQueryable(Of LightSwitchApplication.Customer))

    query = From c In query Where 0 = 1

End Sub

Set Up the Screen

Now that we have our query we can add it to the screen in which we want to enable/disable UI elements based on this permission. On the screen designer click the “Add Data Item” button at the top and add the query to your screen:

image

Then select the control you want to enable/disable and note its name in the properties window, we’ll need this in code.

image

Add Some JavaScript Code

Lastly, select the Screen node in the designer and then drop down the “Write Code” button and add code to the “created” method.

image

 

myapp.BrowseCustomers.created = function (screen) {
    // Write code here.
    screen.getCanAddCustomer().then(function success() {
        screen.findContentItem("AddCustomer").isEnabled = true;
    }, function error() {
        screen.findContentItem("AddCustomer").isEnabled = false;
    });

};

The code calls the query on our screen and it will fail if the user doesn’t have permission to execute it, which will invoke the failure handler. Note that this could also hide the UI if the query failed for another reason, but this ensures the UI is only shown if the client can actually verify the user’s permissions.

Remember that hiding the elements in the client doesn't provide real security, so make sure to use the server-side access control methods shown above to ensure no client can access data you want to protect. 

Enjoy!

Leave a Comment
  • Please add 2 and 6 and type the answer here:
  • Post
  • What a hack. How about a real integrated solution for this common scenario?

  • @Robert -- I'm showing an easy way to accomplish this without having to write a lot of client code. Keep in mind that permissions should always be checked on the server pipeline where the data and business rules are. I am working on some other options so stay tuned :)

  • If you’re not afraid to write some code, here’s a more robust way to get all the user permissions with one database call into the HTML client and use via JavaScript on any screen:

    blogs.msdn.com/.../using-lightswitch-serverapplicationcontext-and-webapi-to-get-user-permissions.aspx

  • In a fact i love the way how you present things , and i would like to ask about :

    - how to print an order from light switch application orders screen ?

    - how can i create and edit reports in light switch  ?

    Thanks.

  • @Robert - Yes it is a Hack, but what a great hack it is :)

    Well done Beth, as I used it to easily customize a default HTML landing page based upon User's permissions.

    And in part, offered an alternate to this forum posting:

    <a href="social.msdn.microsoft.com/.../programatically-select-home-screen-html">Programatically Select Home Screen HTML</a>

  • I've been using this snippet of code in my solution to manage permissions. For a while now, I notice that every day I am getting hundreds of HTTP Errors, mainly because of this solution. Is there any way to avoid having the server run in to and record a HTTP Error from this.  Can it silently fail in some way?

    Thanks,

    Louis

  • Hi Louis,

    What is the exception being thrown? You'll need to diagnose the problem a little deeper. Try setting CustomErrors=Off in the web.config and hitting it with Fiddler. (See this post: blogs.msdn.com/.../diagnosing-problems-in-a-deployed-lightswitch-application-eric-erhardt.aspx)

    If you can't figure it out, start a thread in the forum and we can help from there. msdn.microsoft.com/.../vstudio

  • I actually agree with robert, here. Albeit, late to the game, but if Lightswitch is supposed to be a rapid development for simple applications, why is there no standard way to generate permissions, especially when they can be such a common requirement for a windows environment?

    I'm not scared to write code, unless of course it will have to be redone after a 'new' standard is released. I hope this will not be the case in the near future.

  • Hi :),

    Iam new in light switch, what If i want to compare the user right in my database with Light switch.

    for example the user have the righ Manager ------- > then he will be able to see all screens in light switch.

    how to do this? I exporeted the project to my desktop (.exe) then I took a look at the folder where is was exported there was a 2 SQL files CreatUser, and another file call NaVview(this is my project).

    is the right is to chang the sql code in thoses files to say show:

    EX:

    Select *

    from  DB

    where roles = 'manger'?

    or what can I do?

    Best regards,

    Zayed

Page 1 of 1 (9 items)