9

I'm using ASP.NET MVC Framework 3 and Forms Authentication. I know, how to check on servers side, if the user is authorized for some action (with [Authorize]) and I know, how to check this within an action or a view (with User.Identity.IsAuthenticated or other members of 'User').

What I'm trying to do - is to define some JavaScript code, that will be executed differently, depending if the user is authorized.

Consider such script on the page:

<script>
 function Foo(){
  if(userAuthorized)
   alert("You\'re in the system");
  } else {
   alert("You\'re not authorized");
  }
<script>

Function Foo() is triggered by some event, say click. And I'd like to have an ability to check, if user is authorized, on clients side.

The best solution I've came up with is to actually render global variables initialization in view. Like this:

@if(User.Identity.IsAuthenticated)
{
 <script>
  var userAuthorized = true;
 </script> 
}
else
{
 <script>
  var userAuthorized = false;
 </script> 
}

But it doesn't seems to me as a good approach. Are there any other ways? Thanks in advance.

PS: This is a usability issue, of course I'm doing necessary checks on server.

3
  • 2
    how about including external javascript files for each case. Commented Apr 14, 2011 at 16:18
  • Actually, I thought to do so, if there is no other way. Anyways, thanks for your comment. Commented Apr 14, 2011 at 16:25
  • 1
    I don't think there's anything wrong with your approach. Commented Apr 14, 2011 at 16:33

2 Answers 2

21

I like the idea in @Gaby's comment, though I am not sure whether that's doable since I don't have the whole picture on your project.

At the very least you can simplify your code by doing...

<script>
  var userAuthorized = @User.Identity.IsAuthenticated.ToString().ToLower();
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Another couple of options would be to use a custom HTML data- attribute or create a simple ajax request that asks the server if the user is authenticated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.