NestJS - Axios Oath2 get third party access token - oauth-2.0

I am newby on NestJS I wrote following code to get access token from third party but API respond data: error: 'invalid_request', error_description: 'Missing Mandatory Parameters'} may be I am missing headers or something else.
Following code I am using:
async getEquifaxToken() {
const token_params = {
grant_type: 'client_credentials',
client_id: 0000,
client_secret: 0000,
scope: 'https://api.equifax.com/business/consumer-credit/v1',
};
try {
const response = await axios.post(
environment.equifax_api_url + 'v2/oauth/token',
querystring.stringify(token_params)
);
console.log('--response--', response.data);
} catch (error) {
console.error(error);
}
console.log('--before after--');
}
I got access token from POSTMAN authentication popup.

Mistake was client_id and client_secret not usedful in token_params so just add
btoa function is not available on nestJS you have to install btoa https://www.npmjs.com/package/btoa and then include client_id and client_secret in headers params.
const client_id = 0000;
const client_secret = 0000;
const token_headers = {
Authorization:
'Basic ' +
btoa(
client_id +
':' +
client_secret
),
};
async getEquifaxToken() {
const token_params = {
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret,
scope: 'https://api.equifax.com/business/consumer-credit/v1',
};
try {
const response = await axios.post(
environment.equifax_api_url + 'v2/oauth/token',
querystring.stringify(token_params),
{headers:token_headers}
);
console.log('--response--', response.data);
//Here I got token successfully.
} catch (error) {
console.error(error);
}
}

Related

How can I authenticate users with zapier authentication API

I have a vue-node application and want to authenticate the users with zapier authentication API.
I tried using the below API but it takes account_id parameter which I don’t know how to get.
"account_id": 19907586,
https://zapier.com/api/v3/login
I could not find any official documentation of any API that can authenticate users with their zapier credentials, how can I do this ?
Where can I find an API to authenticate zapier users ?
You can try this :
const axios = require('axios')
const { URLSearchParams } = require('url')
const { ZAPIER_API_KEY } = process.env
const zapierApi = axios.create({
baseURL: 'https://api.zapier.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
})
const params = new URLSearchParams()
params.append('api_key', ZAPIER_API_KEY)
const authenticate = async () => {
const response = await zapierApi.post('/v1/authenticate', params)
return response.data
}
module.exports = {
authenticate,
}

SimpleGraphClient: Invalid token received

