我用这段代码看到的问题是,它将被重用很多;任何被认证用户(除了网站管理员)编辑/创建的内容都只能访问他们的“工作室”对象。ASP.NET MVC - 授权重构
我的问题给大家;你将如何重新考虑这一点,以便服务层可以从客户的知识中抽象出来。我打算稍后在独立桌面应用程序中重用服务层。
请阐明我错误的方式!我非常感谢。
AuthorizeOwnerAttribute.cs(AuthorizeAttribute)
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Get the authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = httpContext.Request.Cookies[cookieName];
// If the cookie can't be found, don't issue the ticket
if (authCookie == null) return false;
// Get the authentication ticket and rebuild the principal & identity
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] userData = authTicket.UserData.Split(new[] { '|' });
int userId = Int32.Parse(userData[0]);
int studioID = Int32.Parse(userData[1]);
GenericIdentity userIdentity = new GenericIdentity(authTicket.Name);
WebPrincipal userPrincipal = new WebPrincipal(userIdentity, userId, studioID);
httpContext.User = userPrincipal;
return true;
}
内部我的 “用户” 控制器此属性附加到需要一个所有者的任何方法的现在
[AuthorizeOwner]
public ActionResult Edit(int Id)
{
IUser user = userService.GetById(HttpContext.User, Id);
return View(user);
}
,在我的服务层是我正在检查传入的IPrincipal是否有权访问请求的对象。 这是它变得臭:
UserService.cs
public IUser GetById(IPrincipal authUser, int id)
{
if (authUser == null) throw new ArgumentException("user");
WebPrincipal webPrincipal = authUser as WebPrincipal;
if (webPrincipal == null) throw new AuthenticationException("User is not logged in");
IUser user = repository.GetByID(id).FirstOrDefault();
if (user != null)
{
if (user.StudioID != webPrincipal.StudioID) throw new AuthenticationException("User does not have ownership of this object");
return user;
}
throw new ArgumentException("Couldn't find a user by the id specified", "id");
}
你能详细讲解会话哈希部分吗? – 2009-11-05 15:41:23
看看这里:http://msdn.microsoft.com/en-us/library/ms178581.aspx – Lazarus 2009-11-05 16:13:13
你能给我一个使用会话哈希的例子吗?我不确定我是否关注你。哪里来玩? – 2009-11-05 17:02:29