Transparent authorization reliability - security

I need a gear for custom authorization in business logic classes. It has to be permissions based system, but I can not decide how to apply authorization rules to methods.
My first thought was to apply custom attributes to method
[NeedPermission("Users", PermissionLevel.Read)]
public IList<User> GetAllUsers()
{
// some code goes here
}
My business logic class has interface, so I can use, for example, Unity Interception behavior and check in runtime if current user has required permissions. And throw an exception if he has not.
But now I'm concerned about reliability of this method.
Usually the reference to business logic class injected by unity container. So there is no problem because it is configured to apply interface interception mechanism.
But what if some developer will instantiate my business logic class directly? Then no interception will be applied and he will be able to call any method even if current user has not permissions to make some actions or even he is not authenticated.
Also somebody can change unity container configuration, turn off Interception extension completly. Again my authorization system will not work.
I saw ASP .NET MVC is using similar mechanism for authorization. Authorization rule is applied only when request came by standard way (IController.Execute). I think this is not a problem in this case because end user of controller (web user) has no way to access controller class directly.
In my case end user of business logic is a programmer who develops front end and he can intentionally or unintentionally screw things - create instance of business logic class and call any methods.
What can you suggest me? How do you deal with this kind of problems?
Thank you.

The .NET Framework supports a mechanism for declarative permission verifications that does not depend on Unity interception or other "external" AOP. In order to take advantage of this, your attribute must inherit from System.Security.Permissions.CodeAccessSecurityAttribute. The System.Security.Permissions.PrincipalPermissionAttribute that is included in the BCL is an example of using this mechanism to evaluate user permissions. If it does not suit your needs, there's nothing stopping you from creating your own attribute that does.

If your constructors are internal and your objects instantiated from a factory, a developper won't be able to bypass your security by error.
If someone really, really wants to create your objets without the security, he could still do it using reflection, but this would have be pretty intentional to do so.

Related

CQRS and cross cutting concerns like ABAC for authorization reasons

Let's assume a monolithic web service. The architectural design is based on the DDD and divides the domain into sub-domains. These are structured according to the CQRS pattern. If a request arrives via the presentation layer, in this case a RESTful interface, the controller generates a corresponding command and executes it via the command bus.
So far so good. The problem now is that certain commands may only be executed by certain users, so access control must take place. In a three-layer architecture, this can be solved relatively easily using ABAC. However, to be able to use ABAC, the domain resource must be loaded and known. The authentication is taken over by the respective technology of the presentation layer and the authenticated user is stored in the request. For example, JWT Bearer Tokens using Passport.js for the RESTful interface.
Approach #1: Access Control as part of the command handler
Since the command handler has access to the repository and the aggregate has to be loaded from the database anyway in order to execute the command, my first approach was to transfer access control to the command handler based on ABAC. In case of a successful execution it returns nothing as usual, if access is denied an exception is thrown.
// change-last-name.handler.ts
async execute(command: ChangeUserLastNameCommand): Promise<void> {
const user = await this._userRepository.findByUsername(command.username);
if (!user) {
throw new DataNotFoundException('Resource not found');
}
const authenticatedUser = null; // Get authenticated user from somewhere
// Handle ABAC
if(authenticatedUser.username !== user.username) {
throw new Error();
}
user.changeLastName(command.lastName);
await this._userRepository.save(user);
user.commit();
}
However, this approach seems very unclean to me. Problem: In my opinion, access control shouldn't be the responsibility of a single command handler, should it? Especially since it is difficult to get the authenticated user or the request, containing the authenticated user, at this level. The command handler should work for all possible technologies of the presentation layer (e.g. gRPC, RESTful, WebSockets, etc.).
Approach #2: Access control as part of the presentation layer or using AOP
A clean approach for me is to take the access control from the handler and carry it out before executing the command. Either by calling it up manually in the presentation layer, for example by using an AccessControlService which implements the business security rules, or by non-invasive programming using AOP, whereby the aspect could also use the AccessControlService.
The problem here is that the presentation layer does not have any attributes of the aggregate. For ABAC, the aggregate would first have to be loaded using the query bus. An ABAC could then be carried out in the presentation layer, for example in the RESTful controller.
That's basically a good approach for me. The access control is the responsibility of the presentation layer, or if necessary an aspect (AOP), and the business logic (domain + CQRS) are decoupled. Problem: The main problem here is that redundancies can arise from the database point of view. For the ABAC, the aggregate must be preloaded via query in order to be able to decide whether the command may be executed. If the command is allowed to be executed, it can happen that it loads exactly the same aggregate from the database again, this time simply to make the change, even though the aggregate has already been loaded shortly before.
Question: Any suggestions or suggestions for improvement? I tried to find what I was looking for in the literature, which was not very informative. I came across the following Security in Domain-Driven Design by Michiel Uithol, which gives a good overview but did not answer my problems. How do I address security concerns in a CQRS architecture? Or are the redundant database access negligible and I actually already have the solution?
I would handle authentication and the overall authorization in the infrastructure, before it reaches the command handlers, because it is a separate concern.
It is also important to handle authentication separately from authorization, because there are separate concerns. It can become pretty messy if you handle authentication and authorization at the same time.
Then you I would do final authorization in the handler (if needed), for example if you have a command AddProductToCart, then I would make sure that the user who initially created the cart-aggreagate is the same as the one making the AddProductToCart command.

