Should the access control belong to business logic? - go

I have a simple CRUD application that provides REST API service.
Besides simple entity CRUD, it also applies ACL rules to the entities.
It is hard for me to decide where to put the access control logic.
I am tempted to using middleware to do access control (this is a go project), since I can "separate business code and authentication & authorization".
But the ACL rules I'm applying is a bit fine-grained. It is based on user (subject) and entity (object). The rule looks like:
subject, object, permission
user_a, entity_a, read
user_b, entity_b, write
So extracting it into middleware is painful because the object part sometimes comes from path variable, sometimes from request body. And after that middleware I still need to extract authentication info for other usage.
What's more, if I apply ACL before the request touching service layer, the API will become less RESTful.
For example, if the user requested an unexists resource, say /foo/1, where there's no entity record nor ACL rules for this resource. If the ACL rules applied before service code, missing ACL rule will produce a 403 instead of a 404.
So my question is is controlling access in middleware a common pattern but I'm not doing it correctly, or should I instead just put the access control part into my service?

Related

Microservices authorization. How to prevent user with valid JWT access other users resources?

I have a number of stateless Microservices behind API Gateway and I want to make sure that a user request containing valid Authorization JWT token cannot access resources of other users.
Currently, my API Gateway only validates if the JWT is not expired and is valid.
To prevent a user request with valid JWT access resources of other users, I was going to use Spring's Method Level Security and check if the principal user id matches the userId in the request URL path. But that means that, in each microservice, I need to add Spring Security, create an authorization filter, and create a security context based on the information I read from JWT. I will need to recreate the Spring Security Context in every single Microservice.
Is it a correct way to do it? If not, what is another way to prevent a user request containing valid JWT to access the resources of other users?
Please advise me.
How you’re handling it is usually the correct approach. In order for each service to remain de-coupled from others it’s important it is able to determine which methods/endpoints care about the user scope and which ones don’t. More rules and logic in the gateway means more restrictions on what individual services can do.
That being said, if you have globally predictable rules that apply to all services you have a case for putting the logic in the gateway. Something like JWT verification is an example of such a rule that is standardized enough that you can make assumptions about what underlying services would want to do with the token upon receiving it (verify it). If you have a rule you can safely apply globally, you can pull it out of the services and put it in the gateway. Otherwise, you’re better off with a bit of duplication so that you don’t create hurdles that would prevent services from handling input differently.

How to customized JWT verification in light-4j

We are using a light-4j proxy service with openapi3 and one of the api methods require more than one scope. Using enableVerifyScope of the jwt, we are getting success if one of the jwtScopes matches any of the specsScopes. Is there a way that we can verify all the required scopes and not only one. Thanks!
You have a very unique use case. Normally you can define several scopes for your endpoint and the scope verification will ensure that the incoming JWT has at least one matched scope to proceed. It looks like you want to ensure that the JWT contains all the scopes in order to grant access to the endpoint. This is not the standard implementation; however, it is very easy to customized the https://github.com/networknt/light-rest-4j/blob/master/openapi-security/src/main/java/com/networknt/openapi/JwtVerifyHandler.java and replace the built in handler in handler.yml file. In light-4j, all middleware handlers can be plugin and so many customers have there own customized handlers especially handlers within business domain. Let me know if you have question on how to inject your handlers to your applications.

Approach to secure different WebApi service methods for different clients

I have a set of services, all of which have, up until now, served a single client. The service methods so far have fallen into two groups - those that are secured/require a token and those that are accessible to anyone. The secured methods have the [Authorize] attribute assigned to them and the non-secured methods do not. It all works fine. We're using an Identity Server-based Authentication service and bearer token authentication.
Now I want to add a new client and one or two new methods that are only accessible to that new client. Defining the new client in my Authentication service is easy enough. I want to understand how best to authorize different methods for different clients. Do I need to build my own custom Authorize attribute that checks either the client id or, better yet, the scope and define a separate scope for these new methods?
I guess that's the bottom line question: Does authorizing different methods for different clients entail a custom Authorize attribute? Is that the typical or best approach or is there another way?

Is it possible to expose multiple endpoints using the same WebAPI controller?

