I'm using Postman and can generate a new token with the "Get new access token" button. How to create a function that updates my token current?
This is my current function:
def access_token():
url = "my_url"
token = "my_current_token"
payload = ""
headers = {
'Authorization': f'Bearer {token}',
'Cookie': 'my_cookie'
}
response = requests.request("GET", url, headers=headers, data=payload)
return response.json()
var user = pm.globals.get("clientId");
var pw = pm.environment.get("clientSecret");
var grantTypeAndScope = "grant_type=client_credentials&scope=scopes"
pm.sendRequest({
url: "https://"+pm.environment.get("host")+"/as/token.oauth2",
method: 'POST',
body: grantTypeAndScope,
header: {
'Authorization': "Basic " + Buffer.from(user+':'+pw).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
}
}, function (err, res) {
if (err === null) {
console.info(res);
pm.environment.set('auth_token', res.json().access_token)
} else {
console.error(err);
}
});
Then in the auth tab of my api requests I set the auth type to bearer and use the variable {{auth_token}}
I actually have the javascript to refresh my token in my pre-request tab at the collection level, so it grabs a new token with each request. Not optimal, but I never have to worry about an expired token.
Related
Hi I've been trying to do some sentiment analysis from google sheets. Here is my code:
function getSentiment(text) {
var apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://language.googleapis.com/v1/documents:analyzeSentiment?key=" + apiKey;
var data = {
document: {
type: "PLAIN_TEXT",
content: text
}
};
var options = {
method: "post",
contentType: "application/json",
headers: {
"Authorization": "Bearer " + apiKey
},
payload: JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
return result.documentSentiment.score;
}
Here is what comes up:
Error
Exception: Request failed for https://language.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response) (line 18).
I think the key is right (changed here for obvious reasons) and enabled so I'm not sure where I go from here. Any ideas? Thanks
I'm working through this tutorial on creating an app that uses the Spotify API. Everything was going great until I got to the callback portion of authenticating using the authentication code flow.
(I do have my callback URL registered in my Spotify app.)
As far as I can tell, my code matches the callback route that this tutorial and others use. Significantly, the http library is axios. Here's the callback method:
app.get("/callback", (req, res) => {
const code = req.query.code || null;
const usp = new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
});
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
data: usp,
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
},
})
.then(response => {
console.log(response.status); // logs 200
console.log(response.data); // logs encoded strings
if (response.status === 200) {
res.send(JSON.stringify(response.data))
} else {
res.send(response);
}
})
.catch((error) => {
res.send(error);
});
Though the response code is 200, here's a sample of what is getting returned in response.data: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003E�˒�0\u0000Ee�uS\u0015��\u000e�(\b\u0012h\u0005tC%\u0010\u0014T\u001e�����0��^:���p\u0014Ѻ\u000e��Is�7�:��\u0015l��ᑰ�g�����\u0"
It looks like it's encoded, but I don't know how (I tried base-64 unencoding) or why it isn't just coming back as regular JSON. This isn't just preventing me logging it to the console - I also can't access the fields I expect there to be in the response body, like access_token. Is there some argument I can pass to axios to say 'this should be json?'
Interestingly, if I use the npm 'request' package instead of axios, and pass the 'json: true' argument to it, I'm getting a valid token that I can print out and view as a regular old string. Below is code that works. But I'd really like to understand why my axios method doesn't.
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
res.clearCookie(stateKey);
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
},
headers: {
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token;
const refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { Authorization: 'Bearer ' + access_token },
json: true,
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' + querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}));
} else {
res.redirect(`/#${querystring.stringify({ error: 'invalid_token' })}`);
}
});
});
You need to add Accept-Encoding with application/json in axios.post header.
The default of it is gzip
headers: {
"content-type": "application/x-www-form-urlencoded",
'Accept-Encoding': 'application/json'
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
}
//Am i doing wrong way?
Im fetching the data at first but after 1-2days of not using the app, fetching data is not working anymore.
Future<List<TopCourses>> fetchTopCourseList() async {
final prefs = await SharedPreferences.getInstance();
final accessToken = prefs.getString('access_token');
final response = await client.get(
URL_STUDENT_GET_TOP_COURSES,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + accessToken,
},
);
if (response.statusCode < 200 || response.statusCode > 400) {
throw Exception('Failed to Load');
} else {
return compute(topcourseFromJson, response.body);
}
}
List<TopCourses> topcourseFromJson(String str) {
final jsonData = json.decode(str);
return new List<TopCourses>.from(
jsonData["top"].map((x) => TopCourses.fromJson(x)));
}
Either your accessToken has expired, or the accessToken you're trying to get from SharedPreferences has been wiped from your app data.
trying checking that your access token is not null
and the token has not to expired
I have the following code whitch refreshes JWT auth token:
axios.defaults.headers.common["Authorization"] = 'Bearer ' + jwt.getToken();
axios.interceptors.request.use((config) => {
let originalRequest = config
if (jwt.isTokenExpired() && api.unauthPaths.indexOf(config.url) == -1) {
return api.refreshToken()
.then(res => {
if (res.data.error == 'TOKEN_BLACKLISTED' && res.headers.authorization) {
let token = res.headers.authorization.slice(7)
console.log(`Current token: ${ axios.defaults.headers.common["Authorization"]}`)
axios.defaults.headers.common["Authorization"] = 'Bearer ' + token;
//in this log token is new, but each next request uses the old token
console.log(`New token: ${ axios.defaults.headers.common["Authorization"]}`)
alert('token was refreshed')
return Promise.resolve(originalRequest)
} else {
jwt.destroyToken()
jwt.destroyExpiredTime()
store.dispatch('auth/destroyToken')
router.push({name: 'login'})
return Promise.reject()
}
})
}
return config
}, (err) => {
return Promise.reject(err)
})
I need to update the token when I get a new one from the server. But when I use
axios.defaults.headers.common["Authorization"] = 'Bearer ' + token;
In code above, axios does not change the default token to new. Each next request comes with an old token. How to set a new token from the axios interceptors?
You have probably already fixed this issue. But for people that also face this issue here is the solution:
if this is your original request. it also uses the original headers
const originalRequest = error.config
you have to change them when you receive your new token:
originalRequest.headers.Authorization = `Bearer ${res.token}`
however you also have to set the default headers again for future calls:
axios.defaults.headers.common["Authorization"] = `Bearer ${res.token}`
I was trying to make an API call to another domain, which has no-cors enabled.
The API call was made something like this:
let url = `https:sampleApiUrl?params=xxxx`;
console.log("hitting dashboard url")
get(url, token)
.then((resp) => {
console.log("resp", resp)
})
.catch((error) => {
console.log(error)
})
This API call, subsequently calls a 'get' method:
const get = (url, authToken) => {
return baseFetch(url, 'get', false, authToken).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
});
}
Now, this get method calls a baseFetch method:
const baseFetch = (url, verb, body, authToken) => {
const request = {
method: verb,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'credentials': 'include'
},
mode: 'cors'
}
if (authToken){
// adding x-access-token in the request header
request.headers['x-access-token'] = authToken;
}
if (body){
request.body = JSON.stringify(body);
}
return fetch(url, request);
}
Now, when this API call is requested, I can't see the "x-access-token" populated in the browser network call.
No x-access-token in request-headers
Also, I am not sure why I get status code 204 in response.
Calling this API from postman and directly from browser or calling as a curl request, returns the correct response.
Thanks
Looking at the image, you are looking at the headers for pre flight OPTIONS method and not the GET method. The pre flght request is generated by the browser and it never has any custom header. therefore it did not have the x-access-token in its headers.