ASP.NET Identity - Using Roles with JavaScript Functionality
I have an application using JQuery DataTables. I want these tables to appear per user, but only allow users to click in a specific role.
So, I can set up authorization on controllers with this ...
[Authorize(Roles = "Admin")]
This is not enough because there will still be this controller and method invocation and 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 would like to wrap something around the click event ...
if (role == "Admin") { //click event in here }
Now I know that roles are server side and javascript is client side.
I've seen some suggestions for using razor syntax to output something to a hidden column and then grab that value with javascript. Something like that...
@if (User.IsInRole("Admin"))
{
<input type="hidden" id="isAdmin" value="true">
}
But this is not very secure because hidden fields can be accessed. How can I use these identity roles to work with my javascript?
source to share
One relatively straightforward approach is to move your JavaScript admin into a separate file and only enable it if the user is in the admin role. For example:.
@Scripts.Render("bundles/js/app")
if (User.IsInRole("Admin") {
Scripts.Render("bundles/js/admin")
}
Thus, it can gradually expand the admin app by launching admin functions to enhance the experience of regular users.
Obviously, the most important line of defense is still an attribute [Authorize]
on your controller or action. No Razor browsing tricks or JavaScript shenanigans can replace this.
source to share
You can do this without going through the model
@if (Request.IsAuthenticated && User.IsInRole ("administrator"))
If this is a single page application, you will need to pass the model. If a hacker changes their role to admin in javascript, they will see buttons with buttons, but they won't be able to do anything with it if they arn admin.
source to share