oauth authorization and token not functioning as expected in JS script - javascript

My application uses the Zoom API with OAuth.
The process is well put in the zoom developer docs and I followed them
I created a zoom app in the developer's account and got the clientID and clientSecret.
First we need to get the Authorization code from "https://zoom.us/oauth/authorize". With this code we can get the access token from "https://zoom.us/oauth/token". Pretty straight forward. I tried it on Postman and all the APIs work.
My JS code below doesn't work and keeps failing to do this task.
const express = require('express');
const axios = require('axios');
let token = null;
const app = express();
const clientId = 'ADqR4l7KTfMmXXXXXXXX';
const clientSecret = 'mhVytefIFS4fSqQ3XXXXXXXXXX';
const redirectURL = 'http://localhost:3000/oauth-callback'
app.get('/', (req, res) => {
res.redirect(`https://zoom.us/oauth/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectURL}`);
});
app.get('/oauth-callback', (req, res) => {
const body = {
client_id: clientId,
client_secret: clientSecret,
code: req.query.code
};
const opts = { headers: { accept: 'application/json' } };
axios.post(`https://zoom.us/oauth/token`, body, opts).
then(res => res.data['access_token']).
then(_token => {
console.log('My token:', token);
token = _token;
res.json({ ok: 1 });
}).
catch(err => res.status(500).json({ message: err.message }));
});
app.listen(3000);
console.log('App listening on port 3000');
zoom dev acct:
zoom dev account
Error message:
Error message
How can I get the access token? Please help me find my errors in the code.

Related

JWT token returning undefined in MERN application

I am using JWT token for authentication in my MERN app. when i click on this endpoint "http://127.0.0.1:1000/api/v1/users/login" in postman to login a user and this endpoint "http://127.0.0.1:1000/api/v1/users/verify" to verify a user's token, the token is returned. However, when i do the same operation in my react frontend app, the token returns undefined. Please what am i doing wrong? Here is my React code. P.S the token is stored in the cookies.
function Welcome() {
const [user, setUser] = useState("");
const sendRequest = async () => {
const res = await axios
.get("http://127.0.0.1:1000/api/v1/users/verify", {
withCredentials: true,
})
.catch((err) => console.log(err));
const data = await res.data;
console.log("RESPONSE", data);
return data;
};
React.useEffect(() => {
sendRequest().then((data) => console.log(data));
}, []);
console.log(user);
return <div>Welcome</div>;
}
Here is the Verify token code in my express app
exports.verifyToken = async (req, res, next) => {
const cookies = await req.headers.cookie;
const token = cookies.split("=")[1];
if (!token) {
res.status(404).json({ message: "no token found" });
}
jwt.verify(String(token), process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(400).json({message: "Invalid token" });
}
req.id = user.id;
});
next();
};
User cookie parser
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");
app.use(express.json());
app.use(cookieParser());
app.get("/", (req, res) => {
res.setHeader("Set-Cookie", "name=langesh;SameSite=None;");
res.send("hello");
});
app.get("/get-cookie", (req, res) => {
res.send(req.cookies);
});
app.listen(9000);
output
{name : "langesh"}
I personally don't have much experience with axios, I prefer fetch() method, it works perfectly.
That said, I think this issue could arise because token isn't identified in the request. Try adding headers: { Authorization: `Bearer ${token}`} to your get method and see if it is fixed.
Your code should look like :
axios.get("http://127.0.0.1:1000/api/v1/users/verify", {
headers: {
Authorization: `Bearer ${token}`
},
withCredentials: true,
})

Trying to fetch the google api's book

Since yesterday I'm trying to get the books on the google API for an exercise, I had to pass on a lot of errors and here is my final code, from this moment I can't move forward:
export async function fetchGoogle (url, options = {}) {
const headers = {Accept : 'application/json', ...options.headers}
const r = await fetch(url, {...options, headers})
if (r.ok) {
return r.json()
}
throw new Error ('Error server', {cause :r})
}
// Bypass error 200
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Then I import this into my main script :
import { fetchGoogle } from "./api.js"
const books = await fetchGoogle ('https://www.googleapis.com/auth/books')
console.log(books)
After all these fights I get the error : Uncaught ReferenceError: require is not defined
at api.js:12:15
Thanks in advance for helping

getPSTNcall Javascript error Microsoft graph

