我有一个 ASP.NET MVC 项目。在这个项目中,用户可以登录到我的网站。所有登录用户都进入同一页面登录页面。我的网站有一个单独的部分,然后只为某些用户划分。这是在 Web.config 中由以下内容定义的:
<location path="SectionedOff">
<system.web>
<authorization>
<allow users="user1,user2,user3" />
<deny users="*" />
</authorization>
</system.web>
</location>
如果用户被授权使用此部分,我想在页面上显示一个按钮,每个人在登录时都会被重定向到该按钮。这是我要完成的粗略绘画: 我已经完成了身份验证和适当的授权,我只是不确定如何根据用户是否获得网站单独部分的授权来显示和隐藏此按钮。我暗暗怀疑我必须阅读 Web.config 文件以获取此信息,但是,我无法弄清楚如何在 Web.config 中的某个位置读取信息。任何帮助将不胜感激:)
最佳答案
<authorization>
web.config
部分file 用于保护虚拟文件和文件夹。它对 MVC Controller 和操作绝对没有影响(当然除非操作试图访问物理文件)。
保护 MVC Controller 和操作的正确方法是使用 AuthorizeAttribute
.参见 this post有关如何将其与 AllowAnonymous
结合使用的示例属性(推荐的方法是保护所有内容,除非您想选择退出,然后应用 AllowAnonymous
属性)。
AuthorizeAttribute
取决于 IPrincipal
和 IIdentity
接口(interface)。所有 security frameworks来自 Microsoft 的(身份、成员身份等)实现了这些接口(interface),因此它们可以与 AuthorizeAttribute
无缝协作.如果您有自定义安全框架,则应实现这些接口(interface) - 请参阅 this answer .
一旦这些实现就位并添加为 HttpContext 的一部分,检查用户是否登录以及他们是否担任特定角色就非常简单了。
@if (this.User.Identity.IsAuthenticated)
{
<input type="button" value="Go somewhere that requires logged in user" />
}
@if (new string[] { "user1", "user2", "user3" }.Contains(this.User.Identity.Name))
{
<input type="button" value="Go somewhere that requires user1, user2, or user3" />
}
@if (this.User.IsInRole("Admin"))
{
<input type="button" value="Go somewhere that requires an Admin role" />
}
或者,您可以使用 MvcSiteMapProvider
, 当 AuthorizeAttribute
时自动隐藏菜单选项对相应的操作没有权限。
Disclaimer: I am a major contributor of the
MvcSiteMapProvider
project.
关于asp.net - 仅当用户有权查看该页面时,我如何显示链接到该页面的按钮? ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37554536/