gpt4 book ai didi

c# - 处理 Multi-Tenancy 站点中的数据访问

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:27 27 4
gpt4 key购买 nike

对于基于 MVC 的 Multi-Tenancy 站点中的数据访问/控制,我将不胜感激:

是否有更好/更安全/优雅的方法来确保在 Multi-Tenancy 站点中用户只能处理自己的数据。有许 Multi-Tenancy 使用相同的应用程序:firstTenant.myapp.com,secondTenant.myapp.com ...

    //
// GET: /Customer/
// show this tenant's customer info only

public ViewResult Index()
{
//get TenantID from on server cache
int TenantID = Convert.ToInt16( new AppSettings()["TenantID"]);
return View(context.Customers.ToList().Where(c => c.TenantID == TenantID));
}

如果用户是第一次登录并且没有该租户/用户的服务器端缓存 - AppSettings 检查数据库并将 TenantID 存储在缓存中。

数据库中的每个表都包含 TenantID 字段,用于将数据访问权限限制为只有合适的租户。

所以,说到重点,如果数据属于当前租户,而不是检查每个 Controller 中的每个操作,我可以做一些更“有成效”的事情吗?

例子:

当 firstTenant 管理员尝试为用户 4 编辑一些信息时,url 有: http://firstTenant.myapp.com/User/Edit/4

假设 ID 为 2 的用户属于 secondTenant。来自 firstTenant 的管理员 http://firstTenant.myapp.com/User/Edit/2在 url 中,并尝试获取不属于他的公司的信息。

为了防止在 Controller 中出现这种情况,我检查正在编辑的信息是否实际上由当前租户所有。

    //
// GET: /User/Edit/

public ActionResult Edit(int id)
{
//set tennant ID
int TenanatID = Convert.ToInt32(new AppSettings()["TenantID"]);
//check if asked info is actually owned by this tennant
User user = context.Userss.Where(u => u.TenantID == TenantID).SingleOrDefault(u => u.UserID == id);

//in case this tenant doesn't have this user ID, ie.e returned User == null
//something is wrong, so handle bad request
//

return View(user);
}

基本上,这种设置需要放置在每个可以访问任何数据的 Controller 中。是否有(以及如何)更好的方法来处理这个问题? (过滤器、属性...)

最佳答案

我选择使用操作过滤器来执行此操作。它可能不是最优雅的解决方案,但它是迄今为止我们尝试过的最简洁的解决方案。

我在 URL 中保留租户(在我们的例子中,它是一个团队):https://myapp.com/{team}/tasks/details/1234

我使用自定义绑定(bind)将 {team} 映射到实际的 Team 对象中,因此我的操作方法如下所示:

[AjaxAuthorize, TeamMember, TeamTask("id")]
public ActionResult Details(Team team, Task id)

TeamMember 属性验证当前登录的用户是否确实属于该团队。它还验证团队是否确实存在:

public class TeamMemberAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var httpContext = filterContext.RequestContext.HttpContext;

Team team = filterContext.ActionParameters["team"] as Team;
long userId = long.Parse(httpContext.User.Identity.Name);

if (team == null || team.Members.Where(m => m.Id == userId).Count() == 0)
{
httpContext.Response.StatusCode = 403;
ViewResult insufficientPermssions = new ViewResult();
insufficientPermssions.ViewName = "InsufficientPermissions";
filterContext.Result = insufficientPermssions;
}
}
}

同样,TeamTask 属性确保相关任务实际上属于团队。

关于c# - 处理 Multi-Tenancy 站点中的数据访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9735361/

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