I try to search items from eBay API. Within the server.js file at my Apollo Server 2, I pass the token string by context property while instantiation (s. Doku: Apollo context argument). So every request contains the authentication HTTP header property. As a tryout, for now, I just use the fixed token string. This will be changed later if I work for the client.
server.js
import { ApolloServer } from 'apollo-server'
import schema from './schema'
const server = new ApolloServer({
schema,
context: ({ req }) => {
const token = 'Bearer v^1.1#i^1#I^3#f^0#p^1#r^0#t^H4sIAAA...' // my token
return {
...req,
headers: {
...req.headers,
// enrich the header with oauth token
authorization: token,
},
}
},
})
server.listen().then(({ url }) => console.log(`🚀 Server ready at ${url}`))
resolver method
// A map of functions which return data for the schema.
const resolvers = {
Query: {
books(root, { keyword = '' }, context) {
console.log(context.headers)
fetch(`https://api.ebay.com/buy/browse/v1/item_summary/?q=${keyword}`)
.then(response => response.json())
.then(json => console.log(json))
return []
}
}
}
The context.header contains the authorization property:
{ host: 'localhost:4000',
connection: 'keep-alive',
'content-length': '108',
accept: '*/*',
origin: 'http://localhost:4000',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
dnt: '1',
'content-type': 'application/json',
referer: 'http://localhost:4000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'de,en;q=0.9',
authorization: 'Bearer v^1.1#i^1#f^0#p^1#r^0#I^3#t^H4sIAAAAAAAAAOV...'
}
The JSON response contains the error with errorId 1002. It says Access token is missing in the Authorization HTTP request header.:
{ errors:
[ { errorId: 1002,
domain: 'OAuth',
category: 'REQUEST',
message: 'Missing access token',
longMessage: 'Access token is missing in the Authorization HTTP request header.' } ] }
Additionally, I use a new browser tab, enter the URL https://api.ebay.com/buy/browse/v1/item_summary/search?q=test and add the same authorization header property (I use the ModHeader chrome extension). I hit enter, the request works and I get the expected JSON.
It is confusing and I don't know what I'm doing wrong while passing the token. Does somebody have an idea?
The headers you see are the ones being sent in the request to your GraphQL server. All you've done is modified them to include the Authorization header and then included your entire request object as your context -- you're not passing any header information to the fetch call actually getting the data from eBay. Minimally, you want to do something like this:
fetch(`https://api.ebay.com/buy/browse/v1/item_summary/?q=${keyword}`, {
headers: {
Authorization: context.headers.authorization,
},
})
Also bear in mind that the fetch call should be returned inside your resolver, otherwise it won't be awaited.
Related
An ruby (Sinatra) API sends a header __authorization__ to the front end application (vuejs) that uses axios.
This works fine on desktops. On a URL called /getJWT the response headers contain:
__authorization__: eyJhI1NiJ9.eyJ1c2VyIjoijE2NzYxMzA0NjB9.4bSrsh-E2pX2pXeC89Bec
access-control-expose-headers : __authorization__
(__authorization__ contains a valid jwt).
on iOS, the header doesn't get set. On the same URL, I get :
__authorization__:
access-control-expose-headers : __authorization__
(__authorization__ is empty).
On the API-side, I have :
get '/getjwt' do
# HTTP_COOKIE contains the refresh token and rack session token
# remove useless part of HTTP_COOKIE to get value of refresh token
refresh = request.env['HTTP_COOKIE']
.sub(/__refresh_token__=/, '') # remove key __refresh_token__
.sub(/;[^;]*$/,'') # remove the first semicolon and everything after the semicolon
settings.jwt = getjwt(refresh)
headers '__authorization__' => settings.jwt
json_status 204
end
and in the Vuejs app, I put the jwt that the __authorization__ header is supposed to send in a pinia store like so:
function getJWT() {
const jwt = getData.get('/user/b/getjwt')
jwt
.then((response) => {
setJWT(response.headers['__authorization__'])
})
.catch((err) => { alert(err) })
return jwt
}
function setJWT(jowt) {
jwt.value = jowt
}
In this code, getDatais an Axios configuration:
const getData = axios.create({
baseURL: import.meta.env.VITE_API_ROOT,
withCredentials: true,
method: 'get',
headers: {
'Content-Type': 'application/json',
},
})
i am trying to get a access token and refresh token to access google sheets data but every time i try to get a token i get the same error "invalid grant type" i am using grant type authorization code. i am trying to get a access token using postman and it worked but its not working in my pycharm.
import http.client
conn = http.client.HTTPSConnection("oauth2.googleapis.com")
payload = 'code=<your code here>A&client_id=<your client id>&client_secret=<your client secret>redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2F&grant_type=authorization_code'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
conn.request("POST", "/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
i tried this and i tried to get token through request also
import requests
url = "https://oauth2.googleapis.com/token"
payload='code=<your-code-here>%0A&client_id=<your client id>&client_secret=<your client secret>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fgsheet&grant_type=authorization_code'
headers = {
'Authorization': 'Bearer ya29.a0AfH6SMC0nVvV0m77pPvgNLnWXopI7VKvoBdVSDSgvi6Fx0mrPYQf9xU6j3UJCA3vrWRi62Tqfv0PFZd9uo59C2NQzraV1MBtAAF1G_tTRXIXELxsbmjf5weGJ6FkmJknDof2riZCnpYzK-J2EWmWKQVeetwd',
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
The method (.request) definition is like this:
HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False)
And your arguments doesn't match!
Reference: https://docs.python.org/3/library/http.client.html#http.client.HTTPConnection.request
I am working on paypal recurring payment and i need token to get subscriber information to allow it login. But i got unauthorized error. Here is my code
getTokan():Observable<any>{
let client_id = '411820721167-jcuj1jeae0l1j06i3q2otsnol2phlqem.apps.googleusercontent.com';
let secret = 'pe7berpzDSlwDVpgj-NQvseP';
let key = client_id+':'+secret;
let headers = new HttpHeaders({
"Accept": "application/json",
"Accept-Language": "en_US",
'Authorization': 'Basic '+key,
'Content-Type': 'application/x-www-form-urlencoded',
});
let options = { headers: headers };
return this.http.post<any>('https://api.sandbox.paypal.com/v1/oauth2/token',"grant_type=client_credentials", { headers: headers })
}
Explain me what is client id and secret. I am using sandbox client Id secret. i got this error.
zone-evergreen.js:2845 POST https://api.sandbox.paypal.com/v1/oauth2/token 401 (Unauthorized)
That is not a PayPal REST APP's clientId and secret. Get a pair for from the sandbox tab of https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Fapplications
Also, they must be Base64 encoded in your request
I am using rails api with puma as an application server and React js as frontend with nginx server as web server. The problem is while I make an api request, for couple of times the server responds with data in json format.
But, after certain request, the web server responds with status 200 ok with no data.When I try to access my data as response.data, I get response.data=""
Request Headers
Response Header
Api request
function fetchHolidays(year) {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'access-token': Cookie.get('accesstoken'),
'client': Cookie.get('client'),
'uid': Cookie.get('uid'),
'expiry': Cookie.get('expiry'),
'token-type': Cookie.get('tokentype')
}
}
return axios(`${baseURL.URL}${baseURL.PORT}/api/v1/holidays`,
requestOptions).then(response => {
return response
});
}
Whenever I attempt to make a PUT Request to Reddit API in order to add a friend, it fails and claims a JSON Parse Error 'JSON_PARSE_ERROR'. Nothing I do is working. Here is how I form the request.
Endpoint: /api/v1/me/friends/username
>>> Endpoint URL: PUT https://oauth.reddit.com/api/v1/me/friends/micheal
Authorization: Bearer <Access_Token>
// The response given:
{"fields": ["json"], "explanation": "unable to parse JSON data", "reason": "JSON_PARSE_ERROR"}
I have also tried the /api/friend/username endpoint and nothing works.
I had exactly the same problem, and your question led me to the solution.
The endpoint is expecting a json payload ACTUALLY NAMED "json." I'm not sure what language you're using, this is what it looks like in Node:
var options = {
url: 'https://oauth.reddit.com/api/v1/me/friends/mynewfriend',
headers: {
'User-Agent': 'Appname/1.0 by username',
'Authorization': "bearer " + <Access_Token>
},
json: {
'name': 'mynewfriend',
'notes': 'whatever notes you want to put',
}
};
request.put(options, function(error, response, body) {
blah blah blah
}
the json itself is described in https://www.reddit.com/dev/api/#PUT_api_v1_me_friends_{username}