While executing the below code I am getting the token such format like Bearer {token}
Now While gitting the getOrderList() I am getting a 400 Bad Request error.
I am not sure what am I doing wrong? I am using this https://documentation.b2c.commercecloud.salesforce.com/DOC1/index.jsp?topic=%2Fcom.demandware.dochelp%2FOCAPI%2F15.2%2Fshop%2FResources%2FOrders.html as a reference to fetch all orders from the salesforce while is created recently.
Can anyone help me with this thing?
'use strict';
const fetch = require('node-fetch');
const ocapi_path = require('./ocapi_path');
const envDomain = 'Domainhere';
const envClientId = 'clientidHere';
const getToken = async (domain = envDomain, clientId = envClientId) => {
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/customers/auth?client_id=${clientId}`,
{
method: 'POST',
body: JSON.stringify({ type: 'guest' }),
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
},
},
);
if (!response.ok) {
const json = await response.json();
throw new Error(`OCAPI error response: ${JSON.stringify(json)}`);
}
return response.headers.get('Authorization');
};
const getOrderList = async (token) => {
const domain = envDomain;
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/orders?status=completed`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Cookie': token,
Authorization: token,
},
},
);
if (response.ok) {
return await response.json();
}
return null;
};
const getTheResult = async () => {
const token = await getToken();
const result = await getOrderList(token);
console.log(result);
}
getTheResult();
You need to exchange the access token for session credentials and then use those to call the Orders API.
Retrieve token for guest (you've done this)
Exchange token for session creds:
To obtain a session for a guest or registered customer
you have to pass a valid JWT to /sessions resource. The JWT has to be
passed as Authorization:Bearer request header. In case of success you
get the session cookies back.
REQUEST:
POST /dw/shop/v20_2/sessions HTTP/1.1
Host: example.com
x-dw-client-id: ...
Authorization: Bearer <token>
RESPONSE:
HTTP/1.1 204 NO CONTENT
Set-Cookie : dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT;
Set-Cookie : dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==;
Set-Cookie : dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67; Max-Age=15552000;
Cache-Control: max-age=0,no-cache,no-store,must-revalidate
Call Order API with session creds from previous step:
REQUEST:
GET /dw/shop/v15_2/orders?status=completed HTTP/1.1
Host: example.com
Cookie: dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c="";dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==; dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67;
Content-Type: application/json; charset=UTF-8
RESPONSE:
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
{
"_v" : "15.2",
"count" : ...,
"data" : [...],
...
}
Related
I am trying to send the JWT token in the headers in the Axios API call but in react.js I am not able to send it. I have tried some ways to send it in the header but on the backend, I am not able to get it. And If send the same token on postman then the backend is able to extract the token from the headers.
const token = window.localStorage.getItem("token");
console.log("token",token) // token
const apiHeaders = {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json, text/plain, */*",
"token": `${token}`,
},
};
const result = await Axios.get(
`${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
{
withCredentials: true,
headers: apiHeaders,
}
);
I have also tried sending token as
token: `${token}`
or
token: token
I don't know what I am doing wrong here?
I think your problem is that you have headers twice:
const apiHeaders = { headers: { ... } }
So apiHeaders is an object with a headers field.
When you use that in the get call, that gets expanded to what is effectively:
const result = await Axios.get(
`${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
{
// You probably don't need to do this! withCredentials: true,
headers: {
headers: {
token: token
}
},
}
);
BTW, it would be normal to pass that as a "bearer token" in the authorization header:
headers: {
Authorization: `Bearer ${token}`
}
Also, you probably don't need the withCredentials when you post the token in a header.
i am getting cors issue while trying to connect with azure data lake in vue js app
export default class CustomTokenCredential {
token;
expiresOn;
constructor(token, expiresOn) {
this.token = token;
if (expiresOn == undefined) {
this.expiresOn = Date.now() + 60 * 60 * 1000;
} else {
this.expiresOn = expiresOn.getTime();
}
}
async getToken(_scopes, _options) {
return {
token: this.token,
expiresOnTimestamp: this.expiresOn,
};
}
}
this is the config file
after msal authentication i am getting token
let token = localStorage.getItem("tokencredential");
token = JSON.parse(token);
const tokencredential = new CustomTokenCredential(token)
let todayDate = new Date().toJSON().slice(0, 10).replace(/-/g, '-');
let gmtDate = new Date().toString()
let datalakeService = new DataLakeServiceClient(
`https://accountname.dfs.core.windows.net`,
tokencredential
)
datalakeService.pipeline.options.headers = {
'Content-Type': "application/json",
"x-ms-version": todayDate,
"x-ms-date": gmtDate,
"authorization": `Bearer ${token}`
// "Accept": "*/*",
// 'accept-encoding': 'gzip, deflate',
// 'Host': "https://ompstoragedevelopment.dfs.core.windows.net"
}
these are the code that try to get all containers
async function getContainer(){
let i = 1;
let fileSystems = this.datalakeService.listFileSystems();
for await (const fileSystem of fileSystems) {
console.log(`File system ${i++}: ${fileSystem.name}`);
}
}
then i am getting these kind of errors(i changed to accountname from original account name) , dont know where is issue coming from ,please guide me
also tried with rest api ,here are codes please check
let token = localStorage.getItem("setAccessToken");
token = JSON.parse(token);
let todayDate = new Date().toJSON().slice(0, 10).replace(/-/g, '-');
let gmtDate = new Date().toString()
axios.get("https://account.dfs.core.windows.net?resource=filesystem", {
headers: {
'Content-Type': "application/json",
"x-ms-version": todayDate,
"x-ms-date": gmtDate,
"authorization": `Bearer ${token}`
}
}).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
Access to XMLHttpRequest at 'https://accountname.blob.core.windows.net/?comp=list&_=1649331391770' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhrHttpClient.js?0815:74 GET https://accountname.blob.core.windows.net/?comp=list&_=1649331391770 net::ERR_FAILED
profile:1 Access to XMLHttpRequest at 'https://accountname.blob.core.windows.net/?comp=list&_=1649331391770' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'm using sveltekit set-cookie in an endpoint but I'm unable to figure out how to set more than one cookie. I get three cookies back from expressjs server. I need to set the three of them in my endpoint.
I have this endpoint in sveltekit that fetch from an expressjs
import cookie from 'cookie';
export async function post (event) {
const info = await event.request.json()
let email = info.name
let password = info.password
let fetchresults = ""
//fetch from expressjs//
const letscookie = async () => {
let res = await fetch('http://localhost:3000/testcookie',{
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-type' : 'application/json',
},
body: JSON.stringify({
username : email,
password : password
})
})
const data = await res.json()
fetchresults = data
return data
}
let cookieresults = await letscookie()
return {
headers : {
"loginjs-cookieone" : fetchresults.accesstoken,
"loginjs-cookietwo" : fetchresults.refreshtoken,
"x-custom-header": "Whatever",
'set-cookie': cookie.serialize("loginjs", " setcookie_in_loginjs_headers")
},
body : {
//passthistofront,
//results,
cookieresults
}
}
}
My question is how to setup more than one cookie in my headers? if I do
headers : {
"loginjs-cookieone" : fetchresults.accesstoken,
"loginjs-cookietwo" : fetchresults.refreshtoken,
"x-custom-header": "Whatever",
'set-cookie': cookie.serialize("loginjs", " setcookie_in_loginjs_headers"),
'set-cookie' : [cookie.serealize("cookieone", "valueone"), cookie.serealize("cookietwo", "valuetwo")]
},
I get the last cookie set and anything before it is ignored or over written.
So how do I set more than one cookie in my headers using set-cookie?
I removed other set-cookie lines.
Just one set-cookie and put the cookies in an array like this
'set-cookie' : [cookie.serealize("cookieone", "valueone"), cookie.serealize("cookietwo", "valuetwo")]
One set-cookie in headers.
I'm using axios to send a post request, here's my code:
const getHeaders = (token) => {
const headers = {
"content-type": "application/json",
}
if (token !== undefined) headers.Authorization = `Bearer ${token}`;
return headers;
}
const post = async ({ url, body = {}, token }) => {
const requestObject = {
headers: getHeaders(token),
...body
}
console.log(requestObject);
return await axios.post(url, requestObject);
}
This works when there's no token (for example, the login request), it sends it alright. However, for the next request, I pass a token to request the user details (for example), but when I look at the Chrome network tab, I see this:
So, the headers are being sent as the payload, but then, in the request headers, the "Authorization: Bearer ..." is not there. What am I doing wrong?
If you want to send options you need a third argument....
const post = ({ url, body = {}, token }) => {
const options = {
headers: getHeaders(token)
}
return axios.post(url,body, options);
}
Also async/ await makes no sense here
I am trying to use the twitter api, but need to get authentication. There are 2 types , and I only need Application-only authentication aka app only. This is the type of authentication where an application makes API requests on its own behalf.
The docs explain to use this method, you need to use a bearer token. You can generate a bearer token by passing your consumer key and secret through the POST oauth2 / token endpoint.
Here is the link to docs explaining this endpoint. There is even an example request but still it isn't very clear to me what needs to be done.
I have an API key and API secret key, but am getting the following error:
body: ‘{“errors”:[{“code”:170,“message”:“Missing required parameter:
grant_type”,“label”:“forbidden_missing_parameter”}]}’ }
My server side code looks like this
var request = require('request');
var btoa = require('btoa');
const KEY = encodeURIComponent('1234');
const SECRET = encodeURIComponent('5678');
request({
headers: {
'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
uri: 'https://api.twitter.com/oauth2/token',
method: 'POST',
body: JSON.stringify({
'grant_type': 'client_credentials' // I am passing the grant_type here
})
}, function (err, res, body) {
console.log('res', res)
});
The CURL request in the docs looks like the following:
POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
To to this there were a couple of things. First the request needed to be made server side. You need to install btoa from npm to provide the encoding of the key and secret key. The KEY and SECRET need to be separated by a colon. The body of the request needs to be a string of
'grant_type=client_credentials'
See full code example below.
const btoa = require('btoa');
request({
headers: {
'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
uri: 'https://api.twitter.com/oauth2/token',
method: 'POST',
body: 'grant_type=client_credentials'
}, (error, response, body) => {
const token = JSON.parse(body).access_token;
});
For Swift 5
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let info = Bundle.main.infoDictionary
let twitterConsumerKey : String = (info?["TwitterConsumerKey"] as? String)!
let twitterConsumerSecret : String = (info?["TwitterConsumerSecret"] as? String)!
let loginString = String(format: "%#:%#", twitterConsumerKey, twitterConsumerSecret)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
let urlString = NSString(format: "https://api.twitter.com/oauth2/token");
print("url string is \(urlString)")
let request : NSMutableURLRequest = NSMutableURLRequest()
request.url = NSURL(string: NSString(format: "%#", urlString)as String) as URL?
request.httpMethod = "POST"
request.timeoutInterval = 30
request.httpBody = "grant_type=client_credentials".data(using: String.Encoding.utf8)!
request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
let dataTask = session.dataTask(with: request as URLRequest) {data, response, error -> Void in
guard let httpResponse = response as? HTTPURLResponse,
let receivedData = data else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode)
{
case 200:
let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue)
if response == "SUCCESS"
{
}
default:
print("save profile POST request got response \(httpResponse.statusCode)")
let str = String(decoding:data!, as: UTF8.self)
print(str)
}
}
dataTask.resume()
The problem is with the format of http body of request. I was wrongly using dictionary of grant_type : client_credentials instead of string grant_type= client_credentials.
request.httpBody = try! JSONSerialization.data(withJSONObject:
["grant_type" : "client_credentials"], options: [])