on3al on3al - 1 year ago 152
TypeScript Question

What is the format for credentials in ServiceStacks JsonServiceClient?

I'm attempting to use ServiceStack's typescript JsonServiceClient, and it works fine with routes that don't require authentication, but I can't find any documentation on how to use it with authenticated routes.

I'm using basic authentication, and I can get it work if I manually set the authorization header, but I see that the JsonServiceClient has credentials property that is a string.

What format should that credentials string be in to use basic auth ( or any other auth providers) and how do I ensure the basic auth header is sent on every request?

I know I shouldn't have to set the authorization header manually like a caveman.

Answer Source

If you've registered the CredentialsAuthProvider you can authenticate with a normal Web Service Request, e.g:

var client = new JsonServiceClient(baseUrl);
client.Post(new Authenticate {
    provider = "credentials",
    UserName = userName,
    Password = password,
    RememberMe = true,

If successful (i.e. doesn't throw) the ServiceClient will be populated with ServiceStack's Session Cookies allowing it to make authenticated requests.

If you have HTTP Basic Auth enabled, i.e. registered the BasicAuthProvider then you can use the built-in Username/Password properties to send HTTP Basic Auth credentials with each request, i.e:

var client = new JsonServiceClient(baseUrl) {
    UserName = userName,
    Password = password

Some other options for authenticating with the Service Client is to specify an API Key if you've registered the ApiKeyAuthProvider or specifying a JWT Token if using a JwtAuthProvider.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download