用户能够编辑不属于同一用户的其他实体,我如何才能阻止此操作?

问题描述 投票:0回答:1

我正在为我的应用程序使用

FormsAuthentication
,当用户通过身份验证时,用户可以编辑和更改url中的
ID
参数并且用户能够更改和编辑其他用户的数据,为了解决这个问题我使用这个解决方案:

[Authorize]
public ActionResult UserInfo(long id)
{
    var userViewModel = _userService.GetUserById(id);
   ** if (userViewModel.Username != HttpContext.User.Identity.Name)
        throw new UnauthorizedAccessException("we are not allowed to show other users' information to you");**
    return View(userViewModel);
}

但这不是一个好的解决方案,因为有了这个,我必须检查所有操作的相同逻辑,以检查用户是否正在编辑他/她自己的数据 我如何使用 dbContext 中的 AOP 解决方案和其中的

SaveChanges()
来解决它?

我的用户类:

public string Username { get; private set; }
public string Password { get; private set; }
public string Name { get; private set; }
public DateTime? BirthDate { get; private set; }
public List<WishList.WishList> WishLists { get; private set; }

其他班级:

public string Title { get; private set; }
public string Description { get; private set; }
public List<WishListItem.WishListItem> WishListItems { get; private set; }
public User.User User { get; private set; }
public long UserId { get; private set; }

public string Title { get; private set; }
public decimal RoughPrice { get; private set; }
public int Priority { get; private set; }
public WishList.WishList WishList { get; private set; }
public long WishListId { get; private set; }

我的数据库上下文:

public class WishListManagementDbContext : System.Data.Entity.DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<BaseEntity> BaseEntities { get; set; }
    public DbSet<WishListItem> WishListItems { get; set; }
    public DbSet<WishList> WishLists { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.AddFromAssembly(typeof(WishListManagementDbContext).Assembly);
        base.OnModelCreating(modelBuilder);
    }

}

如果你能帮助我,我将不胜感激。

c# asp.net-mvc forms-authentication
1个回答
0
投票

无需在每个操作中都编写此代码的一种可能方法是使用全局过滤器。它将在您的应用程序的每个操作调用中自动执行。

创建一个派生自

ActionFilterAttribute
IActionFilter
的类,并覆盖方法
OnActionExecuting
。所以,对于你的情况,它会是这样的:

using Microsoft.AspNetCore.Mvc.Filters;

public class MyGlobalActionFilter : ActionFilterAttribute, IActionFilter
{
    //I am assuming you used DI for the service, so you can use it here too
    private readonly UserService _userService;
    public MyGlobalActionFilter(UserService userService)
    {
        _userService = userService;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var userViewModel = _userService.GetUserById(id);
        if (userViewModel.Username != HttpContext.User.Identity.Name)
            throw new UnauthorizedAccessException("we are not allowed to show other users' information to you");
    }
}

然后将其添加到您的

Program.cs
文件中:

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<MyGlobalActionFilter>();
});
© www.soinside.com 2019 - 2024. All rights reserved.