is middleware with business rule wrong? - middleware

Controlling which type of user can access each route using middleware (in the controller layer) is not breaking what the clean architecture recommends?
For example:
"Only administrators can use the route to list all users", this is a business rule, it should be in the use-case layer, not the controller layer.

I found a answer here:
"Security is an application specific concern, it belongs to the interactors. The controllers would access the current user's credentials and pass that information to the interactors. The interactors would use an authorization service to ensure that their particular interaction was authorized. The business objects wouldn't know anything about it."
https://groups.google.com/forum/#!topic/clean-code-discussion/wHzmboOEHzo

Related

Understanding Claims

I'm trying to get up to speed with OpenId Connect, OAuth2.0, Security Token Service and Claims. Imagine a scenario with a large website with many areas and different functionality e.g. Customer, Order, Supplier, Delivery, Returns etc. My question is this – would I create Claims on the Token Server such as CanCreateCustomer, CanReadCustomer, CanUpdateCustomer, CanDeleteCustomer etc, i.e. effectively CRUD Claims for each main area/Business Object? This would lead to many tens but more likely hundreds of Claims. Or is my understanding coming up short?
So fixing terminology, you mean "scopes", not "claims". Scopes are identifiers used to specify what access privileges are being requested. Claims are name/value pairs that contain information about a user.
So an example of a good scope would be "read_only". Whilst an example of a claim would be "email": "john.smith#example.com".
You can send claims in the id token (or JWT), or/and have them available via the userinfo endpoint (if using the "openid" scope).
You can break scopes down per service, and have them as granule as you would like. Or have them as high level (read / write / admin). I would recommend having enough scopes to actively achieve the security principle of least privilege (basically: giving people what they need to do their job). You can use namespaces if you have a lot of scopes.
Your understanding is right, but you have a lot more flexibility in OAuth2.0 scopes (claims)
These scopes can be configured in any way for eg, in your case instead of creating individual scopes for each CRUD operation for each main area, you could create group scopes like
customer.read_write
order.read_write
Etc, you can even go one level higher , by creating functionality level scopes, like
webportal.full_access
adminportal.full_access
Then in your application, after authentication, the authorisation can be done like,
ValidScopesIn({Scopes.WEBPORTAL_FULL_ACCESS, Scopes.CUSTOMER_READ_WRITE})
public void createCustomer(Customer customer) {
// your creation logic
}
I think your understanding is largely correct. However, if I understand what you describe correctly it seems more of an authorization (OAuth) rather than an authentication (OIDC) problem, and as such you might have a look at how other OAuth resource providers define their scopes (not claims btw), for instance GitHub or Slack.
I would recommended that "scopes" be configured as URIs so that collisions do not occur.
As an example.
-jim

.net mvc authentication cookies & sessions

net mvc 5 application using entity frame work etc and am new to .net c# etc (used to php & sessions)
so i have read allot about using .nets authentication service and that is some how registers a user upon login using FormsAuthentication.SetAuthCookie.
however i need to authenticate a user group for example admin or moderator. and from what i understand this can be achieved and be set using [authenticate(roles="admin")].
but surely if this is using a set cookie a user if they knew how could just change their registered role from user to admin to access restricted content?
so in as simple terms as possible how does .net mvc ensure security in authenticating users? can i use sessions instead of cookies? do i need to create my own authentication system.?
i have searched and read all i can find and most resources just explain how cookies work or how to implement authentication using cookies but very little about sessions.
I'll try to be as concise as possible:
Yes, ASP.NET MVC 5 uses cookies out of the box (if you chose Individual User Accounts in the project wizard)
The authorization of a group or role by means of an [Authorize(Roles="bla")] attribute to decorate controllers and/or controller methods will do just that. It's as if you would be writing
if(!User.IsInRole("bla"))
{
return new HttpUnauthorizedResult();
}
else
{
//here's your ultra-secret View
return View();
}
What if a user changes role while in-session or if he or she has a persistent cookie?
Indeed, you'll need to handle the interval between role change and cookie update.
Read up on it here
Long story short: the design decision is yours whether you think it better to log off a user when re-assigning roles or to make db roundtrips at every authorization check.
Can you use a session variable like in PHP? Sure (the Session object exists), but you shouldn't.
If and when the situation arises where you absolutely NEED to pass some arbitrary data however, there's ViewBag, ViewData and TempData.
I won't go as far as to say, that these constructs are superfluous, they certainly have their use from time to time, but do try and design your application to maximize the use of strongly-typed models, viewmodels and make use of the REST-based url architecture to get or put your data.

