次の方法で共有


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

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!

Comments

  • Anonymous
    April 13, 2013
    The comment has been removed

  • Anonymous
    April 15, 2013
    @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 :)

  • Anonymous
    April 17, 2013
    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

  • Anonymous
    June 14, 2013
    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.

  • Anonymous
    July 06, 2013
    The comment has been removed

  • Anonymous
    September 16, 2013
    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

  • Anonymous
    September 16, 2013
    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

  • Anonymous
    June 03, 2014
    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.

  • Anonymous
    July 13, 2014
    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  DBwhere roles = 'manger'?or what can I do?Best regards,Zayed

  • Anonymous
    January 11, 2015
    Hi Beth,Thanks for help the LightSwitch Community.I have used and I will continue to use LightSwitch (HTML and SilverLight).It's very nice and very productive!

  • Anonymous
    July 25, 2015
    Dear Beth I have applied your approach and it working very well, but somehow it takes some seconds to disable the buttons, which may let the user to click it before its disabled .. Any Help please ???

  • Anonymous
    September 05, 2015
    Why this code fails the first time? (id null or not defined) When I retry it works! myapp.ConfirmarRecepcion.created = function (screen) {    // Write code here.    if (screen.GUIAItem.Documento.id != 1) {        screen.findContentItem("GUIAItem_pagadoEntrega").isEnabled = false;    } };

  • Anonymous
    December 01, 2015
    Is it possible to reference the security entities via a RIA service as described in blogs.msdn.com/.../how-to-reference-security-entities-in-lightswitch.aspx ?

  • Anonymous
    May 18, 2016
    I'm curious to find out what blog platform you have been utilizing? I'm experiencing some small security issues with my latest site and I would like to find something more safeguarded.Do you have any suggestions?

  • Anonymous
    June 11, 2016
    The comment has been removed

  • Anonymous
    June 23, 2016
    What's up, just wanted to say, I loved this article. It was practical.Keep on posting!

  • Anonymous
    September 19, 2016
    Wow, աonderful weblog layout! How long have you еver been running a blog foг? you made blogging glance eаsy. The entire look of your web site is fantаstic,as neatly as the content!

  • Anonymous
    December 16, 2016
    Hi if your does not have permission to view, i want to hide the tab itself in screen.in htmlclient-defaulti have few tabs (i.e. customer<products)when user clicks on customer, it displays the customer tabhere my questionbased on the user permissions the customer tab should be hide/show.if user does not have read permissions, the tab should be hidecan you please help me in this

  • Anonymous
    May 10, 2017
    I am new to lightswitch. I refer your videos only to complete my lightswitch project. I am facing one problem in adding permissions to the entity. When i callresult = Me.Application.User.HasPermission(Permissions...) after Permissions i do not get list of permissions ,instead i get string operations. How do I correct it so that I can get list of permissions?

    • Anonymous
      May 12, 2017
      Could figure out the issue Permissions method was overloaded to string after removing that could access the permissions list.Thank you