c# – 如何在MVC5中手动检查url授权?
IIS-经理
要限制对网络应用程序的访问,管理员可以通过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应用: 用户必须通过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] public class MainController : Controller { [...] } 像[Authorize(Users =“User1,User2”)]这样的装饰是没有办法的,因为Endus的代码是不可访问的,应该可以配置对应用的访问. 当用户未被授权时,他将被重定向到登录页面.工作正常但是我需要在Login操作中进行授权检查.所以我的问题: 如果登录的用户被授权重定向到MainController,我如何手动验证我的AuthController? 解决方法
由于您使用的是Authorize属性,因此您不需要在操作中手动检查授权.这些是一些规则: >限制对已认证用户的访问权限:[授权] 由于您使用Authorize属性装饰MainController,所以无需登录即可访问其操作.
为此需求创建角色.您应该使用MainController以上的[Authorize(Roles =“Role1”)],然后Role1的每个用户都可以访问主控制器的操作.它可以简单地在您的应用程序的用户和角色管理中完成.所以: >在开发时,用静态角色来装饰控制器和动作 注意 在大多数应用程序中,角色是静态的,您可以确定哪个角色可以访问哪些操作.在这种情况下,当前的Authorize属性将足以进行授权.只需在运行时将用户添加到角色. Identity Samples包含所需的型号,视图和控制器. 在运行时要创建新角色或在运行时更改角色权限的情况下,需要创建一个新的Authorize属性,该配置文件从配置文件或数据库读取用户的角色,并且还可以读取角色从配置文件或数据库,并决定授权. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |