I am trying to connect to a JWT authenticated service using the Servicestack JsonServiceClient, however the Docs only describe how to do this using the C# client:
http://docs.servicestack.net/jwt-authprovider
In these docs, it indicates there should be a BearerToken property on the client like so:
var client = new JsonServiceClient(baseUrl) {
BearerToken = jwtToken
};
However this seems to be missing on the Javascript Client. How can I assign the jwtToken when using the Javascript client?
I have tried the following variations to get this to work:
var jwtToken = this.auth.getAccessToken();
this.client = new JsonServiceClient('/');
// Variation #1
this.client.headers.append("Authentication" , jwtToken,);
// Variation #2
this.client.headers.append("Authentication" , "Bearer " + jwtToken,);
// Variation #3
this.client.headers.append("Authentication" , "BearerToken " + jwtToken,);
Victory!
My mistake was the header name. It's not "Authentication" it's "Authorization".
So this works:
this.client.headers.append("Authorization" , "Bearer " + jwtToken,);
Related
Im new in Puppeteer and im stuck.
Project is related to Angular App, on which user is logged in by link from email.
I need to pass barear token to the headless browser. Whatever solution i found online, its not working.
Is there any option to pass user object in Local Storage perhaps?
Or any other idea?
Thanks
faced the same issue but tried to copy the cookies and worked with me
var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(
new LaunchOptions { Headless = true,IgnoreHTTPSErrors=true });
await using var page = await browser.NewPageAsync();
var keys = HttpContext.Request.Cookies.Keys;
string cookieString = "";
foreach (var key in HttpContext.Request.Cookies.Keys) {
cookieString = cookieString + key +"="+ HttpContext.Request.Cookies[key]+";";
}
await page.SetExtraHttpHeadersAsync(new Dictionary<string, string> {
{ "cookie" , string.Join(';',cookieString) }
});
rojaswilmer has already suggested to use setExtraHTTPHeaders. Just change Basic with Bearer since it's not HTTP Basic auth, as explained also in another question in StackOverflow.
Hello did you try with the api to modify the header?
const headers = new Map();
headers.set(
'Authorization',
`Basic ${new Buffer(`${myuser}:${mypass}`).toString('base64')}`
);
await page.setExtraHTTPHeaders(headers);
https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md#pagesetextrahttpheadersheaders
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
};
Here is my issue:
We integrated docusign in our application, server side with nodejs using this tutorial https://github.com/docusign/docusign-node-client ("OAuth JSON Web Token (JWT) Grant" section)
We have done the "Go Live Process": our application is registered in our production account
We have replaced the test config to the production config.
When we try to create an envelope, we get the following error:
PARTNER_AUTHENTICATION_FAILED: The specified Integrator Key was not found or is disabled. Invalid account specified for user
What am I doing wrong ?
async function docusignInit() {
var options;
var env = [40077,50077].indexOf(config.main.port) != -1 ? 'test' :'prod';
if (env == "test") {
options = {
basePath: restApi.BasePath.DEMO,
oAuthBasePath: oAuth.BasePath.DEMO
}
} else {
options = {
oAuthBasePath: "account.docusign.com",
// We called https://account.docusign.com/oauth/userinfo to found the uri
basePath:"https://eu.docusign.net/restapi/"
}
}
// in production, We must do
// var apiClient = new docusign.ApiClient(options.basePath);
// Otherwise, we get "Error: getaddrinfo ENOTFOUND undefined undefined:443"
var apiClient = new docusign.ApiClient(options.basePath);
var privateKeyFile = fs.readFileSync(`./server/docusign/keys/${env}/private.PEM`);
var res = await apiClient.requestJWTUserToken(config.docusign.integratorKey, config.docusign.userName, [oAuth.Scope.IMPERSONATION, oAuth.Scope.SIGNATURE], privateKeyFile, 3600)
var token = res.body.access_token;
apiClient.addDefaultHeader('Authorization', 'Bearer ' + token);
docusign.Configuration.default.setDefaultApiClient(apiClient);
await sendDocusign({
userId: 1,
firstName: 'foor',
lastName: 'bar',
email:'foo#bar;'
})
}
async function sendDocusign(role) {
var envDef = new docusign.EnvelopeDefinition();
envDef.emailSubject = 'Please signe this';
envDef.templateId = config.docusign.templateId;
var role = new docusign.TemplateRole();
role.roleName = "roleName";
role.clientUserId = role.userId;
role.name = role.firstName + " " + role.lastName;
role.email = role.email;
envDef.allowReassign = false;
envDef.templateRoles = [role];
envDef.status = 'sent';
var envelopesApi = new docusign.EnvelopesApi();
return await envelopesApi.createEnvelope(config.docusign.userAccountId, {
'envelopeDefinition': envDef
})
}
As you are able to generate AccesToken properly in PROD with PROD RSA KeyPair, so please check the endpoint which you using to make API calls to create an envelope. In demo it is always demo.docusign.net but in PROD it will be a different value depending on where you PROD account exists in the DocuSign data center. For instance if your PROD account is in NA1, then hostname will be will be www.docusign.net; if it is NA2 then hostname will be na2.docusign.net etc.
So it is recommended to make a /userinfo API call with the Access token to know the baseURI to make calls related to envelope. To get the base URI, call the /oauth/userinfo endpoint, supplying your application’s access token as a header.
For the developer sandbox environment, the URI is
https://account-d.docusign.com/oauth/userinfo
For the production environment, the URI is
https://account.docusign.com/oauth/userinfo
Documentation related to /userinfo API call is available here. Once you know you BaseURI then append this baseURI with envelopes related endpoint like below:
{base_uri} + "/restapi/v2.1/accounts/" + {account_id}
considering your error seems that you're missing the integratorKey or you're writing it in the wrontg way. According to that LINK is possible that you miss the brackets inside the intregrator key?
The integrator key must be placed in front of the user ID that is in
the Username node of the UsernameToken. The integrator key must be
wrapped with brackets, “[ and ]”.
An example of the api in the above documentation:
<soap:Header>
<wsa:Action>http://www.docusign.net/API/3.0/GetRecipientEsignList</wsa:Action>
<wsa:MessageID>uuid:3f9d7626-c088-43b4-b579-2bd5e8026b17</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsa:To>http://demo.docusign.net/api/3.0/api.asmx</wsa:To>
<wsse:Security soap:mustUnderstand="1">
<wsu:Timestamp wsu:Id="Timestamp-8838aa24-9759-4f85-8bf2-26539e14f750">
<wsu:Created>2006-04-14T14:29:23Z</wsu:Created>
<wsu:Expires>2006-04-14T14:34:23Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-7c7b695e-cef7-463b-b05a-9e133ea43c41">
<wsse:Username>[Integrator Key Here]2988541c-4ec7-4245-b520-f2d324062ca3</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
<wsse:Nonce>SjlScsL5q3cC1CDWrcMx3A==</wsse:Nonce>
<wsu:Created>2006-04-14T14:29:23Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soap:Header>
I am trying to update only one application setting using below request. My setting is getting updated properly, but my all other application settings are vanished. I see only one settings there with the correct updated value which I tried to update. I do not want to loose or change all other application settings.
What am I missing here or what is wrong I am doing?
I am following the below given article:
https://learn.microsoft.com/en-us/rest/api/appservice/webapps/updateapplicationsettings
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/appsettings
I am using their online tool to send the request:
https://learn.microsoft.com/en-us/rest/api/appservice/webapps/updateapplicationsettings
Since I am using the online tool it is generating the authorization token. But I want to do programmatically. It would be great if I can get the sample code to generate the token and to update application settings.
Authorization: Bearer
eyJ0eXAiOixxxxxxxeyE_rd3Cw
Content-type: application/json
I reproduce your problem and if you want to update application setting, you need to write down all the application settings, otherwise it will be overridden by the one application setting.
Preparation:
1.Register an App registration in Azure Active Directory and get appid and appsecret. Please refer to this article.
2.Add the registered app into Role assignments under Access control.
Here is C# code sample you could refer to.
var appId = "xxxxxxxxxxxxxxxxxxxx";
var secretKey = "xxxxxxxxxxxxxxxxxxxx";
var tenantId = "xxxxxxxxxxxxxxxxxxx";
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
var accessToken = tokenResponse.AccessToken;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var baseUrl = new Uri($"https://management.azure.com/");
var requestURl = baseUrl +
#"subscriptions/xxxxxxxxxxxxxxxxxxx/resourceGroups/xxxxxx/providers/Microsoft.Web/sites/xxxxxx/config/appsettings?api-version=2016-08-01";
string body = "{\"kind\": \"webapp\",\"properties\": {\"WEBSITE_NODE_DEFAULT_VERSION\": \"6.9.1\",\"aaa\": \"bbb\"}}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/json");
var response = client.PutAsync(requestURl, stringContent).Result;
}
The result is as below:
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")