How to get HttpRequestContext when I am using Self Hosted Owin? - owin

How to get HttpRequestContext when I am using Self Hosted Owin?
My class is being called by ApplicationInsights and not by a controller, so I don't have access to any context.
Is there any way similar to what we do using HttpContext?

There is no static class to retrieve the request when using OWIN self hosted, because you are essentially in a console application, which is unaware that you wrote code that receives http requests.
Owin is a pipeline. The request is passed from middleware to middleware by calling the next middleware with a context parameter containing the request (and the response for that matter).
Each middleware registered in the pipeline can inspect the request on the way in, in their registration order, and call the next middleware before processing the response.
It is very easy to write your own middleware, register it in the pipeline, and inspect the request object for each request coming in.
Take a look here if you need a quick code example : http://benfoster.io/blog/how-to-write-owin-middleware-in-5-different-steps

Related

How to use `fastapi_another_jwt_auth` in the middleware instead of via dependency injection in FastAPI?

I have a FastAPI project which uses fastapi_another_jwt_auth as a way of authenticating users. I'd intend to implement it in most of my endpoints except for a few whitelisted ones, but I find it hard to unit test endpoints that require authentication so I'm thinking of implementing it in a middleware with a simple if-else check for whitelisted endpoints. This way, I just need to disable the middleware to run unit tests and testing for authentication becomes trivial since we're just testing against a whitelist.
The API for fastapi_another_jwt_auth seems designed around the concept of Dependency Injection for FastAPI. Is there a way to use the same library in the middleware?
I looked at the code for fastapi_another_jwt_auth. Apparently, when injecting, the framework runs the AuthJWT constructor, which takes in the Request and Response object. This is shown below.
class AuthJWT(AuthConfig):
def __init__(self,req: Request = None, res: Response = None):
...
Once it is successfully initialised, we can then use the .jwt_required() method.
So the way to implement it in the middleware is:
#app.middleware("http")
async def middleware_callback(req, call_next):
if not whitelisted: # this is pseudocode
auth = AuthJWT(req)
auth.jwt_required() # throws error when user is not authenticated
# rest of the logic
...
This way, I can manage all authentication at the middleware level and I don't have to inject the AuthJWT object into my view functions.

Why do we add properties to request object?

I can't understand why do we add properties to request object?
As I know, the request object comes from the front end side and if any information is needed or they have, the frontend side should attach it to the request object and send it to backend side like a cookie or JWT token, etc.
And after we got that information in the backend side we can add/update more properties to the response object, like new JWT token, new session ID, etc.
But I see in backend codes, they also add properties to request object and this is vague to me. I don't know why the backend side should add something to the request? Maybe because of the internal transactions between the different middleware this happens? I mean middleware1 adds something to the request object and sends it to the middleware2 in backend side?
For example I can't understand why do we add something to req.session not res.session? Because as I understand this data should be passed to the frontend side to be added into their next request.
But if there is any other reason for adding properties to req object instead of the res object, please let me know?
Mutating the request object by adding additional properties is the primary method of passing additional data between middlewares within Express. Since the request and response are passed to every middleware, this is the only chain that gives you continuity between middlewares.
(You will also see some passed on the response object as well, but in general it's most common to see it on req).
Note that you need to avoid collisions with Express's properties and methods as well as the underlying connection objects from Node.

Authenticate Web API session before body upload

I have a simple Web API 2 controller that handles file uploads. It looks like this:
[MyCustomAuthenticationFilter]
[Authorize]
public class FileController : ApiController
{
private IFileRepository _FileRepository;
public FileController(IFileRepository fileRepository)
{
_FileRepository = fileRepository;
}
public async Task<FileInfo> Post()
{
var stream = await Request.Content.ReadAsStreamAsync();
var info = await _FileRepository.CreateFileAsync(stream);
return new FileInfo(info);
}
}
It takes a streamed upload from the client, hands it off to a repository object (which talks to an Azure Storage Blob container), and then returns some data about the uploaded file. Simple enough, and it works great.
Except, the authentication filter is not applied until the client has finished uploading the file. Authentication is a simple challenge/response system using a token, so this means a client could easily upload several hundred megabytes of data (potentially over a slow cellular data connection) before finding out that their token has expired and they need to refresh it and try again. I'd like to be able to examine the request header and validate (or reject) it as early as possible, but that doesn't seem to be doable with the standard filters. I also tried creating a simple IHttpModule and hooking into the BeginRequest event, but that apparently does not fire until after the upload completes, either.
How can I hook into the pipeline such that I can validate the Authorization headers for a request before the client upload completes?
Edit to add:
Obviously Authenticating early doesn't do me any good if I can't also Authorize, based on the route in Web API. My service has a few anonymous methods, so I can't just blanket reject un-authenticated users. Given the architecture of IIS and ASP.net, maybe that means this just isn't possible.
You'll most likely need to make this request into a 2 stage request. One authentication request prior to the file upload request. That's a lot of baggage and the end point can't process a request until it finishes receiving it. Try a separate authorization request before uploading the file. If your request passes then you can send the file upload. Is this an okay solution?

Request method not recognized after promisification

I built an API using AWS API Gateway and Lambda, now I am writing end to end tests, I am using Promise from bluebird and request, so I promisified request like this:
Promise.promisifyAll(require('request'));
Promise.promisifyAll(request);
Now when I make requests (POST, PUT, GET), using request.methodAsync, the method is not recognized by the API Gateway !
I launched Jasmine with :
NODE_DEBUG=request jasmine
I can see the method = 'POST' or whatever, but the API still not recognize the method of the requests I am making with the promisified request ! any one run into this situation ?
Hi I'm from the Api Gateway team. As long as the request is sent to a valid resource path / HTTP method pair on a deployed API, Api Gateway will accept it. Please note you'll need to put the stage name as the first path part in the URI (see example in the Api Gateway console on the Stages page).
If you're invoking the right API resource, the issue sounds like a client-side bug.
Jack

How to use a callback array as the handler for a Sails.js route?

When using Express, it is possible to attach a callback array to a route like this:
app.get('/path', thisIsAnArrayOfFunctions);
And then, when making a request to http://route_to_server/path each function inside thisIsAnArrayOfFunctions is called.
Exactly how does that routing behaviour works in express? is it just an iteration through thisIsAnArrayOfFunctions, passing the arguments req, res and next?
Is it possible to achieve a simple implementation in Sails for this?
I know it works if I attach the routing as an express middleware, but I want to know if there's a solution using the Sails' (version 0.9.8) controller structure.
Thanks in advance.
The Sails-y way of chaining functions to a route is by using policies. The idea is that your controller code should be the last stop in handling your route. Anything that might modify the response (like a login check, or something that could change the params) should be implemented as a policy, which is middleware that can call next or send a response directly. Policies are mapped to controller actions, and multiple policies can be applied to a single action (or to all actions in a controller).
Docs for policies are here.

Resources