I went through different Architecture books such as this one: Microsoft Application Architecture Guide, 2nd Edition
And now I am building a new n-tier website with ASP.Net MVC as Presentation layer.
My question is, If I will use the asp.net Identity, on which tier/layer should I implement the user authentication?
I thought it should be in the Cross Cutting Concerns, because I will need to check if user is authorized or authenticated to access some functions plus I may use the user name on many tiers, such as the Business, Services and Presentation layer.
and also thought it will be better to put it in the Presentation layer specially because the presentation layer is MVC and it will be easy to deal with ASP Identity from there and will allow me to user [Authorize] and [AllowAnonymous] easily.
I know that this question answer depend on many other factors but I am trying here to achieve the most best practice, so need to get your point of view and discuss it.
There are quite a few similar questions here on stackoverflow, and just many answers. Here my view on the matter.
You have to separate the abstraction from the implementation.
The abstraction (an interface) defines the questions you need to able to ask to the authentication service. This interface is used by all other parts of your application that are going to use your authentication service. This means that your abstraction must be defined somewhere that can be referenced by the other parts of your application. My suggestion would be to put this in the business layer, since the methods in the interface (in other words the 'questions that you want to ask to the service') are usually business related. Another suggestion is to put it in a Core layer (if you have one).
That leaves us with the implementation of the interface. I would implement this in the easiest place that you can that works. Can you do it in the business layer, fine. Do you need to use the identity classes from MVC, good too, place it there. It doesn't really matter where you put it, since it isn't used directly.
Of course, to make this all work you do need to use a little Dependency Injection, to register your implementation for the interface.
I have found that this is usually a pretty straightforward answer if you separate the concern of authentication from authorization. Authentication always ends up having to sit in front of presentation. It's a layer in front of the presentation layer. It really has to be.
After authentication occurs, passing that authenticated identity down into the other layers is just another model object, and should be treated as such. Binding authentication/authorization to all the different layers as a cross cutting concern makes your code much harder to reuse in different contexts. Also makes it much harder to test.
Related
I'm aware that in model-view-controller, the Model is the class part.
If I have a User class and instantiate an object, the object must refer to a single user from the database.
So I'll have the CRUD methods on the user, for that specific user.
But if I need a function to run a SELECT * FROM Users, should I create a function within the User class? Or a function in a helper file? Or in the controller? Where should it go, in order to respect the MVC pattern?
I mean, it makes no sense to instantiate a User object just to run a function to display the Users table.
I'm not sure if this will raise "primarily opinion based" flags. I just don't know where those functions should go. If you guys consider the question worth closing, it's ok. But tell me in the comments in which stack community I should ask this.
Back up a bit. Let's go foundational for a moment.
In the MVC pattern
The model is your state (in simple terms), meaning a representation of the data important to the business functionality you are working with
The view is a way of presenting the state to the user (NOTE user here could be another system, as you can use MVC patterns for service endpoints)
The controller ensures the model gets to the view and back out of the view
In a system designed with good separation of state, business functions are not present in the model, the view or the controller. You segregate business functionality into its own class library. Why? You never know when the application will require a mobile (native, not web) implementation or a desktop implementation or maybe even become part of a windows service.
As for getting at data, proper separation of concerns states the data access is separate not only from the model, view and controller, but also from the business functionality. This is why DALs are created.
Before going on, let's go to your questions.
should I create a function within the User class? This is an "active record" pattern, which is largely deprecated today, as it closely couples behavior and state. I am sure there are still some instances where it applies, but I would not use it.
Or a function in a helper file? Better option, as you can separate it out. But I am not fond of "everything in a single project" approach, personally.
Or in the controller? Never, despite Scott Gu's first MVC examples where he put LINQ to SQL (another groan?) in the controller.
Where should it go, in order to respect the MVC pattern?
Here is my suggestion:
Create a DAL project to access the data. One possible pattern that works nicely here is the repository pattern. If you utilize the same data type for your keys in all/most tables, you can create a generic repository and then derive individual versions for specific data. Okay, so this one is really old, but looking over it, it still has the high level concepts (https://gregorybeamer.wordpress.com/2010/08/10/generics-on-the-data-access-layer)
Create a core project for the business logic, if needed. I do this every time, as it allows me to test the ideas on the DAL through unit tests. Yes, I can test directly in the MVC project (and do), but I like a clean separation as you rarely find 0% business rules in a solution.
Have the core pull the data from the DAL project and the MVC project use the core project. Nice flow. Easy to unit test. etc.
If you want this in a single project, then separate out the bits into different folders so you can make individual projects, if needed, in the future.
For the love of all things good and holy, don't use the repository pattern. #GregoryABeamer has a great answer in all respects, except recommending you create repository instances to access your entities. Your ORM (most likely Entity Framework) covers this, and completely replaces the concepts of repositories and unit of work.
Simply, if you need something from your database, hit your ORM directly in your controller. If you prefer, you can still add a level of abstraction to hide the use of the ORM itself, such that you could more easily switch out the data access with another ORM, Web Api, etc. Just don't do a traditional unit of work with tens or hundreds of repository instances. If you're interested, you can read a series of posts I wrote about that on my blog. I use the term "repository" with my approach, but mostly just to contrast with the typical "generic" repository approach you find scattered all over the interwebs.
I'd use some kind of 'Repository' layer. Then, my controller calls the UserRepository GetAll method and sends the data to View layer.
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.
This may sound like a stupid or unconstructive question but I'm a fan of not creating so many layers to reduce the amount of code that has to be written and maintained. In a classic scenario, the application logic would be in one class which calls the business layer. However, if the application logic is simple enough, would it be a crime if I were to put application logic in view models? In my case, this would entail calling the business layer in my view models.
yes, it would be a crime and completely destroy the mvc nature of... mvc.
if you have to, put application logic in your controller.
Surely it is not a crime. But it is good to understand why the Application Logic is "Normally" (what is normal) separated from the User Interface layer. The most important reason that is usually given for this separation is the ability to re-use the application logic when you application gets another User Interface implementation. This can be another technology, or another deployment model. Also for maintenance and readability this is often a best practice.
The fact that you are talking about a viewmodel probably means that you are creating a controller class that has no dependency on the view, according to MVC. This is already a separation in some sense from your user interface.
So my opinion: If you have the need / requirement / wish to modernize your user interface in the future or have multiple user interfaces target the same application logic, put some effort in a separate application logic component. Otherwise, you are not commiting a crime by implementing your application logic in your controller.
I'm having some trouble with deciding on a solution for my mvc application.
Background.
We have an EF model which we perform operations on via WCF Services (not data services).
I have an MVC application which has a number of Repositories that talk directly to the Services and return WCF types back to a controller which is calling the repository method, a type called for example WCFUserEntity (it's not actually prefixed with WCF).
Inside the controller I plan to automap the WCFUserEntity to a ViewModel entity.
What is bugging me about this solution is that because i'm returning WCFUserEntity to the controller I have to have a reference to the WebService proxy in my controller which doesn't sit well with me, i'd like my controllers to know nothing of where the repository has got the data from. So another option for me is to do the automapping inside of the repository and return the ViewModel entity to the controller, i can't find much around which supports this idea though, so really what i'm looking for is validation of this 2nd solution or help with a 3rd.
thanks, Dom
You may want to consider a third option.
The use of ViewModelBuilders.
in your controller they would work like this:
var myViewModel = myViewModelBuilder.WithX().WithY().Build();
WithX and WithY would be methods that would add stuff to your viewmodel internally (within the builder, for example WithCountriesList() if you want to add a dropdown showing the countries in your view) and the Build method would return the internal viewmodel after adding all the bits with the WithXXX methods. This is so because most of the time you may want to add lists for dropdowns and things that are not part of your original model (your userEntity in this case).
This way, your controller doesn't know anything about how to build the viewmodel, your repository is also agnostic of viewmodels. All the work is done in the Builder. On the downside, you need to create a ViewModelBuilder for each ViewModel.
I hope this helps.
How I would approach this might require some architecture changes, but I would suggest you approach your WCF API to return ViewModels instead of entities.
For starters, think about bandwidth issues (which would be an issue if you are hosting the WCF in Azure or the cloud). If your ViewModel is only using a few specific properties, why waste the bandwidth returning the other data? In high traffic scenarios, this could cause a waste of traffic that could end up costing money. For example, if your view is only display a user and his questions, there's no reason to send his email, answers, point count, etc.. over the wire.
Another issue to think about is eager loading. By having the WCF service return a ViewModel, you know you have all the data (even when it pertains to related entities) required from the view in one trip to the WCF service. You do not need to get the WCFUserEntity and then ask WCF for WCFDocumentEntities that are related to that specific user.
Finally, if your WCF API is built around ViewModels then you have a MUCH clearer understanding of the business processes involved. You know that this specific request (and view in the system) will give you this specific information, and if you need different information for a different view then you know that it's a completely different business request that has different business requirements. Using stack overflow as an example, it makes it trivial to see that this business process is asking for the current user with his related questions, while this business process is requesting the current user with his related answers.
Using ViewModels in your data retrieval WCF API means that your frontend layers do not necessarily know where the data came from, it just knows that it called a business process and got the data it needs. As far as it knows the data layer connected to the database directly instead of WCF.
Edit:
After re-reading, this actually looks like your 3rd option. Most research on the net don't talk about this option, and I don't know why, but after having some similar frustrations you are having (plus others listed in this post) this is the way I have gone with my business layer. It makes more sense and is actually (imho) easier to manage.
In my pet project I want to have a user system with the following requirements:
It needs to work with Db4o as a persistance model
I want to use DI (by means of Turbine) to deliver the needed dependencies to my user model
It needs to be easy to plug in to asp.net-mvc
It needs to be testable without much hassle
It needs to support anonymous users much like SO does
I want Authentication and Authorization separated (the first can live without the second)
It needs to be safe
I'm aware I'm putting a few technologies before functionalities here, but as it is a pet project and I want to learn some new stuff I think it is reasonable to include them as requirements.
Halfway in rolling my own I realized I am probably suffering some NIH syndrome.
As I don't really like how needlessly complex the existing user framework in asp.net is, it is actually mostly only all the more complicated stuff regarding security that's now giving me some doubts.
Would it be defendable to go on and roll my own? If not how would you go about fulfilling all the above requirements with the existing IPrinciple based framework?
It sounds to me like what you want to do is roll your own Custom .NET Membership Provider.
It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above).
Direct from MSDN...
Implementing a Membership Provider
I think you recognize where the thin parts in your consideration are: namely in that you've included how to do what you're doing as motive in why you're doing it and the NIH (funny: I'd never seen that before) issue.
Putting those aside, your provider is something that you could potentially reuse and it may simplify some of your future efforts. It should also serve to familiarize you further with the issue. As long as you understand the ASP.NET framework so you can work with it too if you need to (and aren't specialized such that you don't know what you're doing if you're not using your tool) then I believe you've already crafted your defense.
As DOK mentioned, be cautious that you're not rolling your own here to avoid a larger task at hand in whatever your other functionality is. Don't let this be a distraction: it should be something your application really needs. If it's not, then I'd lean towards focusing on your software's core mission instead.
If you go ahead and create your own custom solution, you will have a better idea of how difficult it is and what features you want. This will help you to evaluate off-the-shelf solutions for future projects.
OTOH, spending time developing functionality that is already readily available means you won't be spending that time working on the major functionality of your project. Unless authentication and authorization are a major component of your project, you might consider investing your time, and expanding your knowledge, in another area.
I too am working on a pet Project using ASP.net MVC and db4o and did the same thing, so you're at least not alone in going down that route :). One of the biggest reasons for me to start playing around with db4o as persistence layer is that especially authorization on field level (i.e I'm allowed to see Person A's first name but not Person B's first name) is though to achieve if you're forced into complex SQL statements and an anemic domain model.
Since I had complex authorization needs that needed to be persisted (and synchronized) in both db4o and Solr indexes I started working on rolling out my own, but only because I knew up front it was one of the key features of my pet project that I wanted 100% control over.
Now I might still use the .Net Membership provider for authentication but not (solely) for authorization of objects but only after i POC'd my authorization needs using my own.