How can I isolate users' data in ASP.net MVC application?

試著忘記壹切 提交于 2019-12-12 09:52:48

问题


So I have an asp.net application (using MVC5, ASP 4.5, EF) deployed on Azure. The application allows users to register and login. However, once logged in, anyone can see everyone else's data.

What is the best practice to isolate the data belonging to different users so that each user can only see the data he/she creates?

Another small question is how does Facebook separates its users' data?

Thanks


回答1:


For every piece of data a user creates, store their user ID and only allow users to see data that has their user ID. A couple of examples:

SQL:

SELECT UserDataID, Value FROM UserData WHERE UserID = @UserID;

Pass in the user's id to the @UserID parameter.

LINQ:

using (var entityFrameworkContext = new MyDataEntities())
{
    var currentUserData = entityFrameworkContext.UserData.Where(userData -> userData.UserID = currentUserID);
}

Where currentUserID could be the user name or ID from forms authentication, for example: HttpContext.Current.User.Identity.Name.




回答2:


The way in which I accomplished this was by the following.

In your controller you will need to use

 public ActionResult Index()
    {
        var currentUser = manager.FindById(User.Identity.GetUserId());
        return View(db.ToDoes.ToList().Where(todo => todo.User.Id == currentUser.Id));
    }

You can then also create an admin role which can then view all the details of users and return ToList(). You then might want to put an [Authorize] method on it to only allow Admins access.

    [Authorize(Roles="Admin")]
    public async Task<ActionResult> All()
    {
        return View(await db.ToDoes.ToListAsync());
    }

I found the following project of great help in understanding. https://github.com/rustd/AspnetIdentitySample

Hope this is of some help



来源:https://stackoverflow.com/questions/20340489/how-can-i-isolate-users-data-in-asp-net-mvc-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!