Separation of concerns and authentication - asp.net-mvc

I'm trying to be a Good Developer and separate my concerns out. I've got an ASP.NET MVC project with all my web code, and a DAL project with all the model code.
Sometimes code in the DAL needs to check if the current user is authorized to perform some actions, by checking something like CurrentUser.IsAdmin.
For the web site, the current is derived from the Windows username (from HttpContext.Current.User.Identity), but this is clearly a web concern and shouldn't be coupled to the DAL.
What's the best pattern to loosely couple the authentication? Should the DAL be asking the MVC code for a username, or the MVC be telling the DAL? Are there advantages or disadvantages to one or the other?
Thank you!

Typically I handle the security at the controller level, not at the data level. If you want to handle it at the data level, then I'd use injection to give your DAL either the current user or the means to access who the current user is. In this case it would mean injecting the User object from the Controller when you create the DAL instance. I sometimes do this for auditing, i.e., the current user may be a member of a role that allows access to a modify a user's data. In that case I want to insert the actual user making the change into the audit table. I would avoid using HttpContext.Current -- you should use the properties on the controller instead and inject them rather than having the DAL obtain them from a static object. That will make your DAL much easier to test.
When handling security in the controller you can use the AuthorizeAttribute or custom attributes derived from it to implement your cross-cutting security concerns.

Related

MVC Security Violation - Improperly Controlled Modification of Dynamically-Determined Object Attributes

We are developing an MVC 5 Application and while we ran security scan using Veracode we are getting the below flaw saying
"Improperly Controlled Modification of Dynamically-Determined Object Attributes"
And added this link as reference to fix.
Tried implementing Bind Attribute to my Controllers functions with HTTP Post and the issue is fixed.
So in ASP.NET MVC is it mandatory to use Bind Attribute for all the Post to avoid security violation ?
Or can i ignore this flaw or any other alternative way i can address this as hard coding and maintaining Bind Attributes really gets difficult in real time applications.
Please share your views.
it is not mandatory to use the Bind attribute.
The link which you have posted is basically the dirtiest example they could have came up with. They are directly binding an EF model into the controller, which no real world application would do and I hate Miscrosoft where they show you how easily you can go from DB to Web by applying the dirtiest worst practise patterns without explaining that this is not something you would want to do in real life.
In real life you would create a (View)Model which is tailored to your View. This means the class will ONLY have the properties which you want to accept from the request, therefore you wouldn't really need the Bind attribute in most cases.
EF models are low level classes in your data layer and shouldn't be bound to any controllers IMO.
UPDATE:
Actually on the top of the link they have posted this:
Note It's a common practice to implement the repository pattern in
order to create an abstraction layer between your controller and the
data access layer. To keep these tutorials simple and focused on
teaching how to use the Entity Framework itself, they don't use
repositories. For information about how to implement repositories, see
the ASP.NET Data Access Content Map.
However, this is just talking about the repository pattern, which is a good pattern to abstract your data layer, but the DTO which the repository pattern would return is still too low level for binding to a View.
You should create a model which is tailored to your view and in your controller or service layer you can do the infrastructure mapping between the different layers.

Service layer and project structure in ASP.NET MVC 5 without repository and UoW patterns

