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
LocalHttpWebRequestFilter
hook 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
LocalHttpWebRequestFilter
is called by ServiceStack right before the http request is made, and exposes the underlyingHttpWebRequest
object, 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.ServiceStack's AuthTests shows different ways of authenticating when using the ServiceStack Service Clients. By default BasicAuth and DigestAuth is built into the clients, e.g:
Behind the scenes ServiceStack will attempt to send the request normally but when the request is rejected and challenged by the Server the clients will automatically retry the same request but this time with the Basic/Digest Auth headers.
To skip the extra hop when you know you're accessing a secure service, you can tell the clients to always send the BasicAuth header with:
The alternative way to Authenticate is to make an explicit call to the
Auth
service (this requires CredentialsAuthProvider enabled) e.g:After a successful call to the
Auth
service the client is Authenticated and if RememberMe is set, the client will retain the Session Cookies added by the Server on subsequent requests which is what enables future requests from that client to be authenticated.