MVC5 Authentication: Authorize attribute on every controller or base controller

I have been doing a lot of research on the best way to secure my MVC 5 application.
We have one Web.csproj with many WebAPI Controllers and also an MVC site with two areas - one for Admin and then the public facing website.
After reading this article which states that the Base Controller is best way, I decided to go with that approach.
However, I am personally not OK with the use of base controllers (see this stackoverflow answer for some of my reasoning).
So, given that I am using MVC 5 (ASP.Net Identity and OWIN Authentication) - can anyone shed some light on the pros and cons of each approach?
The current practice in MVC 5 is to apply the AuthorizeAttribute as a Global filter, and open up individual Actions/Controllers with the AllowAnonymousAttribute
So in App_Start\FilterConfig.cs add the following lines:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
... existing filters
// use the [AllowAnonymous] attribute to open up individual Actions/Controllers
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
filters.Add(new RequireHttpsAttribute());
}
note: for good measure I have also added the RequireHttpsAttribute as every authenticated request with ASP.Net Identity carries the auth cookie, which is vulnerable to Man In The Middle attacks if carried over regular HTTP.
I would always use a base controller, for more reasons than just authentication and authorization...
To get to your question, what we ended up doing was rolling our own custom Authorisation Attributes with complex rules that all inherit from AuthorizeAttribute. Its pretty simple, all you do is inherit from the given attribute and then overwrite the OnAuthorization and AuthorizeCore methods.
Generally, all our controllers do not allow anon access, based on our baseController class. From there it gets as complicated as needed. But it always makes sense to use a base class for things like this and build on top of that. If you ever need to make a very wide system change quickly you tap it into the baseClass and thats it.

Why doesn't unlockedActions override requireAuth in CakePHP?

In my Cake 2.3 app, I have an action that's called via ajax. Since I'm using the Security component, I had to use $this->Security->unlockedActions, otherwise the action would fail.
However, unlockActions doesn't work when $this->Security->requireAuth() is called. Is this a bug? Do I have a misunderstanding of how CakePHP handles security?
Why doesn't unlockActions override requireAuth?
SecurityComponent::requireAuth() adds that action to an array of required actions, stored in SecurityComponent::$requireAuth.
If you take a look at the Security Component's startup code, you'll find that SecurityComponent::_authRequired(), the method that checks the $requireAuth array, is called before the unlocked actions are even checked. I imagine if you require an action to be authorized, that should take precedence over telling the app that it doesn't.
I would still consider this a bug (or incorrectly documented), as it clearly states in the documentation:
There may be cases where you want to disable all security checks for
an action (ex. ajax request). You may "unlock" these actions by
listing them in $this->Security->unlockedActions in your beforeFilter.
This is a new feature so it might be good to open up a ticket explaining the confusion and see what the core team thinks about it.
I should also note here that disabling the Security Component for ajax requests isn't always necessary. I have several apps that successfully use the Security Component, along with CSRF checks, side-by-side with ajax.
Authentication is very different from security.
Security protects against several ways to hack into your website, while the auth components handles the clearance of your users. When a member is updating his profile, I do want to verify that it is a logged in member (authentication), but i might not want to use the security component for the action he is calling.

