简体   繁体   English

通过n层应用程序传递用户身份

[英]Passing User identity through n-tier application

I have an MVC.Net application that is separated out into tiers containing Repositories, Business logic and front end services for AngularJS and MVC Controllers. 我有一个MVC.Net应用程序,该应用程序分为包含AngularJS和MVC控制器的存储库,业务逻辑和前端服务的层。

The repositories are currently stand alone and not wrapped in a unit of work pattern. 当前,存储库是独立的,没有以工作模式包装。 This refactoring is going to take place. 重构将进行。

I wanted to query with people what in their experience is the most efficient way to carry the current logged in user through the various tiers to enable security at the repository level. 我想向人们询问,以他们的经验,最有效的方式是使当前登录的用户通过各个层,以在存储库级别实现安全性。

At the moment I have a UserLogic class that maintains a reference to the current logged in user's Entity. 目前,我有一个UserLogic类,该类维护对当前登录用户的Entity的引用。 This UserLogic class is then injected into controllers/business logic etc... But I suspect that's a fairly convoluted mechanism to use! 然后将此类UserLogic类注入到控制器/业务逻辑等中……但是我怀疑这是一个相当复杂的机制!

One approach could be to have any given repository require a user context upon instantiation. 一种方法是让任何给定的存储库在实例化时都需要用户上下文。 Something like this: 像这样:

public class WidgetRepository
{
    private UserContext User { get; set; }

    public WidgetRepository(UserContext user)
    {
        if (user == null)
            throw new ArgumentNullException("user");
        // maybe also confirm that it's a *valid* user in some way?
        User = user;
    }

    // repository operations
}

You can employ as much "defensive programming" in that constructor as you like, I suppose. 我想,您可以根据需要在该构造函数中使用尽可能多的“防御性编程”。 Then in the repository operations you can filter queries based on that user. 然后,在存储库操作中,您可以基于该用户过滤查询。 Something like: 就像是:

public IEnumerable<Widget> Widgets
{
    get
    {
        return dbContext.Widgets.Where(w => w.Owner.Id == User.Id);
    }
}

This would filter all widgets by the user who owns them transparently to the application. 这将对应用透明地拥有它们的用户过滤所有窗口小部件。

Keep in mind that there are trade-offs with this sort of thing. 请记住,在这种情况下需要权衡取舍。 Doing this could work really well in some scenarios, not so well in others. 在某些情况下,这样做可能真的很好,而在其他情况下则不太好。 If the DAL is transparently filtering data based on user context, then it could become quite difficult to perform system (non-user) operations or administrative (super-user) operations with the same DAL. 如果DAL基于用户上下文透明地过滤数据,则使用同一DAL执行系统(非用户)操作或管理(超级用户)操作可能会变得非常困难。 It's impossible to say if that's going to be a problem with my current knowledge of your system, this is just a heads-up on issues I've seen come up in the past. 我目前对您的系统的了解是否会引起问题,这是无法确定的,但这只是我过去遇到的问题的提醒。

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

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