I have an application using JQuery DataTables. I want these tables to display for every user, but only allow the click functionality for users in a specific role.
So, I can set up authorization on the controllers with this...
[Authorize(Roles = "Admin")]
That's not enough because there will still be a call to this controller and method and a redirection for those not in the "Admin" role.
Let's say I have a function in my javascript like this...
//Click event on the table row
$('#table1').on('click', 'tr', function (event) {
//Post the data to the controller
$.ajax({
type: "POST",
url: "/Controller/Action",
data: {someData : someData},
success: function () {
//do something
}
});
});
I'd like to wrap something around this around the click event...
if (role == "Admin") { //click event in here }
Now, I know that the roles are on the server side, while the javascript is on the client side.
I've seen some suggestions about using razor syntax to output something into a hidden column and then grab that value with the javascript. Something like this...
@if (User.IsInRole("Admin"))
{
<input type="hidden" id="isAdmin" value="true">
}
But, that's not really secure, because the hidden fields can still be accessed. What proper way can I use these identity roles to work with my javascript?
One relatively easy approach is to move your admin JavaScript to a separate file and only include it if the user is in your admin role. E.g.:
@Scripts.Render("bundles/js/app")
if (User.IsInRole("Admin") {
Scripts.Render("bundles/js/admin")
}
That way, it can progressively enhance the app for admins by lighting up admin-specific features to augment the regular users' experience.
Obviously, the most important line of defense is still the [Authorize]
attribute on your controller or action though. No Razor view tricks or JavaScript shenanigans can replace that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With