【发布时间】:2011-08-17 16:59:48
【问题描述】:
从另一个动作调用控制器动作时是否需要使用RedirectToAction?我目前只是直接调用它们,因为我不希望它们返回,因此我绕过 Authorize 标记来执行我的一项操作(它执行我想要的操作)。
如果这是错误的形式,请告诉我,如果是,我应该创建多个新操作来设置客户端 cookie 还是直接在 LogOn() 操作中设置它们?
我可以改为将SwitchClient 设为私有,然后将公开的授权操作设为仅供客户端管理员使用吗?然后,将通过 LogOn 操作调用私有操作,但除非用户通过管理员身份验证,否则无法访问。
这是我的代码:
[HttpGet]
[CustomAuthorizeAccess(Roles = "Administrator", RedirectResultUrl = "Unauthorized")]
public ActionResult SwitchClient(string client)
{
if (Request.Cookies["Client"] == null)
{
HttpCookie clientCookie = new HttpCookie("Client", client);
Response.Cookies.Add(clientCookie);
}
else
{
Response.Cookies["Client"].Value = client;
}
return new RedirectResult(Request.UrlReferrer.AbsolutePath);
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
//Add user's role to cookies (assumes each user only has one role)
string role = Roles.GetRolesForUser(model.UserName).First();
HttpCookie roleCookie = new HttpCookie("Role", role);
if (role == "client1")
{
SwitchClient("client1");
}
else if (role == "client2")
{
SwitchClient("client2");
}
else if (role == "Administrator" || role == "client3")
{
SwitchClient("client3");
}
//Make role cookie persistent for 7 days
//if user selected "Remember Me"
if (model.RememberMe)
{
roleCookie.Expires = DateTime.Today.AddDays(7);
}
if (Response.Cookies["Role"] != null)
{
Response.Cookies["Role"].Value = null;
Response.Cookies.Remove("Role");
}
Response.Cookies.Add(roleCookie);
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
【问题讨论】:
-
这会绕过授权吗?如果是这样,那么 - 绝对不要这样做。内部方法和外部方法之间存在差异(只是公共/私有或公开/未公开给服务)。
-
据我所知,它确实绕过了,因为在
LogOn()操作中,我在调用SwitchClient之前已经调用了FormsService.SignIn(model.UserName, model.RememberMe);(这适用于任何客户端,不不管他们是否是Administrator角色。
标签: asp.net-mvc-3 forms-authentication redirecttoaction authorize-attribute