I'd like to create a good app in ASP.NET MVC 5 using EF 6 Code first concept. I want it to be well-designed i.e. having generally speaking: Presentation, Logic and Data layers separated. I want it to be testable :)
Here's my idea and some issues related with creating application
Presentation layer: It's my whole MVC - view models(not models), views, controllers
I believe that's validation should be done somewhere else (in my opinion - it's a part of business logic) but it's quite convenient to use attributes from the DataAnnotations namespace in ViewModelds and check validation in controller.
Logic layer: Services - classes with their interfaces to rule business logic.
I put there functions like: AddNewPerson(PersonViewModel Person), SendMessageToPerson(...).
They will use DB context to make their actions (there's a chance that not all of them will be relying on context). There's a direct connection between service and db - I mean the service class have reference do context.
Where should I do mapping between ViewModel and Model? I've heard that service is a bad place for it - so maybe in controllers. I've heard that service should do the work related with db exclusively.
Is it right? Is my picture of service layer is good?
Data layer: I've read about Repository and UoW patterns a lot. There're some articles which suggest that EF6 implements these two things. I don't want to create extra code if there's no need for such a behavior. The question is: am i right to assume that i don't need them?
Here's my flow:
View<->Controllers(using ViewModels)<->Services(using Models)<->DB.
**I'm gonna use DI in my project.
What do you think about my project structure?
There is no reason to use a Unit of Work pattern with Entity Framework if you have no need to create a generic data access mechanism. You would only do this if you were:
using a data access technology that did not natively support a Unit of work pattern (EF does)
Wanted to be able to swap out data providers sometime in the future.. however, this is not as easy as it might seem as it's very hard NOT to introduce dependencies on specific data technologies even when using an Unit of Work (maybe even BECAUSE you are)... or
You need to have a way of unifying disparate data sources into an atomic transaction.
If none of those are the case, you most likely don't need a custom Unit of Work. A Repository, on the other hand can be useful... but with EF6 many of the benefits of a Repository are also available since EF6 provides mocking interfaces for testing. Regardless, stay away from a generic repository unless it's simply an implementation detail of your concrete repositories. Exposing generic repositories to your other layers is a huge abstraction leak...
I always use a Repository/Service/Façade pattern though to create a separation between my data and business (and UI and business for that matter) layers. It provides a convenient way to mock without having to mock your data access itself and it decouples your logic from the specific that are introduced by the Linq layer used by EF (Linq is relatively generic, but there are things that are specific to EF), a façade/repository/server interface decouples that).
In general, you're on the right path... However, let me point out that using Data Attributes on your view models is a good thing. This centralizes your validation on your model, rather than making you put validation logic all over the place.
You're correct that you need validation in your business logic as well, but your mistake is the assumption that you should only have it on the business logic. You need validation at all layers of your application.. And in particular, your UI validation may have different requirements than your business logic validation.
For instance, you may implement creating a new account as a multi-step wizard in your UI, this would require different validation than your business layer because each step has only a subset of the validation of the total object. Or you might require that your mobile interface has different validation requirements from your web site (one might use a captcha, while the other might use a touch based human validation for instance).
Either way, it's important to keep in mind that validation is important both at the client, server, and various layers...
Ok, let’s clarify a few things...
The notion of ViewModel (or the actual wording of ViewModel) is something introduced by Microsoft Martin Fowler. In fact, a ViewModel is nothing more than a simple class.
In reality, your Views are strongly typed to classes. Period. To avoid confusion, the wording ViewModel came up to help people understand that
“this class, will be used by your View”
hence why we call them ViewModel.
In addition, although many books, articles and examples use the word ViewModel, let's not forget that it's nothing more than just a Model.
In fact, did you ever noticed why there is a Models folder inside an MVC application and not a ViewModels folder?
Also, ever noticed how at the top of a View you have #model directive and not # viewmodel directive?
That's because everything could be a model.
By the way, for clarity, you are more than welcomed to delete (or rename) the Models folder and create a new one called ViewModels if that helps.
Regardless of what you do, you’ll ultimately call #model and not #viewmodel at the top of your pages.
Another similar example would be DTO classes. DTO classes are nothing more than regular classes but they are suffixed with DTO to help people (programmers) differentiate between all the other classes (including View Models).
In a recent project I’ve worked on, that notion wasn’t fully grasped by the team so instead of having their Views strongly typed to Models, they would have their Views strongly typed to DTO classes. In theory and in practice everything was working but they soon found out that they had properties such as IsVisible inside their DTO’s when in fact; these kind of properties should belongs to your ViewModel classes since they are used for UI logic.
So far, I haven’t answered your question but I do have a similar post regarding a quick architecture. You can read the post here
Another thing I’d like to point out is that if and only if your Service Layer plans on servicing other things such as a Winform application, Mobile web site, etc...then your Service Layer should not be receiving ViewModels.
Your Service Layer should not have the notion of what is a ViewModel. It should only accept, receive, send, etc... POCO classes.
This means that from your Controller, inside your ActionResult, once the ModelState is Valid, you need to transform your ViewModel into a POCO which in turn, will be sent to the method inside your Service Layer.
In other words, I’d use/install the Automapper nugget package and create some extension methods that would convert a ViewModel into a POCO and vice-versa (POCO into a ViewModel).
This way, your AddNewPerson() method would receive a Person object for its parameter instead of receiving a PersonViewModel parameter.
Remember, this is only valid if and only if your Service Layer plans on servicing other things...
If that's not the case, then feel free to have your Service Layer receive, send, add, etc...ViewModels instead of POCOs. This is up to you and your team.
Remember, there are many ways to skin a cat.
Hope this helps.