I am able to get acesstoken with all the scope but when I add CallRecord-PstnCalls.Read.All, CallRecords.Read.All to scopes it gives me error
msal-browser.min.js:35 Uncaught (in promise) ServerError: invalid_client: AADSTS650053: The application 'postman' asked for scope 'CallRecord-PstnCalls.Read.All' that doesn't exist on the resource '00000003-0000-0000-c000-000000000000'. Contact the app vendor.
Trace ID: f7f4e4a5-078d-4aaf-bee7-c0c61f9f8e00
Correlation ID: 66ccba3c-fce0-4c40-8b00-83060b9defc3
Timestamp: 2021-12-28 13:24:30Z
the following is my code.Please help me my boss needs this done today.I have all the permission in azure for PSTN
const express = require('express')
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
});
async function run(){
const config = {
auth: {
clientId: '1be18c1a-5a3d-43ac-a953-5e04c6b8a93f',
authority: 'https://login.microsoftonline.com/organizations/',
redirectUri: 'http://localhost:8080'
}
};
var client = new msal.PublicClientApplication(config);
var loginRequest = {
scopes: ['CallRecord-PstnCalls.Read.All','CallRecords.Read.All']
};
let loginResponse = await client.loginPopup(loginRequest);
console.log('Login Response', loginResponse);
var tokenRequest = {
scopes: ['CallRecord-PstnCalls.Read.All','CallRecords.Read.All' ],
account: loginResponse.account
};
let tokenResponse = await client.acquireTokenSilent(tokenRequest);
console.log('Token Response', tokenResponse);
let payload = await fetch("https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2019-11-01,toDateTime=2019-12-01)", {
headers: {
'Authorization': 'Bearer ' + tokenResponse.accessToken
}
});
let json = await payload.json();
console.log('Graph Response', json);
}
Mainly this issue occurs if the scopes are not added in your App registration. Please make sure that it is added to correct app registration and permission is granted by an admin.
Please follow this link to call an API using MSAL -
Acquire token.
For you further reference we are adding a sample link where we are using MSAL flow to call Graph.
https://github.com/OfficeDev/Microsoft-Teams-Samples/blob/v-nikija/tab-sso-obo-update/samples/tab-sso/nodejs/src/server/tabs.js
Please refer above sample and in authority can you specify the tenantId -
authority: "https://login.microsoftonline.com/${your_tenant_Id}".

Google Drive OAuth 2.0 Invalid grant_type

Following the example from OAuth2WebServer from google I'm trying to set up an authentication flow from an express app using the HTTP/REST method they have but with every request I am returned with an error
I went through Google OAuth “invalid_grant” nightmare — and how to fix it but unfortunately it did not help.
{
error: "unsupported_grant_type",
error_description: "Invalid grant_type: "
}
This is a shortened version of the error I am receiving. If you need to see more of the error let me know and I can post it.
Server
const express = require('express');
const axios = require('axios');
const { web } = require('./src/client_id.json');
const app = express();
const { client_id, client_secret } = web;
let count = 0;
app.use(express.json());
/*************************
** REDIRECT USER TO GOOGLE AUTH **
*************************/
app.get('/', (req, res) => {
const redirect_uri = 'http://localhost:5000/auth';
const scope = 'https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly';
const access_type = 'offline';
res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?scope=${ scope }&access_type=${ access_type }&redirect_uri=${ redirect_uri }&response_type=code&client_id=${ client_id }`);
});
/*************************
** ON AUTH WE EXCHANGE ACCESS TOKEN FOR REFRESH TOKEN **
*************************/
app.get('/auth', (req, res) => {
count++;
if (count >= 2) {
return res.redirect('http://localhost:3000');
}
const { code } = req.query;
const redirect_uri = 'http://localhost:5000/auth';
const grant_type = 'authorization_code';
axios.post('https://www.googleapis.com/oauth2/v4/token', {
code,
client_id,
client_secret,
redirect_uri,
grant_type
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(data => {
console.log(data)
res.redirect('http://localhost:3000');
})
// ALWAYS HITS THE CATCH "Invalid grant_type"
.catch(err => {
console.log(err);
console.log('ERROR')
});
});
app.listen(5000, console.log('Server listening on port 5000'));

Using Node Twitter to send a tweet, twitter api 401 error

I'm using node and express to access the twitter api. the following code gives me a 401 error. I've tried changing my apps access to read, write and access, and regenerating my api keys, but that still gives me an error saying that it can't authenticate me. I read on the twitter forums that leaving the url callback field in the api app settings might be causing this, but that didn't fix it either.
const port = (process.env.VCAP_APP_PORT || 3000);
const express = require("express");
const twitter = require('twitter');
const app = express();
const twitterClient = new twitter({
consumer_key: 'key',
consumer_secret: 'key',
access_token_key: 'key-key',
access_token_secret: 'key'
});
app.get('/hello', (req, res) => {
twitterClient.stream('statuses/filter', {track: 'javascript'}, function(stream) {
stream.on('data', function(event) {
console.log(event && event.text);
});
stream.on('error', function(error) {
throw error;
});
});
});

Categories

Resources