简体   繁体   English

MVC 自定义授权属性

[英]MVC Custom Authorize Attribute

I have a method as below我有一个方法如下

[Authorize]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null) return NotFound();

            //EF bug workaround
            var activities =  (await _context.Activities.AsNoTracking().ProjectTo<ProgramActivityViewModel>()
                .Where(m => m.Id == id).ToListAsync()).SingleOrDefault();

            if (activities == null) return NotFound();

            if (activities.ActivityCoverageArea.Any())
                activities.PhysicalLocation = activities.ActivityPhysicalLocation != null;

            PopulateActivitiesModel(activities);           

            return View(activities);
        }

when user hits this method in browser URL he see this link.当用户在浏览器 URL 中点击此方法时,他会看到此链接。

http://localhost:52580/Activity/Activity/Edit/117

my issue if user manually enters id 125 instead of 117 in browser, he can see data that is not related to him.我的问题如果用户在浏览器中手动输入 id 125 而不是 117,他可以看到与他无关的数据。 i mean he can see his peer's data who is at same level , might be reporting to different manager.我的意思是他可以看到同级别的同事的数据,可能正在向不同的经理报告。 how can I restrict user from doing this??我怎样才能限制用户这样做?

the Id being passed is Activity id not UserId, a user can have multiple activityId's.传递的Id 是Activity id 而不是UserId,一个用户可以有多个activityId。 issue is , she should not see activity of other users.问题是,她不应该看到其他用户的活动。

You need to get the userId of the current logged in user and test that against your data.您需要获取当前登录用户的 userId 并根据您的数据对其进行测试。 If the data does not belong to the current user then you just need to return a 403 or custom error page.如果数据不属于当前用户,那么您只需要返回 403 或自定义错误页面。

If you are using the newer built in MVC authentication system then it should be as simple as: User.Identity.GetUserId();如果您使用的是较新的内置 MVC 身份验证系统,那么它应该很简单: User.Identity.GetUserId();

If you have this kind of issue all throughout your code then I suggest having the userId stored in a base controller or in a viewstate that you can easily access without having to hit your database with an extra request every time.如果您在整个代码中都遇到这种问题,那么我建议将 userId 存储在基本控制器或视图状态中,您可以轻松访问,而不必每次都用额外的请求访问数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM