how to use axios request to exchange google authorization code for access and refresh tokens - axios

I am working on a expo react native app, I tried to implement the google login function.
I am following this expo-auth-session docs https://docs.expo.dev/guides/authentication/#google,
I've successfully gotten the authorization code using the code below:
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: google_client_id,
scopes: [
"https://www.googleapis.com/auth/drive",
],
responseType: "code",
shouldAutoExchangeCode: false,
redirectUri: REDIRECT_URI,
extraParams: {
access_type: "offline"
},
})
useEffect(() => {
if (response?.type === 'success'){
console.log(response.params.code)
}
},
[response]);
response.params.code
is the authorization code that returns to me.
I am now trying to use this authorization code to send a post request to the google token endpoint to exchange for a token. I am following this document here: https://developers.google.com/identity/protocols/oauth2/native-app
I tried the following 2 methods, but both of them gives me an axios error code of 400. I am not sure what's wrong with my code. Can someone please help me with it please, thanks!
axios.request({
method: 'POST',
url: 'https://oauth2.googleapis.com/token',
headers: {
'content-type': 'application/x-www-form-urlencoded',
//Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
},
data: {
grant_type: 'authorization_code',
code: response.params.code,
redirect_uri: REDIRECT_URI,
client_id: google_client_id,
client_secret: google_client_secret
}
}).then((res) => {
console.log(res.data)
}).catch(err => {console.log(err)})
and
axios.request({
method: 'POST',
url: 'https://oauth2.googleapis.com/token',
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
},
data: {
grant_type: 'authorization_code',
code: response.params.code,
redirect_uri: REDIRECT_URI,
}
}).then((res) => {
console.log(res.data)
}).catch(err => {console.log(err)})

Related

How to use refresh_token in #nuxtjs/auth-next?

I'm sorry if there are any mistakes because my native language is not English.
I'm using this module with the configuration below, but when I run auth/rerfresh it's requesting using the access_token.
I get the Authorization header on the server side, and when I decode the JWT, the content is access_token.
I am assuming that with this module, when the access_token expires, it will set the refresh_token in the Authorization header and run api/auth/refresh.
Please let me know if there are any mistakes...
auth: {
redirect: {
login: '/login',
logout: '/login',
callback: '/login',
home: '/'
},
strategies: {
local: {
scheme: 'refresh',
autoLogout: true,
token: {
property: 'access_token',
maxAge: 1800,
global: true,
// type: 'Bearer'
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30
},
user: {
property: false,
autoFetch: true
},
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"grant_type": "password"
},
},
refresh: { url: '/auth/refresh', method: 'get' },
logout: { url: '/auth/logout', method: 'post', },
user: { url: '/auth/me', method: 'get', propertyName: false }
}
},
[/auth/login response]
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZXhwIjoxNjc0NTI1OTA3LCJzdGFmZl9pZCI6ImFiY2RlMTIzIn0.68BPtgr93lwHgSfSQxieEJUJtGPe9bafQMpnbdHEqy0",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaF90b2tlbiIsImV4cCI6MTY3NzExNzg0Nywic3RhZmZfaWQiOiJhYmNkZTEyMyJ9.71B1iofZIsoaduUOH7ahuTi2gc2NCp5fpsRrsZaGPMg",
"token_type": "bearer"
}
[Cookies]
Name
Value
Expires/Max-Age
Priority
auth._token_expiration.local
1674525907000
Session
Medium
auth._refresh_token.local
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaF90b2tlbiIsImV4cCI6MTY3NzExNzg0Nywic3RhZmZfaWQiOiJhYmNkZTEyMyJ9.71B1iofZIsoaduUOH7ahuTi2gc2NCp5fpsRrsZaGPMg
Session
Medium
auth._token.local
Bearer%20eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZXhwIjoxNjc0NTI1OTA3LCJzdGFmZl9pZCI6ImFiY2RlMTIzIn0.68BPtgr93lwHgSfSQxieEJUJtGPe9bafQMpnbdHEqy0
Session
Medium
auth._refresh_token_expiration.local
1677117847000
Session
Medium
auth.strategy
local
Session
Medium
I have tried various auth settings in nuxt.config.js but could not solve the problem.
(For example, autoLogout: false, etc.)
I tried running this.$auth.refreshTokens() but , Authorization header seems to be set to access_token.
As you can see in the image above, the token was received and seems to be stored in the cookie.
refresh: { url: '/auth/refresh', method: 'post' },
Changed as above.
I expected refresh_token to be included in the Authorization header, but it seems to be included in the request body.
Changed to refer to the request body in server-side processing.

GitHub GraphQL keeps returning POST https://api.github.com/graphql 401 error

I have been trying for hours to fetch the data of some of my repositories but I keep getting this error
'POST https://api.github.com/graphql 401'
My Code
const githubData = {
token: "my token",
username: "mikechibuzor",
};
const body = {
query: `query {
user(login: "mikechibuzor"){
bio,
avatarUrl,
repositories(first: 20, orderBy: {field: CREATED_AT, direction: DESC}){
nodes{
name,
description,
forkCount,
languages(first: 100){
nodes{
name
}
}
}
}
}
}`,
};
const baseUrl = "https://api.github.com/graphql";
const headers = {
'Authorization': 'bearer ' + githubData.token,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
};
fetch(baseUrl, {
method: "POST",
Headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
.then((response) => response.json())
.then((data) => console.log(data.data))
.catch((err) => console.log(JSON.stringify(err)));
What am i not doing right?
Maybe just a typo – try the following:
fetch(baseUrl, {
method: "POST",
// lowercase 'h' for headers
headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
// ...
In case that still doesn't work check your scopes for your access token. GitHub gives you detailed control about what kind of actions you want to allow with a specific token and what not.

How can I make a post request to Roblox?

I am using Axios to post a request to a Roblox API endpoint (https://friends.roblox.com/v1/users/1/follow) but it did not work, it keeps returning a 401 status code. Picture here
Here is my code:
axios.post('https://friends.roblox.com/v1/users/1/follow', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookie,
},
})
.then(data => console.log(data))
.catch(err => console.log(err));
I found out an answer. I needed to get the X-CSRF-TOKEN first. Here's the code to get the X-CSRF-TOKEN if you need help!
fetch('https://auth.roblox.com/v2/logout', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': '',
'Cookie': cookie,
},
})
.then(data => {
let csrfToken = data.headers.get('x-csrf-token');
console.log(csrfToken);
})
.catch(err => console.log(err));

Can't make a POST request using axios

The error message I get is
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
http-header.js
"import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:5000",
headers: {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
AuthService.js
import axios from '../http-header.js'
export default {
login : user => {
return axios.post('/user/login', user)
.then(res => {
if(res.status !== 401)
return res.json().then(data => data)
else {
return {isAuthenticated: false, user: {username: "", role: ""}}
}
})
}
}
You have to add 'Access-Control-Allow-Origin': '*' to your backend.

Axios post, missing grant type

Getting data: { error: 'invalid_request', error_description: 'Missing grant type' } }
Content-Type is correct, not sure what is wrong
return axiosInstance({
method: 'post',
url: axiosInstance.defaults.baseURL + '/oauth/token',
data: {
"grant_type": "vapi_key",
key: api_key
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
Edit: This is called via NodeJS
This is an open issue about this matter. Try this solution, Which suggest stringifing the data (you can use qs package for it) :
import qs from 'qs';
return axiosInstance({
method: 'post',
url: axiosInstance.defaults.baseURL + '/oauth/token',
data: {
"grant_type": "vapi_key",
key: api_key
},
data: qs.stringify({
"grant_type": "vapi_key",
key: api_key
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})