How to configure client for access with authsecret? - servicestack

I'm using the client and I need to call a service using authsecret parameter.
If I ad this param to the base url it give me a serialization error.
String baseUrl = AppConfig.GetAppApiUrl();
var client = new JsonServiceClient(baseUrl.AddQueryParam("authsecret","secretz123!"));
var c = client.Send(new ComuneRequest { Id = "A001" });
Using Fiddler I discovered that the request that the client generate is incorrect:
POST
http://192.168.0.63:820/?authsecret=secretz123%21/json/reply/ComuneRequest
So, what I have to do to make the client create a request in a correct format?

It needs to be sent as a Request Parameter (i.e. QueryString or FormData) which you can do using HTTP Utils with:
var url = baseUrl.CombineWith(requestDto.ToUrl()).AddQueryParam("authsecret", secret);
var res = url.GetJsonFromUrl().FromJson<MyResponse>();
Otherwise since AuthSecret is not a property on your Request DTO you wont be able to send it as a Request Parameter in the Request Body, but you should be able to send the param in the Request Headers with:
var client = new JsonServiceClient(baseUrl) {
RequestFilter = req => req.Headers[HttpHeaders.XParamOverridePrefix+"authsecret"] = secret
};

Related

How to fix "attribute xmlns:wsse invalid" error where calling SOAP web service in NodeJS using node-soap

I am trying to call a web service that requires authetication via X509 certificate. I'm using Node.js and node-soap module, getting successfully the WSDL.
But when I try to build the SOAP envelope with the Signature tag inside, I get the following error from the server:
The value of the attribute "prefix="xmlns",localpart="wsse",rawname="xmlns:wsse"" is invalid. Prefixed namespace bindings may not be empty.
I've tried to modify the existingPrefixes that are passed to the underlying library (xml-crypto).
This is my code:
var privateKey = fs.readFileSync(process.env.KEYFILE);
var publicKey = fs.readFileSync(process.env.CERTFILE);
var password = ''; // optional password
var options = {
mustUnderstand: 1,
signerOptions: {
existingPrefixes: {
'wsse': "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
}
},
};
var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password, options);
const endpoint = process.env.ENDPOINT;
soap.createClientAsync(endpoint).then(client => {
client.setSecurity(wsSecurity);
return client.wiOperationAsync({ ... })
})
However, the error persists and I get a SOAP request body with something like this:
<KeyInfo>
<wsse:SecurityTokenReference
xmlns:wsse="">
<wsse:Reference URI="#x509-1639ca80191641b9bd804497cfcef0b5" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
</wsse:SecurityTokenReference>
</KeyInfo>
Any idea to avoid that empty mlns:wsse attribute?

Use nlapiRequestURL to make a request to a Service

