I'm able to sucessfully create the Access token using postman with following parameters,
Callback URL: https://www.getpostman.com/oauth2/callback
Token Name:
Auth URL:
Access Token URL:
Client ID:
Client Secret:
Grant Type:Client Credentials.
But I could not able to get the access token via Curl or node.js as below,
var request = require("request");
var options = { method: 'POST',
url: '',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"","client_secret":"","audience":","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) console.log(error);
//console.log(response);
console.log(body);
});
where I mapped my postman details to node.js script as,
Auth URL: url
Access Token URL: audience
Client Id: client_id
Client Secret: client_secret
Grant Type: grant_type
But I didn't any response. May I Know where i went wrong? or do we have any other mechanism to get the OAuth2 access token?
I'm just followed the script from https://manage.auth0.com/#/apis/590983763e3ae44a0dd1a219/test
After few research, I myself found the solution to generate the OAuth2 token through the code using the request, and I mapped by Postman values into the request_options as,
const options = {
url: access_token_url,
method: 'POST',
auth: {
user: client_id,
pass: client_secret,
},
form: {
grant_type: grant_type,
},
};
and used the request method to get the access token by,
request(options, (error, response, body) => {
if (error) return reject(error);
return resolve(body);
});
This helps me to generate the OAuth2 access token inside my script and fixed my requirement.
Related
in my Express app I have to get access token for Auth0. In the documentation, they have an example for pure Node JS with a request:
var request = require("request");
var options = { method: 'POST',
url: 'https://XXX.eu.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"XXX","client_secret":"XXX","audience":"http://localhost:3001/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
But when I'm trying to do the same in a next way:
app.post('/token', function(options, res) {
return res.json()
});
I'm getting "UnauthorizedError: No authorization token was found".
How can I do it properly?
Are you sure that you have enabled client_credentials grant type in your app?
Go to application / advanced / grant types and enable client_credentials
See picture here
We are trying to link our website to Wordpresses API using OAuth 2.0. Hoping that a client can authenticate and post to WordPress from our site. We need to receive an access token to do this.
We have successfully connected with Wordpress to receive our access code. We've followed the Wordpress api, and have it working for a single user (with secret key not with OAuth). Things we have tried are adding a headers, changing data to different names examples: params, body
This is a simplified version of the code we have been using
const axios = require('axios');
axios({
method: "POST",
data: {
grant_type: 'authorization_code',
client_id: '12345',
client_secret: 'ABCABC1235412345',
code: 'Abc123',
redirect_uri: 'https://localhost:5000/wordpress/callback_wordpress'
},
url: 'https://public-api.wordpress.com/oauth2/token'
}).then( (response) => {
console.log(response);
}).catch( (error) => {
console.log(error);
});
We expect to receive a jwt access token, but instead are getting this 400 error:
data:
{ error: ‘invalid_client’,
error_description: ‘The required “client_id” parameter is missing.’ } } }
It seems clear that we are missing the client_id, however we have it included in our request. Is there somewhere else we need to include it?
var authOptions = {
url: 'https://public-api.wordpress.com/oauth2/token',
form:
{
grant_type: 'authorization_code',
code: code,
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
},
headers: {
'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
We needed to include a header with that information, and we needed to use the variable 'form' instead of 'data'.
I have a question about getting form submissions, but only for registered users with a certain role in my application.
My first failed attempt:
I have tried to create a lambda function which accesses form submissions using the access_token received from a succesfull (invite-user) login on my client. However, I am only getting an empty response.
My second attempt:
Instead of using the user's access_token, I created a new Personal access token, stored it as an environment variable in my application on Netlify, and I use the token in my lambda function using process.env.ACCESS_TOKEN. Using this approach is valid, and I received all form submissions.
Here is my lambda function, test.js:
const request = require('request');
exports.handler = function(event, context, callback) {
let ACCESS_TOKEN = process.env.ACCESS_TOKEN; // when using my personal API token created in Netlify. Does work
let ACCESS_TOKEN = event["queryStringParameters"]['access_token']; // passing the user's `access_token` from the client in request url. Does not work.
const options={
url: "https://api.netlify.com/api/v1/sites/MY_SITE_ID/forms/MY_FORM_ID/submissions",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${ACCESS_TOKEN}`
}
}
request(options, (error, response, body) => {
console.log("access_token", ACCESS_TOKEN); // I know the ACCESS_TOKEN is present in both of my scenarios.
callback(null, {
headers: { "Access-Control-Allow-Origin": "http://localhost:4200","Access-Control-Allow-Headers": "Content-Type"},
statusCode: 200,
body: body
});
});
}
My request url from the client looks like this:
https://MY_DOMAIN.com/.netlify/functions/test?access_token=ACCESS_TOKEN.
I am wondering how I can get form submissions for users with certain roles only. What am I doing wrong? What is the best practice for my scenario?
I sent my question to the team at Netlify, and they were able to help me out. It seems that the acces_token I was sending to the lamdba function was a JWT (json web token). All I needed to do was to decode and verify the JWT in order to access my data. I could then use the user object decoded from the JWT to read the roles. I ended up using code similar to this:
const request = require('request');
const jwt = require('jsonwebtoken');
exports.handler = function(event, context, callback) {
const JWT_SECRET = "MY SECRET"; // secret used to verify the signature of the jwt
let ACCESS_TOKEN;
let user;
if (event && event.queryStringParameters && event.queryStringParameters.access_token) {
const jwt_token = event.queryStringParameters.access_token;
jwt.verify(jwt_token, JWT_SECRET,
(err, decoded) => {
user = decoded;
});
}
if(user && user.app_metadata && user.app_metadata.roles &&
(user.app_metadata.roles.includes("admin") || user.app_metadata.roles.includes("editor"))){
if(process.env && process.env.ACCESS_TOKEN){
ACCESS_TOKEN = process.env.ACCESS_TOKEN;
}
}
const options={
url: "https://api.netlify.com/api/v1/sites/SITE_ID/forms/FORM_ID/submissions",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${ACCESS_TOKEN}`
}
};
request(options, (error, response, body) => {
callback(null, {
headers: { "Access-Control-Allow-Origin": "http://localhost:4200","Access-Control-Allow-Headers": "Content-Type"},
statusCode: 200,
body: body
});
});
}
I'm a beginner with Node and React, and web programming in general. I want to import user credentials from LinkedIn's API and for that I need to authenticate using OAuth2.
My approach so far is to make an API-call from the client side to the LinkedIn oauth API with the relevant parameters, including a redirect URI which leads to an API endpoint on my node server. When the user has been redirected and approved LinkedIn's authentication dialog box, they will be redirected to the node server with an access token.
My question is as follows: I now want to update the user in my database with their corresponding access token, but how do I know which user to update when I can't get any information about the client in my function that handles the last redirect and fetches the access token?
Here's my node function that handles the redirect from LinkedIn:
router.get('/redirect', (req, res) => {
// Handle cancel by user
if(req.query.error){
console.log(req.query.error_description)
return
}
// Extract variables
const code = req.query.code
const state = req.query.state
// Check that state matches
if (state !== testState) {
console.log("State doesnt match")
return
}
// Exchange Authorization Code for an Access Token
var options = {
method: 'POST',
url: 'https://www.linkedin.com/oauth/v2/accessToken',
form: {
client_id: 'theClientID',
client_secret: 'theClienSecret',
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:3000/api/linkedin/redirect'
},
headers:
{ 'cache-control': 'no-cache',
"content-type": "application/json",
'user-agent': 'node.js' },
json: true };
// make the actual request
request(options, (error, response, body) => {
if (error) {
res.status(500).json({
message: error
})
return
}
// Extract access token
const token = body.access_token;
// Here I want to save access token to DB with the corresponding
// user, but I don't know which user to update
})
// Redirect user to profile
res.writeHead(301, {
Location: 'http://localhost:3000/profile'
})
res.end()
})
I had a really hard time formulating this question but I hope that my message gets through.
guys. I have a than error in my NodeJS rest API, and can't resolve this.
My idea is make a github login, this app working like this.
Href to github url returning a temporal code in callback.
Latter, send this temporal code to my REST API and with rest api make a fetch request to other endpoint of the github api, and this endpoint should return access_token=12345 (this access token is a example), for latter send this token to frontend, and convert the token in a JWT token and also send to frontend for latter storage in a localStorage to use it.
My code in NodeJS
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'GET',
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code,
accept: 'json',
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
});
PD: I use node-fetch module for this. https://www.npmjs.com/package/node-fetch
The solution
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code
})
}).then(function(res) {
return res.json();
}).then(function(body) {
res.json(body);
});
});