ASP.NET MVC3 - 3 Tier design - Transaction control and business layer design questions

I am designing an ASP.NET MVC3 application, and I would like to have a clear separation of concerns in a 3 layer architecture. I am using Fluent NHibernate as the ORM, the Repository pattern to work with the entities mapped by NHibernate. I would like to add a proper business layer with a Unit Of Work pattern, keeping the MVC portion only for presentation (by using ViewModels that map to the nHibernate entities through the business layer). This article describes the combined 3-tier and MVC architectures nicely.
According to this MVC + unit of work + repository article I don't see a clear distinction of a business layer. The unit of work class presents strongly typed getters for each repository type, which looks appropriate for a business layer. However, it exposes a Save method, which I think would translate to BeginTransaction and CommitTransaction methods with nHibernate. This begs some questions:
1) Is exposing transaction control to MVC a good idea? At which stage should transaction control happen? Seems to me that MVC should not be responsible for transactions, but how to avoid that?
2) Should there be some automatic way to handle transactions? This ActionFilter implementation is semi-automatic but the transaction control is clearly in the MVC section, which is not the business layer.
3) Is the UnitOfWork class the same as a business layer class?
- if so, does that mean that we can add custom business logic methods into it?
- if not, do we wrap the unit of work with some other class(es) that contains business logic methods?
I appreciate any ideas or examples. Thank you.
First of all I want to clarify a little mis-conception about the business layer, as you want to use the Repository pattern and your setup is a candidate to Domain Driven Design, then the business layer is actually [the Domain Model (Entities and Value Objects where you design your business logic in an object oriented fashion in entities and objects) , and Application Layer to co-ordinate transactions and operations and commands to the domain layer], so the suggested architecture would be something like this:
Presentation (MVC) [OrderView, OrderPresentationModel, OrderController]
Application [OrderService]
Use UnitOfWork (Transactions) and Repositories to execute domain logic
DTOs [OrderDTO, CustomerDTO]
Domain
Entities and Value Objects [Order, Customer, LineItem, Address]
Repository Interfaces [IOrderRepository, ICustomerRepository]
(optional) Unit of Work Interface [IUnitOfWork]
Infrastructure.DataAccess (Using ORM or Data Access Technology)
Repositories [OrderRepository, CustomerRepository]
(optional) Unit of Work [UnitOfWork]
Infrastructure.Common
Logging
Utilities
Example scenario:
[Presentation] OrderController:
_orderService.CreateOrder(OrderDTO);
[Application] OrderService:
_unitOfWork.BeginTransaction();
var customer = _customerRepository.GetById(orderDTO.CustomerId);
var order = new Order() { Customer=customer, Price=orderDTO.Price, ... }
_orderRepository.Add(order);
_unitOfWork.Commit();
About your questions:
1) Is exposing transaction control to MVC a good idea? At which stage should transaction control happen? Seems to me that MVC should not be responsible for transactions, but how to avoid that?
No, i would prefer to separate it in application layer in order to make design flexible to support different presentations.
2) Should there be some automatic way to handle transactions? This ActionFilter implementation is semi-automatic but the transaction control is clearly in the MVC section, which is not the business layer.
Use transactions in application layer.
3) Is the UnitOfWork class the same as a business layer class?
- if so, does that mean that we can add custom business logic methods into it?
- if not, do we wrap the unit of work with some other class(es) that contains business logic methods?
No, it is just a way to group tasks into transactions.
The business logic actually is encapsulated in entities and if the logic is not related to one entity it should be implemented in domain services [TransferService.Transfer(account1, account2, amount)], for co-ordinations, accessing repositories, and transactions the application layer is the place.
Have you looked into the S#arp Architecture? It has built-in MVC Transaction handling, using Action Filters.
I'm usually a layering purist, so I wasn't psyched about letting MVC open the view, but I've come to like it.
There are pro's and con's, but here are some advantages of the Open Session In View pattern.:
Lazy Loading -- It will simplify your data access if you can rely on lazy loading in your MVC Views. No need to explicitly join to all tables required by the view. (Be sure to avoid the N+1 problem by joining explicitly when lazy loading would generate a ridiculous number of queries. Data grids are a common culprit here.)
Simpler BSO layer -- your BSO doesn't need to worry about sessions. It's assumed that you're already working in the context of a session.
If you don't want to go with S#arp, you can still implement Open-Session-In-View yourself with only a few lines of code in an ActionFilter. On the Action Executing method, open the session. In the action executed method, commit, close, and dispose. This is what we're doing on my project and it has worked well for us.
The problem you have with any web based app is that there has to be some coupling of the UI to the buisness layer due to the need to manage object lifetimes by the HTTP Session. In a typical desktop application you don't have to worry about sessions, so this makes it easy to move all transaction handling further down the chain.
Consider where you want to reuse the same logic in three apps, a Web Site, a Web Service, and a Desktop application. Without exposing the transaction handling to the presentation tier, there's no good way to deal with transaction commits, beacuse the business layer is ignorant of how long the objects will exist.
So your choice is, either make sure you commit everything in every method of your buisness objects, or expose the transaction to the UI.
A third alternative would be to build a fairly complex session management controller, which I don't even want to think about... The session management controller could be coupled to the ui and the business logic, seperating them to some extent.. But that would require a lot more analysis.

