Should I use a Web API 2.2 custom filter or message handler? - asp.net-web-api

I am building a Web API service which will accept 2 of 4 possible tokens in the header. These tokens are used for different purposes but will all be able to be resolved (using lookup in a DB and other operations) to a couple of key pieces of user data.
Only a limited number of endpoints in my controllers will need to receive this information and so I need to know if I should be building a message handler (I believe this is executed for all requests) or a custom action filter (attached via attributes to the specific endpoints.)
Which method is most appropriate for retrieving data from the request header, using it to retrieve user information and populating the header/request with the retrieved data for the controller to use?

Token is an over-loaded term but if you are using "token" as in security token meant for authentication, you can create an authentication filter. If your tokens are just identifiers using which you pull more data from a data store, action filter is a good choice. As you said, message handlers run for all requests (per-route or global granularity) and may not be a good candidate. However, message handlers run earlier in the pipeline and action filters run just before the action method. So, in future, if any other component in your Web API pipeline needs this data, action filter could be too late. If you know for sure only controllers will ever need this data, action filter is probably the best place, given the granularity they provide.

Related

How to "break" the Stateless rule in REST

I wanted to approach the question of "what is Stateless exactly in REST" with the following question title because of the following notes I've gathered:
To be "Stateless" means that the user must always supply the necessary information in the request for the server to process.
Because of that fact, a client can contain number of identifiers such as, authentication key to be passed in every request to know who is the user. (Without knowing of his existence)
When the client asks for a list of orders for his business, the server can know which resource to fetch the information from and how to filter it using the User Id.
in ASP.NET Sessions, a client must provide a "Session Id" cookie in order to load the Session data in the first place. So again, the client provides the necessary data for the server to process. ASP.NET just prepares the endpoint method with cached session data to be used for the process. An example of that usage would be to which sub-user the client is logged into.
This is what got me confused, since in some articles about REST, the "Stateless" rule means that no session shall be stored in server about the client.
For example "The server will not store anything about the latest HTTP request.... No session, no history"
My only example (of breaking the rule "properly") that I can think of is a case where you need to process ONE ACTION by multiple requests.
What can be described as an example of a service that completely breaks the REST rule of being stateless?

How to access Request Specific Data in Go?

I have an API written in go and I am using the gin-gonic framework to implement my endpoints. I am following clean architecture for my project which means that my entire application is divided into multiple layers namely - Controller, Service, Repository, And Session. The endpoints are secured by auth0 and the validation is carried out in a gin middleware. In the middleware I can extract the Subject from the JWT (Set in the header)
Now, here's my question. I want to use this subject value in my queries. I was wondering if I can store the Subject (sub) in the context and use it in other parts of my code WITHOUT PASSING CONTEXT AROUND. Is this possible? Or do I simply have to update all my functions and add a new parameter "Sub" to all downstream calls?
I am alluding to using a Global Variable of sorts to access Request Specific Data (SUB from the JWT token). I know it's a bad practice- I am just wondering if there is any other way to accomplish this other than passing around request specific data? Any help is appreciated.
It is really the whole point of the context - it exists to hold these kinds of things and to be passed around the chain. It's important because you want to keep it scoped to the request -- if you start using globals you could run into issues where you get contention because multiple requests are messing with the same data. Likewise if the token was invalidated between requests.
If your authentication middleware runs before your query (which it sounds like it does) then it should be simply a matter of having it put the subject in the context in a way you're happy with.

Autofac construction order with Web API Filters

I have an authentication filter IAutofacAuthenticationFilter hooked up with a web api project. The app uses basic auth for each request, and I want to construct a ClaimsPrincipal based upon the values int he Authorize header.
I also want to construct an object that depends upon the values in the ClaimsPrincipal. The problem I'm running in to is that the controller is constructed (and thus the dependencies) before the filter, and the filter has not constructed the ClaimsPrincipal, and the controller dependencies fail to activate correctly without the ClaimsPrincipal.
Is there any way to specify the order here, or ensure that the filters run completely prior to the controller construction?
Thanks!

Can requests via Ajax to make direct db queries ever be made secure?

Suppose you would format your urls so that you could make direct model queries with a request using Ajax.
Making a query in Django:
MyModel.objects.get(id=4)
Making a query via request to url using Ajax:
/ajax/my-model/get/id/4/
The problem is that this presents a huge security problem, any user that knows how to make requests via Ajax could query the database by recognising that the url corresponds to a query of a specific model. However, if these kind of queries could be made secure, it would allow for much more well structured/reuseable client side code imo.
But I simply don't see how this can be made secure. I just want to make sure if this suspicion is correct.
Never trust input from the client. I think this is a very general rule in web development and applies to any request the client does. I think you have a couple options here:
use Django's internal Authorization mechanism. This is not authentication! Like this you can limit resources to be accessed to specific users only. Also look into reusable django apps, which seem to take some complexity out of that topic.
validate every input from the client. This is mostly for requests which are supposed to change data).
use an API framework like django-tastypie or django-restframework, which are easily plugable with your models and offer authentication and authorization out of the box.
In Django, such views will be protected by its authentication mechanism. It is possible to design the view so it will only allow specific users to query specific queries.

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