I have only recently started working with the MVC approach, so I suppose this is an easy one for you gurus here:
Where do I put access control?
In a view? I don't want to have any logic besides switches and flags in my templates, so that sounds like the least viable option
In the model? Should each business object decide what data it will reveal about itself based on who's asking?
In the controller? That's where I have it now but it makes it hard to keep business rules consistent
Or is there another option?
This will depend on what framework you're using as that and the language will dictate a lot of the tools you have available to you.
From a high level, you should have access security configured at points-of-entry. And you should double-check access security at every level that could be considered autonomous or reused from multiple parts of your application (who knows if security was checked by your co-worker's portal that uses your logic layer? etc.). The other thing to worry about is data security, and that belongs as close to your data as possible (so, yes to your #2 above, but understand that it's separate).
This is akin to the difference between application logic and domain logic, which I'm fond of talking about. If there is any logic that is specific to one particular application (web app compared to a windows service, or whatever) then that logic should be defined in that application only. If some logic crosses the boundary between applications (is reusable between applications) then it qualifies as domain logic and should be defined in your model. Your applications can make use of domain logic, but they should not own it.
For Model (aka data) security, the Model would "control" the access and the Controller would "facilitate" the access. This provides for the reuse of the Model independently of the Controller and minimizes if not negates the general code replication necessary across dissimilar Controllers which use the Model.
For example a Car, a Driver, and a Key. (Model, Controller, API respectively). By virtue of a very small interface (key == API), the Model permits or denies Controller access per API (key fob). Different types of access are permitted (Valet key, Owner Key, Owner FOB). Using the Valet key interface, the Controller will not have access to some of the data/function of the Model such as the glove compartment, the trunk and the gas tank. This is essentially role based access implemented by the Model through identifying and categorizing the Controller with a very small API/command surface area.
This means that the Model can be used by other controllers (car with different drivers) which only need the basic authentication to access the data of the model (functions and compartments of the car).
Related
When using MVC5 I add a domain layer and storage layer using dependency injection for all the business data. But I have always left the ApplicationDbContext in the main MVC application layer project.
I've read a great many posts on SO and see many people recommend moving the ApplicationDbContext out of the MVC project. I'd like to understand why ApplicationDbContext should or should not be moved. Are there any reasons to not move this context?
On the one hand, ApplicationDbContext uses a data model which suggests it should be moved to the storage layer but that will require large DTO's. On the other hand, ApplicationDbContext really relates primarily to application access and I have a separate roles/permissions functionality for the business data anyway. Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?
So I'm confused and before I go to the work to move the ApplicationDbContext to a different layer, I'd like to make sure I'm making a sound and informed decision.
It is not a must, but it is advisable if you are doing DDD and your project tends to grow large.
Although DDD is not about implementation details, DDD asks for a clear separation of concerns. Then you should separate domain logic from infrastructure.
You could achieve that separation in many ways. One way would be to have a single project with folders for Domain, Application and Infrastructure, and have your DbContext reside in the Infrastructure folder. This is suitable for small projects.
In large projects, however, I would recommend you to evaluate the Clean Architecture, which will take this separation to project level.
I'd like to understand why ApplicationDbContext should or should not be moved. Are there any reasons to not move this context?
It can be moved, there's no rule against it. But the tooling will then require you to specify both startup and database projects as parameters, like this:
dotnet ef database update --project <path> --startup-project <path>
But since you're using MVC5, you're probably not using EF Core. In case of EF 6 or lower, you'll be using the Package Manager Console (PMC) to manage migrations and database-updates, which will make your life easier in that regard, since you can mark you MVC project as the Startup Project from the context menu, and select the target project from a dropdown control in the PMC.
Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?
Yes, roles are related to permissions, which are business rules. People probably recommend checking that in the application layer because you need to pull this data from the database, but you could do it like this:
Use the Specification Pattern to represent roles and permissions as an specification in the Domain Layer. But the IRepository interfaces would best be defined in Application Layer, as they represent infrastructure (which will be concretely implemented in the Infrastructure Layer). So you would start the role-checking in the Application Layer by using repositories to retrieve data, but the actual permission validation would be done by an Specification in the Domain Layer.
That would be one way to do it.
Abstract
I am modelling a generic authorization subdomain for my application. The requirements are quite complicated as it needs to cope with multi tenants, hierarchical organisation structure, resource groups, user groups, permissions, user-editable permissions and so on. It's a mixture of RBAC (users assigned to roles, roles having permissions, permissions can execute commands) with claims-based auth.
Problem
When checking for business rule invariants, I have to traverse the permission "graph" to find a permission for a user to execute a command on a resource in an environment. The traversal depth is arbitrary, on multiple dimensions.
I could model this using code, but it would be best represented using a graph database as queries/updates on this aggregate would be faster. Also, it would reduce the complexity of the code itself. But this would require the graph database to be immediately consistent.
Still, I need to use CQRS/ES, and enable a distributed architecture.
So the graph database needs to be
Immediately consistent
And this introduces some drawbacks
When loading events from event-store, we have to reconstruct the graph database each time
Or, we have to introduce some kind of graph database snapshotting
Overhead when communicating with the graph database
But it has advantages
Reduced complexity of performing complex queries
Complex queries are resolved faster than with code
The graph database is perfect for this job
Why this question?
In other aggregates I modelled, I often have a EntityList instance or EntityHierarchy instance. They basically are ordered/hierarchical collection of sub-entities. Their implementation is arbitrary. They can support anything from indexing, key-value pairs, dynamic arrays, etc. As long as they implement the interfaces I declared for them. I often even have methods like findById() or findByName() on those entities (lists). Those methods are similar to methods that could be executed on a database, but they're executed in-memory.
Thus, why not have an implementation of such a list that could be bound to a database? For example, instead of having a TMemoryEntityList, I would have a TMySQLEntityList. In the case at hand, perhaps having an implementation of a TGraphAuthorizationScheme that would live inside a TOrgAuthPolicy aggregate would be desirable. As long as it behaves like a collection and that it's iterable and support the defined interfaces.
I'm building my application with JavaScript on Node.js. There is an in-memory implementation of this called LevelGraph. Maybe I could use that as well. But let's continue.
Proposal
I know that in DDD terms the infrastructure should not leak into the domain. That's what I'm trying to prevent. That's also one of the reasons I asked this question, is that it's the first time I encounter such a technical need, and I am asking people who are used to cope with this kind of problem for some advice.
The interface for the collection is IAuthorizationScheme. The implementation has to support deep traversal, authorization finding, etc. This is the interface I am thinking about implementing by supporting it with a graph database.
Sequence :
1 When a user asks to execute a command I first authenticate him. I find his organisation, and ask the OrgAuthPolicyRepository to load up his organisation's corresponding OrgAuthPolicy.
The OrgAuthPolicyRepository loads the events from the EventStore.
The OrgAuthPolicyRepository creates a new OrgAuthPolicy, with a dependency-injected TGraphAuthorizationScheme instance.
The OrgAuthPolicyRepository applies all previous events to the OrgAuthPolicy, which in turns call queries on the graph database to sync states of the GraphDatabase with the aggregate.
The command handler executes the business rule validation checks. Some of them might include checks with the aggregate's IAuthorizationScheme.
The business rules have been validated, and a domain event is dispatched.
The aggregate handles this event, and applies it to itself. This might include changes to the IAuthorizationScheme.
The eventBus dispatched the event to all listening eventHandlers on the read-side.
Example :
In resume
Is it conceivable/desirable to implement entities using external databases (ex. Graph Database) so that their implementation be easier? If yes, are there examples of such implementation, or guidelines? If not, what are the drawbacks of using such a technique?
To solve your task I would consider the following variants going from top to bottom:
Reduce task complexity by employing security frameworks or identity
management solutions. Some existent out of the box identity management solution might do the job. If it doesn't take a look on the frameworks to help you implement your own. Unfortunately I'm poorly familiar with Node.js world to advice
you any. In Java world that could be Apache Shiro or Spring Security. This could be a good option from both costs and security perspective
Maintain single model instead of CQRS. This eliminates consistency problems (if you will decide to have separate
resources to store your models). From my understanding
permissions should not be changed frequently but they will be accessed
frequently. This means you can live with one model optimised for
reads, avoiding consistency issues and maintaining 2 models. To
track down user behaviour you can implement auditing separately.
From my experience security auditing can require some additional
data which most likely is not in your data model.
Do it with CQRS. And here I would first consider revisit requirements to find a way to accept eventual consistency instead of strong consistency. This opens many options for implementation.
Regarding the question should you use introduce dedicated Graph Database it's impossible to answer without knowledge of your domain, budget, desired system throughput and performance, existent infrastructure, team knowledge and setup etc. You need to estimate costs of the solution with dedicated Graph Database and without it. My filling is that unless permission management is main idea of your project or your project is mature enough (by number of users and R&D capacities) dedicated database is unlikely to pay back it's costs for your task.
To understand what could be benefits of having dedicated Graph Database your existent storage solutions should be taken in opposite. These 2 articles explains pretty well what could be such benefits:
http://neo4j.com/developer/graph-db-vs-nosql/
http://neo4j.com/developer/graph-db-vs-rdbms/
I am quite new to DDD and have come across a scenario that i'm not to sure how to handle.
I have an application that is used to track vehicles. This application is what will be implementing the "core" of the domain for the business i am working for. Not only is this application going to be used, there will be other utility programs that must be created and used in order to help this "core/main" application function.
for example:
there is an windows service needed that will perform configured queries on a database and return results to an external database that my routing application will use. This windows service has the concept of a QuerySettings class that can be created and is then executed by this application.
Question1:
What do you call utility applications like the above described in DDD? ( it definitely isn't the main core of the domain but it's needed in order for the core application to work )
QUestion2:
Is QuerySettings a domain model? if not what is it and where should it be placed within following the onion architecture?
For question1: You may have a look at Bounded context, I think Bounded context contains a group of Domain models that represent concepts in a subdomain(or a core domain). You may need to map or share domain models in different bounded contexts to handle your business, this depends on your bounded context strategy, share-kernal, anti-corruption-layer(to name a few).
For question2: I have little information of how QuerySettings works but in general it is a domain model but in a generic subdomain, not in your vehicle tracking core domain. In core domain's view, it maybe an infrastructure concept.
I am developing an application that displays a list of current work-orders to users. This list is 'live' in that it should automatically update whenever changes are made behind-the-scenes.
I am at the point where I need to implement the synchronization logic to keep the data in the list in-sync. I am abstracting away the actual mechanism driving synchronization (e.g. polling, event-driven, etc.) so we can change approaches as needed but am stuck determining if this logic belongs in the domain layer or data layer.
Should data synchronization as described be 'hidden' in the data layer or is it a domain concern and belongs in that layer?
Not domain layer in my personal expierence. Because it's highly coupled with the ui interface. Do you still need this mechanism if the work-orders list doesn't need to be 'live'? Domain models should be relatively stable (unless the domain changes), not be driven by ui and applications.
If I am developing an application using DDD, where do the infrastrucure and behavior components go? For example, user management, user specific configuration, permissions, application menuing, etc.
These components really have nothing to do with the business requirements being fullfilled by my domain, but they are still required elements of my application. Many of them also require persistance.
It's pretty normal to have non-domain components along with the domain in your project - after all not everything is business domain oriented. Where they belong actually depends on how you structure your solution. In most cases I tend to follow Onion Architecture, so all of my logic is provided by Application Services, regardless if it's domain or non-domain oriented.
Well if you find that your usecases rarely demands information from your core domain joined with application specific, you can probably split that into a separate database. Access this information through Application Service layer, since this layer is suppose to serve your application needs. If that includes user profile persistence etc, that's fine.
But you remember that if you got infrastructural failure and you want to do a rollback with some transaction logs or database backups, you'd probably want all persisted data be roll-backed. So then it's easier to have these domains share a database. Pros and cons - always compromise...
If I know that this application would have minor interaction with it's environment, I would put this in one database and let the application service layer interact with clients.
If I know that there will be several applications/clients I may consider to split database so that Webb application user specifics are stored in separate database. Very hard to say, since I have no overview of all the requirements.
/Magnus