Best practice securing GWTP application

I am working on application using GWT platform, and now i want to add security part. What is the best practice to do this?
My requirements for security are:
having user authorities;
hide some places from users without required authorities;
hide some elements on page from users without required authorities;
secure server side from unauthorized requests;
comfortable managing all of this things (like in spring using annotations or something like this )
having user authorities;
Model your users with permission atribute, like
private int user_type;
hide some places from users without required authorities;
Use the concept of Gate Keeper
A Gate Keeper is Singleton that obligates you to inherit a method called
boolean canReveal()
Using this, you can call server and search for user permission, then reveal or not the presenter called.
If a Presenter need security, just add #UseGateKeeper on it Proxy interface, like:
SomePresenter extends Presenter<V,P>{
#UseGateKeeper(YourGateKeeper.class)
SomePresenterProxy extends ProxyPlace{}
}
This will block users without some permission to access a presenter.
hide some elements on page from users without required authorities;
A good question, I've never seen this type of security in GWTP Projects. But you can always use Widget.setVisible(false) ;D, but I don't know if gwtp has a good practice for this.
secure server side from unauthorized requests;
GWTP GWTP makes it possible to link each of your ActionHandlers with a server-side ActionValidator that determines whether or not the current client can execute the action
You can hide some server calls using ActionValidator's.
read this
comfortable managing all of this things (like in spring using annotations or something like this)
As you can see, many of this security concepts use Annotations and other's stuff to manage easily your Application.

Having trouble putting real-world logic into the DDD domain layer