I started developing a new MS Teams Application and I am trying to authenticate a MS Teams user on my app's backend by following the source code of
https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/app-sso
But unfortunately when I am trying to create a SimpleGraphClient with the token acquired by this function
// Get Access Token
const getAccessToken = async(req) => {
return new Promise((resolve, reject) => {
const { tenantId, token } = reqData(req);
const scopes = ['User.Read']; //['User.Read', 'email', 'offline_access', 'openid', 'profile'];
const url = `https://login.microsoftonline.com/${ tenantId }/oauth2/v2.0/token`;
const params = {
client_id: process.env.MicrosoftAppId,
client_secret: process.env.MicrosoftAppPassword,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token,
requested_token_use: 'on_behalf_of',
scope: scopes.join(' ')
};
// eslint-disable-next-line no-undef
fetch(url, {
method: 'POST',
body: querystring.stringify(params),
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(result => {
if (result.status !== 200) {
result.json().then(json => {
// eslint-disable-next-line prefer-promise-reject-errors
reject({ error: json.error });
});
} else {
result.json().then(async json => {
resolve(json.access_token);
});
}
});
});
};
I am taking the exception :
throw new Error('SimpleGraphClient: Invalid token received.');
What am I doing wrong?

Next-Auth Okta Authorization code with PKCE

I am trying to integrate a NextJS application with Okta, using the Authorization code flow with PKCE. The flow is not complete because the token request is not being performed.
This is the configuration for the provider:
import NextAuth from 'next-auth';
const oktaBaseUrl = 'https://my-okta-domain.com/oauth2/[auth-server-id]';
const clientId = '[My Client Id]';
const authorizationUrl =
oktaBaseUrl +
'/v1/authorize?response_type=code&response_mode=query&state=false';
const accessTokenUrl = oktaBaseUrl + '/v1/token';
const profileUrl = oktaBaseUrl + '/v1/userinfo';
export default NextAuth({
providers: [
{
id: 'okta',
name: 'Okta',
type: 'oauth',
version: '2.0',
protection: 'pkce',
clientId,
clientSecret: '',
accessTokenUrl,
authorizationUrl,
profileUrl,
scope: 'services',
params: {
grant_type: 'authorization_code',
},
profile(profile) {
return {
id: profile.id as string,
name: profile.name,
email: profile.email
};
}
}
],
});
Thefirst stage seems to be perfromed correctly, but when okta returns the code, I only see a message in my application showing an 403 code. It seems it is trying to get the code without perform the request to the token endpoint
Message in console:
[next-auth][error][oauth_get_access_token_error]
https://next-auth.js.org/errors#oauth_get_access_token_error { statusCode: 403, data: '' } okta y64EzO0u9ZbwqFdjJWqapXggDmC1bWx2DGQaITCpta4
[next-auth][error][oauth_callback_error]
https://next-auth.js.org/errors#oauth_callback_error { statusCode: 403, data: '' }
Is there a configuration I am missing?

Using Auth0 for Twitter to get token and secret token

im using auth0 to get authentication for twitter, im using react native and i want to use twitter as login,
this is my code.
_loginWithAuth0Twitter = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const result = await AuthSession.startAsync({
authUrl: `${auth0Domain}/authorize` + toQueryString({
connection: 'twitter',
client_id: auth0ClientId,
response_type: 'token',
scope: 'openid',
redirect_uri: redirectUrl,
}),
});
after request auth give me this result
Object {
"errorCode": undefined,
"params": Object {
"access_token": "8uDhJTvWFxpr6GpTfioXp_8wCtqfwDsW",
"exp://127.0.0.1:19000/--/expo-auth-session": "",
"expires_in": "7200",
"scope": "openid",
"token_type": "Bearer",
},
"type": "success",
"url": "exp://127.0.0.1:19000/--/expo-auth-session#access_token=8uDhJTvWFxpr6GpTfioXp_8wCtqfwDsW&scope=openid&expires_in=7200&token_type=Bearer",
}
i only get acess_token and there is not much thing you can do with access token since twitter still using auth 1.0
i try to set rules
Get email address from Twitter
function (user, context, callback) {
// additional request below is specific to Twitter
if (context.connectionStrategy !== 'twitter') {
return callback(null, user, context);
}
const oauth = require('oauth-sign');
const uuid = require('uuid');
const url = 'https://api.twitter.com/1.1/account/verify_credentials.json';
const consumerKey = configuration.TWITTER_CONSUMER_KEY;
const consumerSecretKey = configuration.TWITTER_CONSUMER_SECRET_KEY;
const twitterIdentity = _.find(user.identities, { connection: 'twitter' });
const oauthToken = twitterIdentity.access_token;
const oauthTokenSecret = twitterIdentity.access_token_secret;
const timestamp = Date.now() / 1000;
const nonce = uuid.v4().replace(/-/g, '');
const params = {
oauth_consumer_key: consumerKey,
oauth_nonce: nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_token: oauthToken,
oauth_version: '1.0',
oauth_callback:'https://pembersih.auth0.com/login/callback'
};
params.oauth_signature = oauth.hmacsign('POST',
url,
params,
consumerSecretKey,
oauthToken);
const auth = Object.keys(params).sort().map(function (k) {
return k + '="' + oauth.rfc3986(params[k]) + '"';
}).join(', ');
request.post(url, {
headers: {
'Authorization': 'OAuth ' + auth
},
json: true
}, (err, resp, body) => {
if (resp.statusCode !== 200) {
return callback(new Error('Error retrieving email from twitter: ' + body || err));
}
});
}
then i get this error
Object {
"errorCode": undefined,
"params": Object {
"error": "access_denied",
"error_description": "Error retrieving email from twitter: [object Object]",
"exp://127.0.0.1:19000/--/expo-auth-session": "",
},
"type": "success",
"url": "exp://127.0.0.1:19000/--/expo-auth-session#error=access_denied&error_description=Error%20retrieving%20email%20from%20twitter%3A%20%5Bobject%20Object%5D",
}
how can i get user token and secret token so that i can use twitter API ?

MS Graph Sample Application Integration Test not Working

I want to do what the MS Graph sample node app is doing in its integrationTests.js, but that test doesn't work. Here's what I've tried:
Followed the quick start for creating a node.js app.
Ran the app. Ensured it worked by sending an e-mail.
Modified the test Checking that the sample can send an email to use my account parameters.
Tried to run the test. It fails with 403: insufficient scope. The call to get the token returned scopes, but lacked Mail.Send.
In the post data for the call to login.microsoftonline.com, I added "scope: 'Mail.Send'"
I still receive a valid token, and the return scope includes Mail.Send, but when I try to post with that token, I get 400: cannot POST /beta/me/sendMail
I tried adding scope (Mail.Send) in the query string and as a header (thought I saw that somewhere), but it made no difference.
I added the Mail.Send permission (under "Application Permissions") for the app in the application registration portal.
I compared the token (using https://jwt.ms) from my test call to the call from the app when it works. I see no real difference. They both contain the Mail.Send scope.
Here is the code (which is only slightly different from what's in the sample):
// in graphHelper.js
function postSendMail(accessToken, message, callback) {
request
.post('https://graph.microsoft.com/beta/me/sendMail')
//.post('https://graph.microsoft.com/beta/me/sendMail?scope=Mail.Send') // nope
.send(message)
.set('Authorization', 'Bearer ' + accessToken)
.set('Content-Type', 'application/json')
.set('Content-Length', message.length)
.set('scope', 'Mail.Send') // nope
.end((err, res) => {
callback(err, res);
});
}
describe('Integration', function () { // mocha
var accessToken;
var scope;
const config = getConfig();
// My account variables in testConfig.json file
function getConfig() {
var configFilePath = path.join(__dirname, 'testConfig.json');
return JSON.parse(fs.readFileSync(configFilePath, { encoding: 'utf8' }));
}
function getAccessToken(done) {
var postData = querystring.stringify(
{
grant_type: 'password',
//grant_type: 'client_id', // not supported
//grant_type: 'authorization_code', // This assumes you've requested an auth code.
resource: 'https://graph.microsoft.com/',
scope: 'Mail.Send',
client_id: config.test_client_id_v2,
client_secret: config.test_client_secret_v2,
username: config.test_username,
password: config.test_password
}
);
var postOptions = {
host: 'login.microsoftonline.com',
port: 443,
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = https.request(postOptions, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
const response = JSON.parse(data);
accessToken = response.access_token;
scope = response.scope;
done();
});
});
postRequest.on('error', function (e) {
console.log('Error: ' + e.message);
done(e);
});
postRequest.write(postData);
postRequest.end();
}
before( // eslint-disable-line no-undef
function (done) {
getAccessToken(done);
}
);
it('Checking that the sample can send an email',
function (done) {
var postBody = emailer.generateMailBody(config.test_name, config.test_username);
graphHelper.postSendMail(
accessToken, scope,
JSON.stringify(postBody),
function (error) {
assert(error === null, `The sample failed to send an email: ${error}`);
done();
});
}
);
});

Resources