gpt4 book ai didi

asp.net-mvc-3 - 具有 MVC3、ASP.NET 成员资格的多用户应用程序 - 用户身份验证/数据分离

转载 作者:行者123 更新时间:2023-12-04 16:55:56 25 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC3 和 EF4、一个数据库、一个代码库构建一个简单的多用户( Multi-Tenancy ?)应用程序,所有用户都使用相同的 URL 访问该应用程序。一旦用户登录,他们应该只能访问他们的数据,我使用默认的 asp.NET 成员资格提供程序,并在每个数据表上添加了一个“UserId”Guid 字段。显然我不希望用户 A 对用户 B 的数据有任何访问权限,所以我几乎在我的 Controller 上的每个操作中都添加了以下内容。

public ActionResult EditStatus(int id)
{
if (!Request.IsAuthenticated)
return RedirectToAction("Index", "Home");

var status = sService.GetStatusById(id);

// check if the logged in user has access to this status
if (status.UserId != GetUserId())
return RedirectToAction("Index", "Home");
.
.
.
}

private Guid GetUserId()
{
if (Membership.GetUser() != null)
{
MembershipUser member = Membership.GetUser();
Guid id = new Guid(member.ProviderUserKey.ToString());
return id;
}
return Guid.Empty;
}

这种重复肯定感觉不对,必须有一种更优雅的方式来确保我的用户无法访问彼此的数据——我错过了什么?

最佳答案

what am I missing?



自定义模型绑定(bind)器:
public class StatusModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Fetch the id from the RouteData
var id = controllerContext.RouteData.Values["id"] as string;

// TODO: Use constructor injection to pass the service here
var status = sService.GetStatusById(id);

// Compare whether the id passed in the request belongs to
// the currently logged in user
if (status.UserId != GetUserId())
{
throw new HttpException(403, "Forbidden");
}
return status;
}

private Guid GetUserId()
{
if (Membership.GetUser() != null)
{
MembershipUser member = Membership.GetUser();
Guid id = new Guid(member.ProviderUserKey.ToString());
return id;
}
return Guid.Empty;
}
}

然后您将在 Application_Start 中注册此模型绑定(bind)器:
// Could use constructor injection to pass the repository to the model binder
ModelBinders.Binders.Add(typeof(Status), new StatusModelBinder());

最后
// The authorize attribute ensures that a user is authenticated. 
// If you want it to redirect to /Home/Index as in your original
// example if the user is not authenticated you could write a custom
// Authorize attribute and do the job there
[Authorize]
public ActionResult EditStatus(Status status)
{
// if we got that far it means that the user has access to this resource
// TODO: do something with the status and return some view
...
}

结论:我们已经让这个 Controller 节食,这是 Controller 应该的方式:-)

关于asp.net-mvc-3 - 具有 MVC3、ASP.NET 成员资格的多用户应用程序 - 用户身份验证/数据分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com