The ServiceStack docs are full of examples on how to use server side implementation of authentication of a user. But how does one set the user credentials on the client side?
I use ServiceStack to consume a JSON REST service like this:
var restClient = new JsonServiceClient (baseUri);
var response = restClient.Get<MyResponse> ("/some/service");
How can I add any form of authentication to the request? The webservice I want to consume uses OAuth 1.0, but I am interested in adding custom authentication, too.
In my code, I have previously performed OAuth token exchange successfully, so I already own a valid access token and need to sign every REST request now using this access token and its token_secret.
Answering myself, as I’ve found a nice way to do it using the
LocalHttpWebRequestFilterhook in theJsonServiceClient:For securing a web service with OAuth 1.0a, every http request has to send a special
Authorization:header. Within this header field, a hash (signature) must be send that uses some characteristics of the request as input data, like the hostname, request url and others.Now it seems the
LocalHttpWebRequestFilteris called by ServiceStack right before the http request is made, and exposes the underlyingHttpWebRequestobject, where one can add extra headers and access the required fields of the request.So my solution is now basically:
Note that I use the Devdefined.OAuth library to do all the heavy stuff in
CalculateSignature(). The creation of request token, obtaining user authorization, and exchanging the request token for access token as required by OAuth is done outside of ServiceStack, before the above service calls.