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

2019-05-17 18:25发布

问题:

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