Can a pure DDD approach be used with NHibernate?

I've been reading up on DDD a little bit, and I am confused how this would fit in when using an ORM like NHibernate.
Right now I have a .NET MVC application with fairly "fat" controllers, and I'm trying to figure out how best to fix that. Moving this business logic into the model layer would be the best way to do this, but I am unsure how one would do that.
My application is set up so that NHibernate's session is managed by an HttpModule (gets session / transaction out of my way), which is used by repositories that return the entity objects (Think S#arp arch... turns out a really duplicated a lot of their functionality in this). These repositories are used by DataServices, which right now are just wrappers around the Repositories (one-to-one mapping between them, e.g. UserDataService takes a UserRepository, or actually a Repository). These DataServices right now only ensure that data annotations decorating the entity classes are checked when saving / updating.
In this way, my entities are really just data objects, but do not contain any real logic. While I could put some things in the entity classes (e.g. an "Approve" method), when that action needs to do something like sending an e-mail, or touching other non-related objects, or, for instance, checking to see if there are any users that have the same e-mail before approving, etc., then the entity would need access to other repositories, etc. Injecting these with an IoC wouldn't work with NHibernate, so you'd have to use a factory pattern I'm assuming to get these. I don't see how you would mock those in tests though.
So the next most logical way to do it, I would think, would be to essentially have a service per controller, and extract all of the work being done in the controller currently into methods in each service. I would think that this is breaking with the DDD idea though, as the logic is now no longer contained in the actual model objects.
The other way of looking at that I guess is that each of those services forms a single model with the data object that it works against (Separation of data storage fields and the logic that operates on it), but I just wanted to see what others are doing to solve the "fat controller" issue with DDD while using an ORM like NHibernate that works by returning populated data objects, and the repository model.
Updated
I guess my problem is how I'm looking at this: NHibernate seems to put business objects (entities) at the bottom of the stack, which repositories then act on. The repositories are used by services which may use multiple repositories and other services (email, file access) to do things. I.e: App > Services > Repositories > Business Objects
The pure DDD approach I'm reading about seems to reflect an Active Record bias, where the CRUD functions exist in the business objects (This I call User.Delete directly instead of Repository.Delete from a service), and the actual business object handles the logic of things that need to be done in this instance (Like emailing the user, and deleting files belonging to the user, etc.). I.e. App > (Services) > Business Objects > Repositories
With NHibernate, it seems I would be better off using the first approach given the way NHibernate functions, and I am looking for confirmation on my logic. Or if I'm just confused, some clarification on how this layered approach is supposed to work. My understanding is that if I have an "Approve" method that updates the User model, persists it, and lets say, emails a few people, that this method should go on the User entity object, but to allow for proper IoC so I can inject the messagingService, I need to do this in my service layer instead of on the User object.
From a "multiple UI" point of view this makes sense, as the logic to do things is taken out of my UI layer (MVC), and put into these services... but I'm essentially just factoring the logic out to another class instead of doing it directly in the controller, and if I am not ever going to have any other UI's involved, then I've just traded a "fat controller" for a "fat service", since the service is essentially going to encapsulate a method per controller action to do it's work.
DDD does not have an Active Record slant. Delete is not a method that should be on an Entity (like User) in DDD.
NHibernate does support a DDD approach very well, because of how completely divorced it remains from your entity classes.
when that action needs to do something
like sending an e-mail, or touching
other non-related objects
One piece of the puzzle it seems you are missing is Domain Events. A domain entity shouldn't send an email directly. It should raise an event in the Domain that some significant event has happened. Implement a class whose purpose is to send the email when the event occurs, and register it to listen for the Domain Event.
or, for instance, checking to see if
there are any users that have the same
e-mail before approving
This should probably be checked before submitting the call to "approve," rather than in the function that does the approving. Push the decision up a level in calling code.
So the next most logical way to do it,
I would think, would be to essentially
have a service per controller
This can work, if it's done with the understanding that the service is an entry point for the client. The service's purpose here is to take in parameters in a DTO from the front end/client and translate that into method calls against an entity in order to perform the desired funcitonality.
The only limitations NHibernate creates for classes is all methods/properties must be virtual and a class must have a default constructor (can be internal or protected). Otherwise, it does not [edit] interfere with object structure and can map to pretty complex models.
The short answer to you question is yes, in fact, I find NHibernate enhances DDD - you can focus on developing (and altering) your domain model with a code first approach, then easily retro-fit persistence later using NHibernate.
As you build out your domain model following DDD, I would expect that much of the business logic that's found you way into you MVC controllers should probably reside in your domain objects. In my first attempt at using ASP.NET MVC I quickly found myself in the same position as yourself - fat controllers and an anemic domain model.
To avoid this, I'm now following the approach of keeping a rich domain model that implements the business logic and using MVC's model as essentially simple data objects used by my views. This simplifies my controllers - they interact with my domain model and provide simple data objects (from the MVC model) to the views.
Updated
The pure DDD approach I'm reading about seems to reflect an Active Record bias...
To me the active record pattern means entities are aware of their persistance mechanism and an entity maps directly to a database table record. This is one way of using NHibernate e.g. see Castle Active Record, however, I find this pollutes domain enitities with knowledge of their persistence mechanism. Instead, typically, I'll have a repository per aggregate root in my domain model which implements an abstract repository. The abstract repository provides basic CRUD methods such as:
public IList<TEntity> GetAll()
public TEntity GetById(int id)
public void SaveOrUpdate(TEntity entity)
public void Delete(TEntity entity)
.. which my concrete repositories can supplement/extend.
See this post on The NHibernate FAQ which I've based a lot of my stuff on. Also remember, NHibernate (depending on how you set up your mappings) will allow you to de-persist a complete object graph, i.e. your aggregate root plus all the objects hanging off it and once you've finished working with it, can cascade saves through you entire object graph, this certainly isn't active record.
...since the service is essentially going to encapsulate a method per controller action to do it's work...
I still think you should consider what functionality that you currently have in your controllers should, more logically, be implemented within your domain objects. e.g. in your approval example, I think it would be sensible for an entity to expose an approve method which does whatever it needs to do to within the entity and if, as in your example, needs to send emails, delegate this to a service. Services should be reserved for cross-cutting concerns. Then, once you've finished working with your domain objects, pass them back to your repository to persist changes.
A couple of books I've found useful on these topics are:
Domain-Driven Design by Eric Evans
Applying Domain-Driven Design and Patterns by Jimmy Nilsson