Authorization strategy on a per-client basis

I have a Rails 4 application. I use devise for authentication and opro for providing oauth2 with my API. All requests are authorized with pundit policies and until now, this setup was totally fine.
Currently, my authorization is always done on a per-user basis. This makes sense, as usually every request is done on behalf of a particular user who is either authenticated in a session or by providing the oauth-token.
The new challenge is: I have certain API-consumers (let me call them devices from now on), whose requests cannot be seen as requests from a particular user. One is an Asterisk Server that can exchange information with the API, another is a GPS Tracking Box that continuously pushes trackpoints to the API.
Thus, I need to authorize certain API-operations on a per-device basis, meaning there is not necessarily a current_user available. Having no current_user however screws up my authorization concept.
I have already considered several approaches to the problem:
creating dedicated users for each device and authorizing them to do the specific action
pro: does not screw up my authorization scheme
contra: would mean to rethink the User-Model, as currently I only have "natural users" that require name, birthday, email, etc
creating dedicated controllers with adapted authorization scheme
pro: high flexibility
contra:
authentication for devices required
extra API endpoints required, does not feel very DRY
I am searching for a best-practice approach for such a situation. I believe this is not an extra-ordinary problem and there must be good solutions for this out there.
You need a separate layer that does the authorization check as well as global attributes called caller_id and caller_type (these are just examples).
You then want to implement a logic e.g.:
if caller_type == device and caller_id == ... then
if caller_type == user and caller_id == ... then
To do that you can just custom-code your own little class. Alternatively you could use XACML to define your authorization logic. See this blog post which applies XACML to servlets. The same principle could be done for your Rails application.
HTH,
David.

How to effectively test unauthenticated user flows?

Given a non-trivial Rails application with significant numbers of controllers and routes only accessible to authenticated users and even then, only by users with the authorisation, what is the most sensible way to test unauthenticated users and unauthorised users are denied access?
Currently I generally test authenticated user flows through features, and fall back to controller tests to test that routes are not accessible to unauthorised or unauthenticated users.
Obviously ensuring that unauthenticated users get a 401 is easy enough to test, but testing authorisation is another matter. It makes sense to have granular tests for access permissions - I want to know if something I've done has inadvertently given a guest the ability to destroy users - but adding such tests for every root balloons the number of tests drastically.
How should I approach this?
It depends on how you do the authorization. You only need to write as many tests as you write blocks of code that authorize.
If you write specific code to check authorization every place a resource is used, there's no alternative but to write a test, probably a controller spec, for each check. I'd also write one Cucumber scenario to specify what the user sees when authorization is denied and to integration-test the entire stack.
If you move your authorization into a framework, whether something like Cancan or a framework of your own, that only requires each controller to call the framework in one place (e.g. CanCan's load_and_authorize_resource), then you only need to write one more spec per controller (one that shows that some authenticated but unauthorized user can't access a resource) to establish that the authorization framework is being called. If the framework moves authorization logic to a new set of classes (e.g. CanCan::Ability subclasses), you'll need to unit-test those classes, but you'll probably be able to use each such class in more than one place, so the number of tests they need won't increase multiplicatively, and their tests will be simpler than controller specs.
Similarly, if your authorization framework were entirely configuration-driven and you had to call it only in one place in your application, you'd only need to write that one Cucumber scenario.
You can probably think of different architectures which would lead to different testing requirements, but I think these examples show the general idea.

Protect deeplink to unauthorized company

I have a multi-tenant application with Companies which have many Users and many Clients.
I have protected the views and controllers with before_filters, so that the current_user can only view clients belonging to the user's company. This works fine, an unauthorized user receives a "you do not have sufficient rights for this action" message. But when a user changes the URL from e.g. "/clients/1/edit" to "clients/2/edit", then he can edit a client from another company. What's the best way to protect this?
Expand your strategy to protect the clients controller as well - you need to be checking ownership of a client record on every action, since only some people should be able to access some clients.
You should be able to continue with whatever solution you've got. Another way to go about it is to use something like CanCan, which centralizes access, and can make it much easier and more straight forward to debug (and more importantly, confirm via your test suite) that users only have access to what they should have access to.
Here is a list of common/popular authorizations gems for Rails that address problems of user access to resources.
Whatever approach you ultimately choose, I can't stress enough how important it is to cover things like security access with test coverage. It's never perfect (because you might forget to test something), but it will mitigate the possibility that you break security access restrictions that are already in place, by keeping your security-related tests as up-to-date as humanly possible.

Resources