加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 具有MVC3的多用户应用程序,ASP.NET成员资格 –

发布时间:2020-12-16 03:28:37 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.NET MVC3和EF4构建一个简单的多用户(多租户?)应用程序,一个数据库,一个代码库,所有用户使用相同的URL访问应用程序.一旦用户登录,他们应该只能访问他们的数据,我使用默认的asp.NET成员资格提供程序,并在每个数据表上添加了“UserId”Guid字段.
我正在使用ASP.NET MVC3和EF4构建一个简单的多用户(多租户?)应用程序,一个数据库,一个代码库,所有用户使用相同的URL访问应用程序.一旦用户登录,他们应该只能访问他们的数据,我使用默认的asp.NET成员资格提供程序,并在每个数据表上添加了“UserId”Guid字段.显然,我不希望用户A对用户B的数据有任何访问权限,因此我几乎在控制器上的每个操作中都添加了以下内容.

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?

自定义模型绑定器:

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中注册这个模型绑定器:

// 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
    ...
}

结论:我们已经把这个控制器放在饮食控制器应该是这样的方式:-)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读