Discord oauth2 /users/#me/guilds error 401 - javascript

It is supposed to get all the guilds a user is joined in. It gets the bearer auth right, but it always errors with code 401. When using a external API (https://reqbin.com/) with auth to test the discord API it also gives the same error 401.
This is the code:
let discordCode = window.location.href
let code = discordCode.split("?code=")
if(code && code.length > 0){
discordCode = code[code.length-1]
}
console.log(discordCode)
fetch("https://discord.com/api/users/#me/guilds",{method: 'GET',headers: {
"Authorization": `Bearer ${discordCode}`,
}}).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})
/*fetch(`/discordProxy/${discordCode}`).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})*/
$("#connect_top_button").click(function(){
window.location.href = "https://discord.com/api/oauth2/authorize?client_id=955915443405729844&redirect_uri=http%3A%2F%2F130.162.37.209%2Fservers&response_type=code&scope=identify%20guilds"
})
The oauth2 scopes I gave to the app are: identify, email, guilds
Edit: Actually, it seems that all the auth tokens from the oauth2 don't work. Weird

You must get discord token and use it in authorization:
"Authorization": `Bearer ${await getTokenDiscord()}`
here is my example of getting the discord token:
async getTokenDiscord() {
const params = new URLSearchParams()
params.append('client_id', CLIENT_ID)
params.append('client_secret', CLIENT_SECRET)
params.append('grant_type', 'authorization_code')
params.append('code', YOUR_DISCORD_CODE)
params.append('redirect_uri', REDIRECT_URL)
params.append('scope', 'identify')
const resp = await fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
}
})
return await resp.json()
}
It's not the best example of how to do this, but it's the way it works for me

Related

Trustpilot Authentication Error Unknown grant_type

I want to use Trustpilot API to send email review invitation. Before making that call, I need to get an access token. I'm following Trustpilot's documentation in the function below. I keep getting this error of Unknown grant_type. According to the documentation, it is supposed to be set to "password" to get the token and it is not working. I tried this solution but it is not working for me. I can't seem to know what's causing the error especially that it is very general.
trustPilot.getAuthToken = async () => {
let apiKey = process.env.TRUSTPILOT_API
let secrect = process.env.TRUSTPILOT_SECRET
let baseEncoded = Buffer.from(`${apiKey}:${secrect}`).toString('base64')
console.log(baseEncoded, 'base')
let authToken = null
try {
authToken = await axios({
method: 'POST',
url: `https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken`,
headers: { Authorization: 'Basic ' + baseEncoded, 'Content-Type': 'application/x-www-form-urlencoded' },
content: `grant_type=password&username=${process.env.TRUSTPILOT_EMAIL}&password=${process.env.TRUSTPILOT_PASSWORD}`,
})
console.log(authToken, 'auth')
} catch (error) {
console.log(error.response, 'err')
throw { code: '404' }
}
return authToken
}
Please take a look at axios documentation. You are passing content: instead of data:. Axios call should be like this:
authToken = await axios({
method: 'POST',
url: `https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken`,
headers: { Authorization: 'Basic ' + baseEncoded, 'Content-Type': 'application/x-www-form-urlencoded' },
data: `grant_type=password&username=${process.env.TRUSTPILOT_EMAIL}&password=${process.env.TRUSTPILOT_PASSWORD}`,
})

Fetch requests for token not passed to next fetch request, 401 returned

I'm reaching out to an endpoint with fetch to get a bearer token that will then be used in another fetch request for authentication. I've used Postman first and verified that the endpoints I'm accessing are working, however with my fetch requests below I get a 401.
I have checked in the console that the Authorization is updated after the first fetch and it's passed to the second however I continue to get a 401.
The first call reaches to ./auth and a bearer token is returned. That token is passed off to the next fetch request and but I am getting a 401.
What am I missing or doing wrong, a second pair of eyes could help.
const token = "./auth";
const listings = "./listings";
let clientHeaders = new Headers();
let raw = JSON.stringify({
email: "fake#account.com",
password: "12345",
});
clientHeaders.append("Authorization", "");
clientHeaders.append("Content-Type", "application/json");
clientHeaders.append("Cookie", "");
let req = {
method: "POST",
headers: clientHeaders,
body: raw,
redirect: "follow",
};
fetch(token, req)
.then((response) => response.json())
.then((result) => {
return fetch(listings, {
method: "GET",
headers: {
Authorization: result.token,
"Content-Type": "application/json",
},
});
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(JSON.parse(data));
})
.catch((error) => {
console.log("error: ", error);
});
You likely need to include the literal word "Bearer" and a space preceding the token in the header:
{
Authorization: `Bearer ${result.token}`
}
// or
{
Authorization: "Bearer " + result.token
}

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();
}

