Search code examples
backbone.jsbackbone-routing

backbone router how to hide parameters from url


I am using backbone router to redirect to my pages, I have for example this url

http://localhost:56508/#/RegistryMain/44/1234

The code

RegistryMain: function (id, cnt) {
        var self = this;
        this.load();
        require([
         'js/views/Questionaire/RegistryMain'
        ], function (RegistryMainView) {
            self.shell();
            if (typeof app.RegistryMainView !== 'undefined') {
                app.RegistryMainView.destroy();
            }
            app.RegistryMainView = new RegistryMainView({ Id: id, cnt: cnt });
            $("#main-nav li.active").removeClass("active");
            $("#admin").addClass("active");
        });
    },

For security reasons, I need to hide /44/1234 from the url so the user can't reuse them or change them to /45/1234 for example and access forbidden pages.

How can i do this in backbone?

And if i should use the POST approach, how to use it in backbone?


Solution

  • mu is too short is right in saying that you're trying to handle security in the wrong place. You can't trust client-side code, at all.

    You should check the rights of the user from the server each time the frontend app calls an API endpoint to avoid your users navigating to pages they don't have the rights to see, or to avoid them messing with the data by posting invalid stuff to an endpoint.

    Your API should return a 401 unauthorized HTTP response code to notify your frontend app of the situation.

    And for smooth page transition, redirect the user to an error page if an API call fails.

    That being said

    To avoid showing a url, you can directly call loadUrl:

    // current url: http://localhost:56508/#/RegistryMain
    
    Backbone.history.loadUrl("RegistryMain/44/1234");
    
    // current url: http://localhost:56508/#/RegistryMain
    

    This will trigger the route callback without changing the url, so the user never sees the params.


    Now that I use .loadUrl in my project, all pages have the same URL, but when I refresh a page, it redirects to the login page (the first page in my project). How to make it refresh the current page?

    That's a drawback of not using the url to trigger routes, you now can't know the state of the app as a single page app lives in the current page only and refreshing starts a new instance completely.

    You should really rethink if not using the url is the right choice. If it still is, you could save the current url in the localStorage and use it on the app startup to redirect to the right page.