I want to create a WebAPI service for use in my single page application but I also want it to be available for a mobile application too.
When users are using the SPA they are signed in using forms authentication and have a session cookie but if they're using the mobile application this wont be the case.
Is it possible to expose the same API controller as 2 different endpoints where one is authenticated using mutual SSL, a token or as a last resort basic auth and the other uses the session cookie?
For example take the following controller:
public class TodoController :
{
public IQueryable<TodoModel> GetTodos()
{
...
}
}
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
I want to configure IIS to use mutual SSL for the mutual auth endpoint and use forms authentication for the other endpoint.
Short answer: yes
This is a very broad question, so I won't go into excessive detail about every aspect. I think you should also take a look at BreezeJS because it makes things building these applications significantly easier.
DESIGN
Do you want to build in pure HTML and JavaScript or incorporate CSHTML? The decision is yours, but if you want to eventually create native-based applications using something such as PhoneGap Build, you'll want to stick to pure HTML and JavaScript so that you can compile the code later.
Do you want to use another JS library such as BreezeJS to make life a little easier when designing your controllers? Out of the box, your Web API controllers will be prefixed with api/{controller}/{id} in WebApiConfig. You may want to add {action} routing if you don't go with something like BreezeJS so that you can have more flexibility with your controllers.
Lastly, let's talk about the Repository Pattern and Unit of Work Pattern. This is a bit of hot-topic, but I find that usually creating a repository allows you a great deal of flexibility and it's great for dependency injection. Adding an additional repository layer to your controllers allows you to differentiate between different users or means of access such as a SPA or mobile application very easily. You can use the exact same controllers, but simply draw from different repositories.
SECURITY
You'll want to touch up a bit on [Authorize], [ValidateHttpAntiForgeryTokenAttribute], [Roles("")], and several other data annotations for starters. This is a huge topic which has a ton of reading material online -- invest in some research. Your controller can have multiple actions which have varying limitations on them, such as preventing CSRF on the SPA, but be less restricted on Mobile by either utilizing varying actions on the controller or drawing from separate repositories.
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
Yes, absolutely. You'll just have to do some extra work with your routing configuration files. With BreezeJS, you get access to not only /api/ but /~breeze/ which works very similarly.
You can secury your Web API using the way you want. For exemple, you can provide a custom Message Handler or a custom Authorization Filter to provide external authentication via token.
There's a full session from the ASP.NET Team that covers this, you just need to choose which one you will pick up:
Security issues for Web API.
Assuming you are hosting web API in IIS, if you enable the forms authentication, FormsAuthenticationModule establishes the identity. That is, if you look at HttpContext.Current.User or Thread.CurrentPrincipal after a successful authentication, the object of type IPrincipal will have the identity (which is FormsIdentity) and the IsAuthenticated property will be set to true. You can do the same thing for any other credential using a custom DelegatingHandler. All you need to do is to validate the credential (token, user id and password in basic scheme in HTTP authorization header or whatever) and set the HttpContext.Current.User and Thread.CurrentPrincipal to an object of type GenericPrincipal with GenericIdentity. After this, the same action method of a controller which is decorated with Authorize will work for both types of requests.

Hot Towel/Durandal/Breeze.js: how to vertically secure data calls?

I'm new to the whole client-side SPA world. I'm using the above technologies, which seem quite promising. However, one huge snag that I can't get over easily is the lack of built-in security. I had to manually roll out the user authorization, which IMHO should be part of the framework.
Now that I have that sorted, I'm getting major headaches with vertical security: where one user is logged in but can easily access other users' info by changing a few parameters in the browser console. I could pass the userId with every call and then compare it with the one on the server, but I was hoping that there would be an overarching solution that doesn't pollute the breeze data calls with user ids.
For example, let's say there's a call from the data service like this:
function getItems(){
var query = breeze.EntityQuery.from('Items').expand("Person");
return manager.executeQuery(query);
}
this will get all the items, not good. So let's limit by userId:
function getItems(userId){
var query = breeze.EntityQuery.from('Items').where("userId", "==", authentication.userId).expand("Person");
return manager.executeQuery(query);
}
in the second example, we get the userId from the authentication service, which stored the userId when the user was logged in. However, a malicious user can easily go the browser console and change that value.
Of course, I could pass the userId using withParameters(...) and compare it with the current one on the server, but I'd have to do that for every call, which doesn't seem right. Is there a better way to secure calls with the trusted user id?
#Ali - I understand your pain and your concern. You are right to fear any form of so-called security that relies on information passed in the URL. Fortunately there are excellent answers to your concerns and Breeze apps work well with them.
For example, have you studied the ASP.NET Breeze/Knockout Template? It uses Forms Auth for authentication and guards the Web API controller with an [Authorize] attribute. Only logged-in users can access any of the controller methods.
That authentication also sets the IPrincipal which the Web API controller makes available through its User property. You'll see User passed to the constructor of the TodoRepository. In that repository you'll find guard logic to restrict query and saves to just the Todo information belonging to the requesting user.
Look at the network traffic. You won't find any user identifying information in the URL or the request/response bodies. You will see an encrypted authentication cookie in a header.
An obvious flaw in the example is that the client/server traffic takes place in the clear. You must add transport level security (HTTPS) before you go to production. But this is a demo after all.
Why not just do this in the controller?
If the Web Api is secured with [Authorize] then you can get the users ID in the controller and make sure that the data returned is for the currently logged in user.

Resources