IIS-Manager
要限制对Web应用程序的访问,管理员可以通过IIS管理器设置用户和组的URL授权:
Web.config
IIS-Manager将授权规则存储在应用程序的web.config中:
<security>
<authorization bypassLoginPages="true">
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="Testuser" />
<add accessType="Deny" users="*" />
</authorization>
</security>
当 bypassLoginPages
设置为 true
时,所有用户都有权访问登录页面 . 当用户未登录时,他将自动被重定向到登录页面:
<authentication mode="Forms">
<forms [...] loginUrl="~/Auth/Login" [...] >
[...]
</forms>
</authentication>
MVC5 App:
用户必须通过Windows SamAccountName和密码通过自定义登录页面登录 . 凭据将发送到 AuthController
的 Login
操作:
[AllowAnonymous]
public class AuthController : Controller
{
public ActionResult Login
{
// validation of SamAccountName and Password against Active Directory here.
[...]
// We want to check the authorization here.
// create authentication ticket
FormsAuthenticationTicket lFormsAuthenticationTicket = new FormsAuthenticationTicket(1,
SamAccountName,
DateTime.Now,
DateTime.Now.AddMinutes(AuthCookieTimeout),
RememberMe,
CustomData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string lEncryptedTicket = FormsAuthentication.Encrypt(lFormsAuthenticationTicket);
var lAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, lEncryptedTicket);
// Create the cookie.
Response.Cookies.Add(lAuthCookie);
[...]
return RedirectToAction("Index", "Main"); // redirect to the main controller
}
}
所有受限制的控制器都会自动通过 [Authorize]
属性进行授权检查:
[Authorize]
public class MainController : Controller
{
[...]
}
像 [Authorize(Users="User1,User2")]
这样的装饰是没有解决方案的,因为Endusers无法访问代码,因为它可以配置对应用程序的访问 .
当用户未获得授权时,他将被重定向到登录页面 . 这很好 . 但我之前需要在 Login
动作中进行授权检查 . 所以我的问题:
如果登录用户有权重定向到 MainController
,如何在 AuthController
中手动验证?
3 回答
由于您使用的是
Authorize
属性,因此无需在操作中手动检查授权 . 这些是一些规则:限制对经过身份验证的用户的访问权限:
[Authorize]
限制对某些特定用户的访问权限:
[Authorize(Users="User1,User2")]
限制对某些特定角色的访问权限:
[Authorize(Roles="Administrators,PowerUsers")]
由于您使用
Authorize
属性修饰了MainController
,这意味着没有人可以在没有登录的情况下访问其操作 . 因此,在Logon
操作中,您不会在此处发现任何安全漏洞,并且在使用RedirectToAction("Index", "Main")
时无需担心授权 .角色是为此类要求而创建的 . 您应该使用
[Authorize(Roles="Role1")]
以上MainController
然后Role1
的每个用户都可以访问主控制器的操作 . 它可以简单地在您的应用程序的用户和角色管理中完成 . 所以:在开发时,使用静态角色装饰控制器和操作
在运行时,您可以使用应用程序管理用户角色 .
Note
在大多数应用程序中,角色是静态的,您可以说哪个角色可以访问哪个操作 . 在这种情况下,当前的
Authorize
属性足以进行授权 . 只需在运行时将用户添加到角色即可 . Identity Samples包含所需的模型,视图和控制器 .如果要在运行时创建新角色或在运行时更改角色的权限,则需要创建一个新的
Authorize
属性,该属性从配置文件或数据库中读取用户的角色,并且还读取权限 . 配置文件或数据库中的角色,并决定授权 .You should not use <authorization> tag in ASP.Net MVC. 适用于 ASP.Net Web Form . 您可以在SO中阅读更多内容 .
在ASP.Net MVC中,您想要使用
[Authorize]
属性 . 此外,您想使用 OWIN middleware 而不是旧 FormsAuthenticationTicket .它很少,所以我在GitHub AspNetMvcActiveDirectoryOwin中创建了一个示例项目 . 原始源是用AD进行身份验证,但您只需要调整ActiveDirectoryService类 .
以下三个是主要类 -
AccountController
ActiveDirectoryService
OwinAuthenticationService替换FormsAuthentication .
两种选择,
使用
Authorize
下的"Roles"选项,如下所示:然后将应允许访问此操作的用户添加到这些角色 . 角色是ASP身份使用的
ClaimsPrincipal
的一部分 .或者,提供您自己的
Authorize
属性实现,该属性测试当前登录用户的任何业务规则,然后允许或禁止访问 .