RMD
RMD

Reputation: 3253

Using a RequestFilter to Perform Custom Authentication in ServiceStack

Brand new to ServiceStack, so forgive me if this is an easy one.

I am writing an API that will use a custom HTTP header for authentication information. I've added a RequestFilter like so:

RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
    if(httpReq.Headers["MyMagicHeader"] != "magic")
    {
        throw HttpError.Unauthorized("Unauthorized");
    }
    else
    {
        //TODO: Populate a "Client" object accessible by the Service
    }
});

My question is, how can I now provide the service in question with the "Client" object that I create based on the value in the magic header?

From the looks of it, my only option is passing this information in via the DTO. So I thought about adding a base class that all my DTOs inherit from, and this base class would contain a Client property.

Is that the correct approach?

Upvotes: 4

Views: 656

Answers (1)

mythz
mythz

Reputation: 143284

The way to pass any information that's available in all Filters and Service in the same request is to use the httpReq.Items object Dictionary, e.g. Dictionary<string,object>"

RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
    if(httpReq.Headers["MyMagicHeader"] != "magic")
    {
        throw HttpError.Unauthorized("Unauthorized");
    }
    else
    {
        //TODO: Populate a "Client" object accessible by the Service
        httpReq.Items["MagicToken"] = CreateMagicValue(httpReq.Headers["MyMagicHeader"]);
    }
});

Upvotes: 3

Related Questions