Sim*_*mon 11 c# iis asp.net-mvc authorization asp.net-mvc-5
IIS-经理
要限制对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>
Run Code Online (Sandbox Code Playgroud)
当bypassLoginPages
设置为true
,所有用户都有权访问登录页面.当用户未登录时,他将自动被重定向到登录页面:
<authentication mode="Forms">
<forms [...] loginUrl="~/Auth/Login" [...] >
[...]
</forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)
MVC5应用程序:
用户必须通过Windows SamAccountName和密码通过自定义登录页面登录.凭据将发送到以下Login
操作AuthController
:
[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
}
}
Run Code Online (Sandbox Code Playgroud)
所有受限制的控制器都会[Authorize]
自动通过属性进行授权检查:
[Authorize]
public class MainController : Controller
{
[...]
}
Run Code Online (Sandbox Code Playgroud)
像装饰一样[Authorize(Users="User1,User2")]
没有解决方案,因为最终用户无法访问代码,应该可以配置对应用程序的访问.
当用户未获得授权时,他将被重定向到登录页面.这很好.但是我需要在Login
之前的行动中进行授权检查.所以我的问题:
AuthController
如果登录用户有权重定向到MainController
?如何在我的手动验证?
问:如果登录用户有权重定向到MainController,如何在我的AuthController中手动验证?
由于您使用的是Authorize
属性,因此无需在操作中手动检查授权.这些是一些规则:
[Authorize]
[Authorize(Users="User1,User2")]
[Authorize(Roles="Administrators,PowerUsers")]
由于您修饰了MainController
with Authorize
属性,这意味着没有人可以在没有登录的情况下访问其操作.因此,在Logon
操作中,您无需检查用户是否有权重定向到主控制器.这里没有任何安全漏洞,您在使用时无需担心授权RedirectToAction("Index", "Main")
.
问: Authorize属性中的定义无法解决问题.管理员如何在购买软件时限制用户和组?你无法访问代码.
角色是为此类要求而创建的.你应该使用[Authorize(Roles="Role1")]
上面的MainController
,然后每个用户都Role1
可以访问主控制器的动作.它可以简单地在您的应用程序的用户和角色管理中完成.所以:
注意
在大多数应用程序中,角色是静态的,您可以说哪个角色可以访问哪个操作.在这种情况下,当前Authorize
属性足以授权.只需在运行时将用户添加到角色即可.标识样本包含所需的模型,视图和控制器.
如果要在运行时创建新角色或在运行时更改角色的权限,则需要创建一个新Authorize
属性,该属性从配置文件或数据库中读取用户的角色,并且还要读取角色的权限从配置文件或数据库中决定授权.
归档时间: |
|
查看次数: |
1061 次 |
最近记录: |