從其他操作調用控制器操作時,是否需要使用RedirectToAction
?我現在只是直接打電話給他們,因爲我不希望他們回來,因此我繞過了授權標籤到我的一個行動(這是我想要的)。MVC3授權:是否可以通過其他操作調用授權操作的不正確形式?
能否請讓我知道這是否是不好的形式,如果是這樣,我應該創建多個新動作來設置客戶端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);
}
這是否繞過授權?如果是這樣 - 絕對不要這樣做。內部和外部方法之間有區別(不管是公共/私人還是暴露/不暴露於服務)。 – 2011-08-17 17:05:44
據我所知可以繞過,因爲在'LogOn()'Action中,我已經調用'FormsService.SignIn(model.UserName,model.RememberMe);'在我調用'SwitchClient'之前這對任何客戶端都有效,不管他們是否是'Administrator'角色 –