Search code examples
jqueryasp.netasp.net-mvc-3client-sideviewdata

Access an authorisation flag from View Data in JavaScript (ASP.NET MVC)


I have an onclick which should not be available to anonymous users.

I currently hacked it together by using a flag element:

@if (ViewBag.User != null)
{
    <div id="userAuthenticated"></div>                        
}

and in jQuery:

$('.whatever').click(function() {
    if ($('#userAuthenticated').length) {
         // ... do something
    }
});

This just feels kinda nasty, but I'm not aware of any better way of doing it. What is best practice for handling this scenario. Is there some neat trick that I don't know about?


Solution

  • Instead, I would suggest having two separate javascript files, mysite-authorized.js and mysite-anon.js, and exclude any functions for authorized users only from the anon file. Then, in your layout file, set the js file to be served based on the authorization level.

    This way, you avoid any authorization flags, whch can be avoided by a savvy user.

    P.S.

    In your view, you already have a means to check for authorization:

    if (this.ViewContext.HttpContext.User.Identity.IsAuthenticated)
    {
        // authenticated user js file here
    }
    else
    {
        // anon user js file here
    }