ASP.NET MVC。检查用户是否从 JavaScript 获得授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5666270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC. Check if user is authorized from JavaScript
提问by Dmitriy
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').
我正在使用 ASP.NET MVC 框架 3 和表单身份验证。我知道,如何在服务器端检查用户是否被授权执行某些操作(使用[Authorize]
),我知道,如何在操作或视图中(使用User.Identity.IsAuthenticated
“用户”或其他成员)进行检查。
What I'm trying to do - is to define some JavaScript code, that will be executed differently, depending if the user is authorized.
我正在尝试做的是定义一些 JavaScript 代码,根据用户是否获得授权,这些代码将以不同的方式执行。
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.
功能Foo()
是由一些事件触发的,比如点击。我希望能够在客户端检查用户是否获得授权。
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.
PS:这是一个可用性问题,当然我正在对服务器进行必要的检查。
回答by jessegavin
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.
我喜欢@Gaby 评论中的想法,但我不确定这是否可行,因为我没有您项目的全貌。
At the very least you can simplify your code by doing...
至少您可以通过执行以下操作来简化代码...
<script>
var userAuthorized = @User.Identity.IsAuthenticated.ToString().ToLower();
</script>
回答by Charlino
Another couple of options would be to use a custom HTML data- attributeor create a simple ajax request that asks the server if the user is authenticated.
另一个选项是使用自定义HTML 数据属性或创建一个简单的 ajax 请求,询问服务器用户是否已通过身份验证。