Despite having studied Domain Driven Design for a long time now there are still some basics that I simply figure out.
It seems that every time I try to design a rich domain layer, I still need a lot of Domain Services or a thick Application Layer, and I end up with a bunch of near-anemic domain entities with no real logic in them, apart from "GetTotalAmount" and the like. The key issue is that entities aren't aware of external stuff, and it's bad practice to inject anything into entities.
Let me give some examples:
1. A user signs up for a service. The user is persisted in the database, a file is generated and saved (needed for the user account), and a confirmation email is sent.
The example with the confirmation email has been discussed heavily in other threads, but with no real conclusion. Some suggest putting the logic in an application service that gets an EmailService and FileService injected from the infrastructure layer. But then I would have business logic outside of the domain, right? Others suggest creating a domain service that gets the infrastructure services injected - but in that case I would need to have the interfaces of the infrastructure services inside the domain layer (IEmailService and IFileService) which doesn't look too good either (because the domain layer cannot reference the infrastructure layer). And others suggest implementing Udi Dahan's Domain Events and then having the EmailService and FileService subscribe to those events. But that seems like a very loose implementation - and what happens if the services fail? Please let me know what you think is the right solution here.
2. A song is purchased from a digital music store. The shopping cart is emptied. The purchase is persisted. The payment service is called. An email confirmation is sent.
Ok, this might be related to the first example. The question here is, who is responsible for orchestrating this transaction? Of course I could put everything in the MVC controller with injected services. But if I want real DDD all business logic should be in the domain. But which entity should have the "Purchase" method? Song.Purchase()? Order.Purchase()? OrderProcessor.Purchase() (domain service)? ShoppingCartService.Purchase() (application service?)
This is a case where I think it's very hard to use real business logic inside the domain entities. If it's not good practice to inject anything into the entities, how can they ever do other stuff than checking its own (and its aggregate's) state?
I hope these examples are clear enough to show the issues I'm dealing with.
Dimitry's answer points out some good things to look for. Often/easily you find yourself in your scenario, with a data shoveling from db up to GUI through different layers.
I have been inspired by Jimmy Nilsson's simple advice "Value objects, Value objects and more Value objects". Often people tend to focus to much on Nouns and model them as entity. Naturally you often having trouble in finding DDD behavior. Verbs are easier to associate with behavior. A good thing is to make these Verbs appear in your domain as Value objects.
Some guidance I use for my self when trying to develop the domain (must say that it takes time to construct a rich domain, often several refactoring iterations...) :
Minimize properties (get/set)
Use value objects as much as you can
Expose as little you can. Make you domain aggregates methods intuitive.
Don't forget that your Domain can be rich by doing Validation. It's only your domain that knows how to conduct a purchase, and what's required.
Your domain should also be responsible for validation when your entities make a transition from one state two another state (work flow validations).
I'll give you some examples:
Here is a article I wrote on my blog regarding your issue about anemic Domain http://magnusbackeus.wordpress.com/2011/05/31/preventing-anemic-domain-model-where-is-my-model-behaviour/
I can also really recommend Jimmy Bogard's blog article about entity validations and using Validator pattern together with extension methods. It gives you the freedom to validate infrastructural things without making your domain dirty:
http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/
I use Udi's Domain Events with great success. You can also make them asynchronous if you believe your service can fail. You also wrap it in a transaction (using NServiceBus framework).
In your first example (just brainstorming now to get our minds thinking more of value objects).
Your MusicService.AddSubscriber(User newUser) application service get a call from a presenter/controller/WCF with a new User.
The service already got IUserRepository and IMusicServiceRepository injected into ctor.
The music service "Spotify" is loaded through IMusicServiceRepository
entity musicService.SignUp(MusicServiceSubscriber newSubsriber) method takes a Value object MusicServiceSubscriber.
This Value object must take User and other mandatory objects in ctor
(value objects are immutable). Here you can also place logic/behavior like handle subscriptionId's etc.
What SignUp method also does, it fires a Domain Event NewSubscriberAddedToMusicService.
It get caught by EventHandler HandleNewSubscriberAddedToMusicServiceEvent which got IFileService and IEmailService injected into it's ctor. This handler's implementation is located in Application Service layer BUT the event is controlled by Domain and MusicService.SignUp. This means the Domain is in control. Eventhandler creates file and sends email.
You can persist the user through eventhandler OR make the MusicService.AddSubscriber(...) method to this. Both will do this through IUserRepository but It's a matter of taste and perhaps how it will reflect the actual domain.
Finally... I hope you grasp something of the above... anyhow. Most important is to start adding "Verbs" methods to entitys and making the collaborate. You can also have object in your domain that are not persisted, they are only there for mediate between several domain entities and can host algorithms etc.
A user signs up for a service. The user is persisted in the
database, a file is generated and saved (needed for the user account),
and a confirmation email is sent.
You can apply Dependency Inversion Principle here. Define a domain interface like this:
void ICanSendConfirmationEmail(EmailAddress address, ...)
or
void ICanNotifyUserOfSuccessfulRegistration(EmailAddress address, ...)
Interface can be used by other domain classes. Implement this interface in infrastructure layer, using real SMTP classes. Inject this implementation on application startup. This way you stated business intent in domain code and your domain logic does not have direct reference to SMTP infrastructure. The key here is the name of the interface, it should be based on Ubiquitous Language.
A song is purchased from a digital music store. The shopping cart
is emptied. The purchase is persisted. The payment service is called.
An email confirmation is sent. Ok, this might be related to the first example. The question here is, who is responsible for orchestrating this transaction?
Use OOP best practices to assign responsibilities (GRASP and SOLID). Unit testing and refactoring will give you a design feedback. Orchestration itself can be part of thin Application Layer. From DDD Layered Architecture:
Application Layer: Defines the jobs the software is supposed to do and directs the
expressive domain objects to work out problems. The tasks this layer
is responsible for are meaningful to the business or necessary for
interaction with the application layers of other systems.
This layer is kept thin. It does not contain business rules or
knowledge, but only coordinates tasks and delegates work to
collaborations of domain objects in the next layer down. It does not
have state reflecting the business situation, but it can have state
that reflects the progress of a task for the user or the program.
Big part of you requests are related to object oriented design and responsibility assignment, you can think of GRASP Patterns and This, you can benefit from object oriented design books, recommend the following
Applying UML and Patterns

Resources