Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity - Using Roles with JavaScript Functionality

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?

like image 554
madvora Avatar asked Mar 16 '23 13:03

madvora


1 Answers

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.

like image 110
Dave Ward Avatar answered Mar 23 '23 22:03

Dave Ward