I am trying to build a simple authentication library, and I am using axios instead of library built by auth0. I am unable to fetch the userdata using the access code. I am also using google provider for authentication.
import axios from 'axios'
export default class Auth {
constructor(
private domain: string,
private client_id: string,
private redirect_uri: string
) {}
startAuthFlow(): string {
const params = new URLSearchParams({
response_type: 'code',
client_id: this.client_id,
redirect_uri: this.redirect_uri,
scope: 'offline_access'
})
const authURI = `https://${this.domain}/authorize?${params.toString()}`
return authURI
}
async handleCallback(code: string) {
return await this.exchangeCodeForToken(code)
}
async getUserInfo(accessToken: string) {
const userInfoEndpoint = `https://${this.domain}/userinfo`
try {
const response = await axios.get(userInfoEndpoint, {
params: {
scope: "openid profile email"
},
headers: {
Authorization: `Bearer ${accessToken}`
}
})
return response.data
} catch (error) {
throw error
}
}
async refreshToken(refresh_token: string) {
const tokenEndpoint = `https://${this.domain}/oauth/token`
const payload = {
grant_type: 'refresh_token',
client_id: this.client_id,
refresh_token
}
try {
const response = await axios.post(tokenEndpoint, payload, {
headers: {
'Content-Type': 'application/json'
}
})
return response.data
} catch (error) {
throw error
}
}
private async exchangeCodeForToken(code: string) {
const tokenEndPoint = `https://${this.domain}/oauth/token`
const payload = {
grant_type: 'authorization_code',
client_id: this.client_id,
client_secret: 'B60OCXAoe7KqIkwLTqHeDlLBMFYtMh6kLw7WAXJl0qCMXDyJzROHyAJr449LKXz9',
code,
redirect_uri: this.redirect_uri,
scope: 'openid profile email'
}
try {
const reponse = await axios.post(tokenEndPoint, payload)
const { access_token, id_token, refresh_token } = reponse.data
return { access_token, id_token, refresh_token }
} catch (error) {
throw error
}
}
}
I am using this library in a express application to test it.
const express = require('express')
const Auth = require('../auth').default
const auth = new Auth('dev-k2t4k3888k1ic1rm.us.auth0.com', 'Zg2GuO5NfJMFVbZsbRVn8naqFUJNKZdU', 'http://localhost:3000/callback')
const app = new express()
app.get('/', (req,res) => {
return res.send('Hello')
})
app.get('/login', (req, res) => {
res.redirect(auth.startAuthFlow())
})
app.get('/callback', async (req, res) => {
const { code } = req.query
try {
const { access_token } = await auth.handleCallback(code)
console.log(access_token)
const user = await auth.getUserInfo(access_token)
console.log("USER: ", user)
res.redirect('/')
} catch (error) {
console.log(error)
return res.status(404).send(error)
}
})
app.listen(3000, () => {
console.log('Server running on port 3000')
})
Can anyone help me why I am not able to fetch the user data? I can see the userdata in my auth0 dashboard