ASP.NET MVC2 and MemberShipProvider: How well do they go together?

I have an existing ASP.NET application with lots of users and a large database. Now I want to have it in MVC 2. I do not want to migrate, I do it more or less from scratch. The database I want to keep and not touch too much.
I already have my database tables and I also want to keep my LINQ to SQL-Layer. I didn't use a MembershipProvider in my current implementation (in ASP.NET 1.0 that wasn't strongly supported).
So, either I write my own Membershipprovider to meet the needs of my database and app or I don't use the membershipprovider at all.
I'd like to understand the consequences if I don't use the membership provider. What is linked to that? I understand that in ASP.NET the Login-Controls are linked to the provider. The AccountModel which is automatically generated with MVC2 could easily be changed to support my existing logic.
What happens when a user is identified by a an AuthCookie? Does MVC use the MembershipProvider then?
Am I overlooking something?
I have the same questions regarding RoleProvider.
Input is greatly appreciated.
With MVC it is simple to bypass the Membership and Role provider framework altogether. Sometimes it is easier to do this than to implement custom Membership/Role providers, in particular if your authn/authz model doesn't quite fit the mold of those providers.
First, you should realize that you don't need to write everything from scratch, you can use the core Forms authentication API, which can be used independently of the Membership/Role provider framework:
FormsAuthentication.SetAuthCookie -
Call this after user has been
authenticated, specify the user name
Request.IsAuthenticated - Returns
true if SetAuthCookie was called
HttpContext.Current.User.Identity.Name - Returns the user name specified in the call to SetAuthCookie
So here is what you do in MVC to bypass the Membership/Role provider:
Authentication: In your
controller, authenticate the user
using your custom logic.If
successful, call
FormsAuthentication.SetAuthCookie
with the user name.
Authorization: Create a custom
authorize attribute (deriving from
AuthorizeAttribute) . In the
AuthorizeCore override, implement
your custom authorization logic,
taking the user in
HttpContext.Current.User.Identity.Name
and the roles defined in the Roles
property of the AuthorizeAttribute base class.
Note you can also define properties on your custom
authorization attribute and use that in your authorization logic.
For example you can define a property representing roles as enumerated values
specific to your app, instead of using the Roles property which is just a string.
Affix your controllers and actions with your
custom authorize attribute,
instead of the default Authorize
attribute.
Although you most likely can do this without a custom membership provider, I'm not sure that you save that much effort. Until I read this blog post I thought implementing one was hard, but it's really not. Basically you do this:
Create a class that inherits System.Web.Security.MembershipProvider.
MembershipProvider is an abstract class, so you are readily shown what methods need to be implemented.
The names are pretty self explanatory, so you can probably more or less copy your existing logic.
You might end up doing more than you need with this approach - but on the other hand, anything you might want to use now or in the future that requires a membership provider will already have its needs met.
The source of the SQLMembershipProvider is available here http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx. Take that as a base.
It looks a bit much at first, but you only have to implement the methods you need.
Yes the AuthCookie is used. Yes its a good idea to use the MembershipProvider, because it is well known by other developers.
There are thinks I dont like about it: For example It is not possible to have a transaction that spans the creation of a user by the membershipsystem and some other data in your own datbase. But still it works well.

Resources