is there anyway i can refresh spotify token in react? - javascript

I create a function that I can log in to my Spotify and get the access token and I create a function to refresh my token but it does not work properly when I pass it to the request function with Axios and it returns 400 or 404.
what should I do ?
here is my code :
const AUTH_URL =
" https://accounts.spotify.com/authorize?client_id=MY_ID&response_type=token&redirect_uri=http://localhost:3000/&scope=user-read-playback-state";
let Login = () => {
const spotifyHandle = (params) => {
const afterHashtag = params.substring(1);
const param = afterHashtag.split("&");
const paramsSplit = param.reduce((Para, currentPara) => {
const [key, value] = currentPara.split("=");
Para[key] = value;
return Para;
}, {});
return paramsSplit;
};
useEffect(() => {
if (window.location.hash) {
const { access_token, expires_in } = spotifyHandle(window.location.hash);
localStorage.clear();
localStorage.setItem("accessToken", access_token);
localStorage.setItem("expiresIn", expires_in);
}
});
return (
<div>
<a href={AUTH_URL}>
<button>Login</button>
</a>
</div>
);
};
here the refresh function:
let refresh = async () => {
const clientId = "id";
const clientSecret = "secret";
const headers = {
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: clientId,
password: clientSecret,
},
};
const data = {
grant_type: "client_credentials",
};
try {
const response = await axios.post(
"https://accounts.spotify.com/api/token",
qs.stringify(data),
headers
);
console.log(response.data.access_token);
return response.data.access_token;
} catch (error) {
console.log(error);
}
};

