What is the best way to prevent user from seeing things like admin links in a knockout component?
I don't want to make a client request if the user has right to see those links because it would expose this section on the client.
The only way I can figure it out is to use a view to represent the component template and then check if the user as right on the server-side before rendering the HTML.
But is there another way that can be cleaner than this or is it the right way to proceed?
I've faced similar challenges with AngularJS Apps.
Rather than perform an extra service request, I like to pass logged-in status and role in Model or
ViewBag
.For simplicity, let's assume we're using
ViewBag
.1) In the Action Method, set
2) In a JS File, globally define
UserModel
with bindings and function to check if user has correct role-name:In .cshtml View:
3) bind Role and Logged in data
4) Show Partial if
Role
is correct:Ways to hide Admin Components:
The Razor Ways:
Rather than hide components with Knockout, there are C#/Razor ways
-> Nested if clause
The advantage of Razor Conditions over Knockout is the component will not render when server creates page, leaving no trace for client to see
-> Conditional sections in
_Layout
Cleaner than simple Razor Condition and automatically applied throughout application
-> Partial with Child Action
Called
(Action, Controller, Parameter)
:The cleanest of all approaches. Can be combined in a section for greater convenience.
Conclusion on how to hide Admin Components:
How you choose to hide Admin Components depends on your needs. The Razor/C# approach is more convenient and feels more secure.
On the other hand, if you are interested in giving the user the SPA experience,
C#
and server methods fall short. Do you allow users to Authenticate without refreshing pages? If so, an Admin may Authenticate and change from anonymous user to Admin.If you are comfortable with refreshing the screen to show the changed content,
C#/Razor
is your approach. If your priority is to give the user the "responsive experience", You will want to implement a Knockout solution.