How do you use nlapiRequestURL to make a request to a service? My attempt below is failing with the error: UNEXPECTED_ERROR (output from NetSuites script execution log).
My service is set to run without login and works correctly when I directly access it through a browser using its url. Its just the request through nlapiRequestURL thats failing.
Any idea what could be going wrong?
// This code executes in Account.Model.js (register function)
// I am using my own netsuite user credential here
var cred = {
email: "MY_NETSUITE_EMAIL"
, account: "EXXXXX" // My account id
, role: "3" // Administrator
, password: "MY_NETSUITE_PASSWORD"
};
var headers = {"User-Agent-x": "SuiteScript-Call",
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
var payload = {
type: 'is_email_valid'
, email: 'spt015#foo.com'
};
// A raw request to the service works fine:
// http://mywebsite.com/services/foo.ss?type=is_email_valid&email=spt015#foo.com
// Error occurs on next line
var response = nlapiRequestURL(url, payload, headers);
You are attempting to call a non-Netsuite url with Netsuite authentication headers. You do not need that unless for some reason of your own you have implemented NS-style authorization on your service.
nlapiRequestURL does not automatically format a payload into a query string. If your service takes a posted JSON body then you need to call JSON.stringify(payload) e.g
var response = nlapiRequestURL(url, JSON.stringify(payload), headers);
If your service needs a query string like in your example then you need to construct a query string and append it to your service url. e.g.
var qs = '';
for(var k in payload) qs += k +'='+ uriEncodeComponent(payload[k]) +'&';
var response = nlapRequestURL(url +'?'+ qs.slice(0,-1), null, headers);
I would suggest changing your nlapiRequestURL to a GET instead of POST, and add the parameters to the url instead. Your function call will look like this instead.
nlapiRequestURL(url, null, headers, "GET")

how to refresh token servicestack typescript

On servicestack it says that for regular client it should be like that but for typescript it should be somehow different. Anyone knows how to do it?
var client = new JsonServiceClient(baseUrl);
client.OnAuthenticationRequired = () => {
client.BearerToken = authClient.Send(new Authenticate()).BearerToken;
};
Support for onAuthenticationRequired and refreshToken was added to the TypeScript servicestack-client in v0.0.32 where they can be used to transparently handle 401 Unauthorized Responses and re-authenticate the JsonServiceClient from within the callback before it automatically retries the original failed request:
Transparently handle 401 Unauthorized Responses
If the server returns a 401 Unauthorized Response either because the client was Unauthenticated or the configured Bearer Token or API Key used had expired (or was invalidated), you can use onAuthenticationRequired callback to re-configure the client before automatically retrying the original request, e.g:
client.onAuthenticationRequired = async () => {
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const response = await authClient.get(new Authenticate());
client.bearerToken = response.bearerToken;
};
//Automatically retries requests returning 401 Responses with new bearerToken
var response = await client.get(new Secured());
Automatically refresh JWT Tokens
With the Refresh Token support in JWT you can use the refreshToken property to instruct the Service Client to automatically fetch new JWT Tokens behind-the-scenes before automatically retrying failed requests due to invalid or expired JWTs, e.g:
//Authenticate to get a new Refresh Token
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const authResponse = await authClient.get(new Authenticate());
//Configure client with RefreshToken
client.refreshToken = authResponse.RefreshToken;
//Clients will automatically retrieve new JWT Tokens as needed
var response = await client.get(new Secured());
Send Refresh Tokens to an alternate server
Use the refreshTokenUri property when refresh tokens need to be sent to a different ServiceStack Server that issues new JWT Tokens, e.g:
client.refreshToken = refreshToken;
client.refreshTokenUri = authBaseUrl + "/access-token";

ServiceStack: Send JSON string instead DTO via POST

I would like to send a string (JSON formatted) to my webservice instead using a DTO.
var client = new JsonServiceClient(absoluteUrl);
client.Post<T>(absoluteUrl, data);
But, after to do change my data (DTO object) to a JSON string, I'm getting a ServiceStack Exception: Internal Server Error. Looks like the ServiceStack Post/Send method changes my JSON request.
Is it possible or is there any way to avoid it? Someone else had the same issue?
UPDATE 1: I'm using this approach because of the OAuth authentication. I'm generating a HMAC by request.
Thanks.
You can use HTTP Utils to send raw JSON, e.g:
var response = absoluteUrl.PostJsonToUrl(data)
.FromJson<T>();
ServiceStack's .NET Service Clients provide Typed API's to send Typed Request DTO's, it's not meant for POST'ing raw strings but I've just added support for sending raw string, byte[] and Stream in this commit so now you can send raw data with:
var requestPath = request.ToPostUrl();
string json = request.ToJson();
var response = client.Post<GetCustomerResponse>(requestPath, json);
byte[] bytes = json.ToUtf8Bytes();
response = client.Post<GetCustomerResponse>(requestPath, bytes);
Stream ms = new MemoryStream(bytes);
response = client.Post<GetCustomerResponse>(requestPath, ms);
This change is available from v4.0.43+ that's now available on MyGet.
Sharing Cookies with HttpWebRequest
To have different HttpWebRequests share the same "Session" you just need to share the clients Cookies, e.g. after authenticating with a JsonServiceClient you can share the cookies with HTTP Utils by assigning it's CookieContainer, e.g:
var response = absoluteUrl.PostJsonToUrl(data,
requestFilter: req => req.CookieContainer = client.CookieContainer)
.FromJson<T>();

how to pass in paramters to a post request using the servicestack json client

I'm having trouble getting my servicestack json client to format a REST Post request.
I'm trying to post to my login service with a raw json body of
{"Uname":"joe", "Password":"test"}
but the post methods is actually mistakenly sending this
{"login":""}
Here's the code I'm using.
JsonServiceClient.HttpWebRequestFilter = filter =>
{
filter.Headers.Add(string.Format("X-API-Key: {0}", "test"));
};
var client = new JsonServiceClient(url);
var url = "/login";
var login = new LoginModel { Uname = uname, Password = pwd };
return client.Post<UserCredentials>(url, login);
How should I structure the parameter object so that it serializes to the correctly to the intended raw value in the post request? Additionally, can I just pass in a dictionary or a more generic object so that I don't have to create a LoginModel class or struct?
It turns out the issue was that I was using public fields instead of public properties in my LoginModel. Changing it to properties fixed it.

Resources