The Spotify API follows the OAuth 2.0 specs and it requires (as presented at this Spotify's documentation section):
grant_type to be equal to authorization_code
code to be equal to the authorization code returned from the initial request to the Account /authorize endpoint
redirect_uri This parameter is used for validation only (there is no actual redirection). The value of this parameter must exactly match the value of redirect_uri supplied when requesting the authorization code.
And a Authorization is also required at the request header, as stated at the docs:
Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic *<base64 encoded client_id:client_secret>*

Related

Refresh and Access token issue axios and react native

// I have the following code
// this is for refreshing the token and it works perfectly fine
export async function refreshTokenGenerator() {
const url = RefreshCurrentTokenURL;
const refreshTokenGeneratedFirst = newUser.getRefreshToken();
const response = await axios
.post(url, {
refreshToken: refreshTokenGeneratedFirst,
})
.catch((error) => {
console.log(
"🚀 ~ file: auth.js:118 ~ refreshTokenGenerator ~ error cant refresh token",
error
);
});
const newRefreshTokenGenerated = response.data.refreshToken;
// assign the new generated refresh token to the user model
// Refresh token loop works fine, no error from overriding the RT
const assignNewRefreshTokenToUserModel = newUser.setRefreshToken(
newRefreshTokenGenerated
);
// access token loops works fine,
// use it whenever u receive error 401 because it means that AT expired
const newAccessTokenGenerated = response.data.token;
return newAccessTokenGenerated;
}
// This part is for authenticating the menu and fetching the categories
async function authenticateMenu() {
const url = CategoriesAuthUrl;
let userToken = newUser.getToken();
const authStr = "Bearer ".concat(userToken);
const options = {
method: "GET",
headers: {
Authorization: authStr,
},
url: url,
};
const response = await axios(options).catch(async (error) => {
if (error.response.status === 401) {
// should call the refreshToken to refresh the access and refresh token
console.log("Error 401 unauthorized");
const newUserToken = await updateAccessToken();
userToken = newUserToken;
}
console.log(
"😡 ~ file: menu.js:28 ~ authenticateMenu ~ Error getting categories from API call",
error
);
});
const fetchedCategories = response.data;
console.log(
"🚀 ~ file: menu.js:40 ~ authenticateMenu ~ fetchedCategories",
fetchedCategories
);
return fetchedCategories;
}
// Get Categories
export async function getCategories() {
return authenticateMenu();
}
**In my HomeScreen I call the fetch categories like this**
useEffect(() => {
async function fetchCatHandler() {
const categoriesFetched = await getCategories().catch((error) => {
console.log(
"🟥 ~ file: HomeScreen.js:63 ~ fetchCatHandler ~ error from fetching categories from Home screen",
error
);
});
setParsedCategories(categoriesFetched);
}
fetchCatHandler();
async function getUserName() {
setUserName(await newUser.getUserName());
}
getUserName();
}, []);
// The code works perfectly fine until the access token is expired. Hence, whenever I receive error.response.status === 401 I call the function updateAccessToken which regenerates new access and refresh token and I save these in the user model
// when I fetch the categories it works fine up until the access token expires and I get the error [AxiosError: Request failed with status code 401].
// Any idea what am I missing/doing wrong??
export async function updateAccessToken() {
console.log("updateAccessToken called");
const newGeneratedTokenAfterExpiration = await refreshTokenGenerator();
newUser.setToken(newGeneratedTokenAfterExpiration);
const userToken = newGeneratedTokenAfterExpiration;
return userToken;
}
Once you've gotten an 401, the response is over. It doesn't change the response if you alter the token afterward. After getting a 401 and generating a new token, you should've sent a new request with the new token and return its response instead.
async function authenticateMenu() {
const url = CategoriesAuthUrl;
let userToken = newUser.getToken();
const authStr = "Bearer ".concat(userToken);
const options = {
method: "GET",
headers: {
Authorization: authStr,
},
url: url,
};
const response = await axios(options).catch(async (error) => {
if (error.response.status === 401) {
// should call the refreshToken to refresh the access and refresh token
console.log("Error 401 unauthorized");
const newUserToken = await updateAccessToken();
userToken = newUserToken;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// >>>>> This doesn't effect the current req/resposnse. After reseting the token you should send another request, with the new token
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
console.log(
"😡 ~ file: menu.js:28 ~ authenticateMenu ~ Error getting categories from API call",
error
);
});
const fetchedCategories = response.data;
console.log(
"🚀 ~ file: menu.js:40 ~ authenticateMenu ~ fetchedCategories",
fetchedCategories
);
return fetchedCategories;
}
Regardless, you shouldn't refresh the token after it has already expired. It's not secure
Best of luck with your project:)

Authenticatin for HERE RouteMatching API

I'm trying to use HERE's RouteMatching API of JavaScript
Current full code is here: https://github.com/code4history/ShibeContour/blob/d7e56a7/here_mapmatcher.js
For authentication, I coded like this:
import properties from "properties"
import hmacSHA256 from 'crypto-js/hmac-sha256.js'
import Base64 from 'crypto-js/enc-base64.js'
import fetch from 'node-fetch'
import {promises as fs} from "node:fs"
const getProps = async () => {
return new Promise((res) => {
properties.parse("./credentials.properties", {path: true}, function (error, data) {
res(data)
})
})
}
const getToken = async (props) => {
const nonce = `${performance.now()}`
const timestamp = Math.floor((new Date()).getTime() / 1000)
const parameters = [
"grant_type=client_credentials",
`oauth_consumer_key=${props["here.access.key.id"]}`,
`oauth_nonce=${nonce}`,
"oauth_signature_method=HMAC-SHA256",
`oauth_timestamp=${timestamp}`,
"oauth_version=1.0"
].join("&")
const encoding_params = encodeURIComponent(parameters)
const base_string = `POST&${encodeURIComponent(props["here.token.endpoint.url"])}&${encoding_params}`
console.log(base_string)
const signing_key = `${props["here.access.key.secret"]}&`
const hmac_digest = encodeURIComponent(Base64.stringify(hmacSHA256(base_string, signing_key)))
const headers = {
"Authorization": `OAuth oauth_consumer_key="${props["here.access.key.id"]}",oauth_nonce="${nonce}",oauth_signature="${hmac_digest}",oauth_signature_method="HMAC-SHA256",oauth_timestamp="${timestamp}",oauth_version="1.0"`,
"Cache-Control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded"
}
const body = `grant_type=client_credentials`
const response = await fetch(props["here.token.endpoint.url"], {
method: 'post',
body,
headers
})
return response.json()
}
This works well, I got authentication token successfully.
Like this:
{
access_token: 'eyJhbGciOiJSUzUxMiIsImN0eSI6IkpXVCIsImlzcyI6IkhFUkUiLCJhaWQiOiJIZ0NSaFV4...',
token_type: 'bearer',
expires_in: 86399,
scope: 'hrn:here:authorization::org...'
}
But even I used this access_token, route matching call causes authentication error.
Code is:
const main = async () => {
const props = await getProps()
const token_data = await getToken(props)
const body = await fs.readFile("gps/8DD83AC3-8B5A-4108-9CC0-2B78CF9936EC.kml", {encoding: "UTF-8"})
const headers = {
"Authorization": `Bearer ${token_data.access_token}`,
"Cache-Control": "no-cache",
"Content-Type": "application/octet-stream"
}
const response = await fetch(`https://routematching.hereapi.com/v8/calculateroute.json?routeMatch=1&mode=fastest;car;traffic:disabled&apiKey=${props["here.access.key.id"]}`, {
method: 'post',
body,
headers
})
const respond = await response.json()
console.log(respond)
}
main()
Error response was like this:
{
error: 'Forbidden',
error_description: 'These credentials do not authorize access'
}
What is wrong?
I can't imagine what is wrong.
Finally I found the reason
API URL is not match.
We can find many candidate urls,
https://fleet.api.here.com/2/calculateroute.json
https://routematching.hereapi.com/v8/calculateroute.json
etc...
but true working url is only
https://routematching.hereapi.com/v8/match/routelinks
which we can find in this document.
https://platform.here.com/services/details/hrn:here:service::olp-here:route-matching-8/api-ref
Once I changed API endpoint to this correct one, it works well.

Django + React Axios instance header conflict?

I have all my functions based views on django protected with #permission_classes([IsAuthenticated]) so I have to send a JWT as Bearer token on every request.
In the first version I was using this code:
import axios from 'axios';
import { decodeUserJWT } from '../../extras'
const user = JSON.parse(localStorage.getItem("user"));
var decoded = decodeUserJWT(user.access);
var user_id = decoded.user_id
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {Authorization: 'Bearer ' + user.access},
params: {userAuth: user_id}
});
export default instance;
Everything was working fine.
But then I added interceptors so I could handle the refreshToken process:
const setup = (store) => {
axiosInstance.interceptors.request.use(
(config) => {
const token = TokenService.getLocalAccessToken();
if (token) {
// const uid = await decodeUserJWT(token);
config.headers["Authorization"] = 'Bearer ' + token;
// config.headers["userAuth"] = uid;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
const { dispatch } = store;
axiosInstance.interceptors.response.use(
(res) => {
return res;
},
async (err) => {
const originalConfig = err.config;
if (originalConfig.url !== "/auth/token/obtain/" && err.response) {
console.log("TOKEN INTERCEPTOR");
// Access Token was expired
if (err.response.status === 401 && !originalConfig._retry) {
originalConfig._retry = true;
try {
const rs = await axiosInstance.post("/auth/token/refresh/", {
refresh: TokenService.getLocalRefreshToken(),
});
const { access } = rs.data;
dispatch(refreshToken(access));
TokenService.updateLocalAccessToken(access);
return axiosInstance(originalConfig);
} catch (_error) {
return Promise.reject(_error);
}
}
}
return Promise.reject(err);
}
);
};
What happens?
When I add the line config.headers["userAuth"] = uid; the django server console starts showing up that when the react app tries to access the routes it gets a Not Authorized, and when I take that line off de code ... it works fine.
I also tried to pass the param userAuth in the axios.create and keep only the Bearer config inside the interpector code, but still no positive result, the code with the interpector code only works when I take off the userAuth line from axios.
Any ideia on why this is happening and how can I fix this?

Session cookie from node-fetch is invalid?

I am writing a javascript program (for a github action) right now but ran into a problem.
I was trying to log into www.overleaf.com and access the page https://www.overleaf.com/project after generating a session cookie by sending a POST request to https://www.overleaf.com/login with my credentials and the csrf token.
The response contained the requested token in the set-cookie header as expected, however, when I tried to access https://www.overleaf.com/project via GET, I get redirected back to https://www.overleaf.com/login
When copying a session cookie saved in my browser, the request works just fine as expected.
I tried doing the same thing in the command line with cURL and it worked there.
I am fairly certain my authentication request is accepted by Overleaf's server, because I have tried intentionally incorrectly sending the password or the csrf token and in both cases, the response does not give me a new session cookie but sends the old one.
If anyone has any clue what is going wrong, I'd be very thankful for your input.
This is what worked in the terminal, which I'm trying to replicate in javascript with node-fetch:
curl -v --header "Content-Type: application/json" --cookie "GCLB=someothercookie;overleaf_session2=firstsessioncookie" --data '{"_csrf":"the_csrf_token", "email": "MYEMAIL", "password":"MYPASSWORD"}' https://www.overleaf.com/login
to get the cookie and csrf token and
curl -v https://www.overleaf.com/project --cookie "overleaf_session2=returnedsessioncookie; GCLB=someothercookie" as the request that returns the html page of my projects.
This is my javascript code, I have double, triple, quadruple checked it but I think I'm missing something.
const fetch = require("node-fetch");
const parser = require("node-html-parser");
const scparser = require("set-cookie-parser");
async function run() {
const email = process.env.EMAIL;
const password = process.env.PASSWORD;
var cookies = await login(email, password);
console.log(await all_projects(cookies));
}
async function login(email, password) {
const login_get = await fetch("https://www.overleaf.com/login");
const get_cookies = login_get.headers.raw()["set-cookie"];
const parsed_get_cookies = scparser.parse(get_cookies, {
decodeValues: false
});
const overleaf_session2_get = parsed_get_cookies.find(
(element) => element.name == "overleaf_session2"
).value;
const gclb = parsed_get_cookies.find(
(element) => element.name == "GCLB"
).value;
console.log("overleaf_session2_get:", overleaf_session2_get, "gclb:", gclb);
const get_responsetext = await login_get.text();
const _csrf = parser
.parse(get_responsetext)
.querySelector("input[name=_csrf]")
.getAttribute("value");
login_json = { _csrf: _csrf, email: email, password: password };
console.log(login_json);
const login_post = await fetch("https://www.overleaf.com/login", {
method: "post",
body: JSON.stringify(login_json),
headers: {
"Content-Type": "application/json",
"Cookie": "GCLB=" + gclb + ";overleaf_session2=" + overleaf_session2_get
}
});
const post_cookies = login_post.headers.raw()["set-cookie"];
const parsed_post_cookies = scparser.parse(post_cookies, {
decodeValues: false
});
const overleaf_session2_post = parsed_post_cookies.find(
(element) => element.name == "overleaf_session2"
).value;
console.log(
"successful:",
overleaf_session2_get != overleaf_session2_post ? "true" : "false"
);
console.log(await fetch("https://www.overleaf.com/project", {
headers: {
"Cookie": "overleaf_session2=" + overleaf_session2_post
}
}))
return "overleaf_session2=" + overleaf_session2_post;
}
async function all_projects(cookies) {
const res = await fetch("https://www.overleaf.com/project", {
headers: {
Cookie: cookies
}
});
return res;
}
run();
Yes your authentication request is probably valid however this is likely to be a security issue which browsers do not allow you to do such thing and freely access another website's cookie.
Browsers do not allow you to access other domain's cookies, If they did then web would be an unsafe place because for example Stackoverflow could access my Facebook account cookie and extract my personal information.
I fixed my issue by not using node-fetch and switching to https.
Here is what worked:
async function login(email, password) {
//GET login page
const get = await get_login();
//get necessary info from response
const csrf = parser
.parse(get.html)
.querySelector(`meta[name="ol-csrfToken"]`)
.getAttribute("content");
const session1 = scparser
.parse(get.headers["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "overleaf_session2").value;
const gclb = scparser
.parse(get.headers["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "GCLB").value;
//POST login data
const post = await post_login(csrf, email, password, session1, gclb);
//get necessary data from response
const session2 = scparser
.parse(post["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "overleaf_session2").value;
//GET new csrf token from project page
const projects = await get_projects(session2, gclb);
const csrf2 = parser
.parse(projects.html)
.querySelector(`meta[name="ol-csrfToken"]`)
.getAttribute("content");
//return data
return {
session: session2,
gclb: gclb,
csrf: csrf2,
projects: projects.html
};
}
async function get_login() {
const url = "https://www.overleaf.com/login";
return new Promise((resolve) => {
https.get(url, (res) => {
var data;
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve({ html: data, headers: res.headers });
});
});
});
}
async function get_projects(session2, gclb) {
const url = "https://www.overleaf.com/project";
return new Promise((resolve) => {
https.get(
url,
{ headers: { Cookie: `GCLB=${gclb};overleaf_session2=${session2}` } },
(res) => {
var data;
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve({ html: data, headers: res.headers });
});
}
);
});
}
async function post_login(_csrf, email, password, session1, gclb) {
const url = "https://www.overleaf.com/login";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Cookie: `GCLB=${gclb};overleaf_session2=${session1}`
}
};
const postData = {
_csrf: _csrf,
email: email,
password: password
};
return new Promise((resolve) => {
var req = https.request(url, options, (res) => {
resolve(res.headers);
});
req.on("error", (e) => {
console.error(e);
});
req.write(JSON.stringify(postData));
req.end();
});
}

Why does my Auth0 API call give a 403 error when trying to delete a user?

I'm trying to integrate Auth0.com, and I've written a function that should unlink an identity and then delete it.
The unlinking works, but I keep getting a 403 error when trying to delete the unlinked identity.
The Auth0 API docs (https://auth0.com/docs/api/management/v2#!/Users/delete_users_by_id) say a 403 error is due to either rate limits, insufficient scopes, or user not matching the bearer token.
I think I added the correct scopes to the auth0 client, I'm very sure I'm not hitting rate limits, so it must be the mismatching bearer token.
But I don't understand how that could be?
Can you take a look at what I have and tell me what's gone wrong?
P.S. In case it matters, I'm using auth0-spa.js not the standard auth0.js. More info here.
This is the code I'm working with:
function(properties, context) {
// Load any data
const domain = context.keys.auth0_domain;
const client_id = context.keys.auth0_client_id;
const connection = properties.connection;
const auth0_user_id = properties.auth0_user_id;
//Do the operation
const auth0 = new Auth0Client({
domain: domain,
client_id: client_id,
audience: `https://${domain}/api/v2/`,
scope: "openid email profile read:current_user update:current_user_identities delete:users delete:current_user",
});
const auth0_user_obj = {
id: auth0_user_id
};
const getUserProfile = async (userId) => {
const token = await auth0.getTokenSilently();
const response = await fetch(
`https://${domain}/api/v2/users/${userId}`, {
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return await response.json();
};
const getSecondaryIdentity = async () => {
const auth0user = await getUserProfile(auth0_user_id);
const secondary_identity = auth0user.identities.find(i => i.connection === connection);
return secondary_identity;
}
const unlinkDeleteAccount = async () => {
const secondaryIdentityObj = await getSecondaryIdentity();
const {
provider,
user_id
} = secondaryIdentityObj;
const accessToken = await auth0.getTokenSilently();
const {
sub
} = await auth0.getUser();
await fetch(
`https://${domain}/api/v2/users/${sub}/identities/${provider}/${user_id}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const secondUserId = provider + '|' + user_id;
await fetch(
`https://${domain}/api/v2/users/${secondUserId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
};
unlinkDeleteAccount();
}

Categories

Resources