Axios get request response with 403 error forbidden

I'm new in react . Trying to make "get" request and getting 403 error forbidden, "Response for preflight does not have HTTP ok status.". In network tab in Request Method instead of "get" method shows "options". What could be the problem? Cors already open , problem with token
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer + ${token}`,
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
that's how I'm saving token. May be I'm not correctly saving it in localStorage? But when console.log it displays fine
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************/get-token", formdata)
.then(res => {
if (res.data) {
console.log(res.data)
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
I see a problem in your Bearer token
you write it:
Authorization: `Bearer + ${token}`
but it should be :
Authorization: `Bearer ${token}`,
and the full answer is :
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
Do it like this:
let token = localStorage.getItem("token")
axios.defaults.headers.common['Authorization'] = token
axios
.get("http://dev.*****************get-template")
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
This is due to CORS issue.
To solve this you need to set Access-Control-Allow-Origin header on your server side, allowing the domain from which you are sending the request or you can set it to *

Axios not passing headers on requests

I'm building a VueJS application and I'm using JSON web tokens as my auth system. When I log the user, I store the token with localStorage and works fine. I check the headers and it's in the 'Authorization' param.
I pass with axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')
I see the headers and it's okay. But when I execute a get request to an protected route in my API, return 'unauthorized'. But when I pass the header with token manually in the request, works fine.
Somebody know how to pass the header automatically when executing some request?
try this..
//in get request
const auth = {
headers: {Authorization:'JWT ' + localStorage.getItem('token')}
}
axios.get('http://yourapi.com',auth).then(result => {
console.log(result.data)
})
//in post request
const auth = {
headers: {Authorization:'JWT ' + localStorage.getItem('token')}
}
//note:auth will be 3rd parameter in post request
axios.post('http://yourapi.com',{somekey:'some value'},auth).then(result => {
console.log(result.data)
})
You can use axios.create to create a new axios instance with a config object, including the headers. The configuration will be used for each subsequent calls you make using that instance.
Something like this worked for me:
var App = Vue.component('app', {
mounted () {
this.response = null
this.axiosInstance = axios.create({
baseURL: 'http://localhost:5000/',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
},
data () {
return {
response: this.response,
}
},
methods: {
login () {
this.axiosInstance.post('login', {username: 'test', password: 'test'})
.then(resp => {
this.accessToken = resp.data.access_token
this.axiosInstance.defaults.headers['Authorization'] = 'Bearer ' + this.accessToken
})
.catch(err => this.response = err.response.status + ' ' + err.response.statusText)
},
protected () {
this.axiosInstance.get('protected')
.then(resp => this.response = resp.data)
.catch(err => this.response = err.response.status + ' ' + err.response.statusText)
}
},
template: '<div><button #click="login">Connect</button><button #click="protected">Protected</button></div>'
})
interceptor which includes your auth token in every request as an Authorization header:
axios.interceptors.request.use(
function(config) {
const token = localStorage.getItem('token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
},
function(error) {
return Promise.reject(error)
}
)
you could place it in the main file, for example main.js
Check whether server get token from header of "Authorization"
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
if No. 2 works, then you may want to execute apis even if web is refreshed, then follow:
axios.interceptors.request.use(function (config) {
const token = 'Bearer ' + localStorage.getItem('token');
config.headers.Authorization = `Bearer ${token}`;
return config;
});
For me issue was with capital Headers vs headers.
Should be lower case. My IDE got me the wrong autocomplete (i.e. with capital H)
This works:
await axios.get(url, {
headers: { 'x-custom-header': 'super header value' }
});
This doesn't!
await axios.get(url, {
Headers: { 'x-custom-header': 'super header value' }
});

Categories

Resources