Using Auth0 for Twitter to get token and secret token - twitter

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 ?

Related

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?

Loopback 4 implementing Microsoft Graph API

I am currently building a microservice that is responsible to communicate with Microsoft Graph, I have already made one with Loopback 3 and this was not a problem.
Except now, I am trying to do the same thing but with Loopback 4, but since the language changes from JavaScript to TypeScript I don't know if it's still possible to achieve this.
This was the code I used for Loopback 3 in my root server file:
'use strict';
const express = require('express');
const erouter = require('express').Router();
var session = require('express-session');
var passport = require('passport');
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const request = require('request');
var querystring = require('querystring');
const graph = require('./graph.service');
const getBookings = require('./getBookings.service');
const cors = require('cors');
var compression = require('compression');
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
// Configure simple-oauth2
const oauth2 = require('simple-oauth2').create({
client: {
id: process.env.OAUTH_APP_ID,
secret: process.env.OAUTH_APP_PASSWORD
},
auth: {
tokenHost: process.env.OAUTH_AUTHORITY,
authorizePath: process.env.OAUTH_AUTHORIZE_ENDPOINT,
tokenPath: process.env.OAUTH_TOKEN_ENDPOINT
}
});
passport.serializeUser(function(user, done) {
var MSUser = server.models.MSUser;
var id = user.profile.oid;
MSUser.find({ where: { oid: id } }, function(err, msu) {
if (err) return done(err, null);
if (!msu) {
MSUser.create(user);
} else {
done(null, id);
}
});
});
passport.deserializeUser(function(id, done) {
var MSUser = server.models.MSUser;
MSUser.findById(id, function(err, user) {
if (err) return next(err);
done(null, user);
});
});
async function signInComplete(iss, sub, profile, accessToken, refreshToken, params, done) {
if (!profile.oid) {
return done(new Error("No OID found in user profile."), null);
}
try {
const user = await graph.getUserDetails(accessToken);
if (user) {
profile['email'] = user.mail ? user.mail.toLowerCase() : user.userPrincipalName.toLowerCase();
}
} catch (err) {
done(err, null);
}
let oauthToken = oauth2.accessToken.create(params);
var AuthUser = server.models.AuthUser;
var user = {};
AuthUser.find({ where: { email: profile['email'] } }, function(err, au) {
if (err) return done(err, null);
if (au.length != 1) return done(new Error("User was not found with that email address."), null);
user = au[0];
const dataMsAuth = querystring.stringify({
"created": new Date().toDateString(),
"token_type": oauthToken.token.token_type,
"expires_in": oauthToken.token.expires_in,
"access_token": oauthToken.token.access_token,
"scope": oauthToken.token.scope,
"ext_expires_in": oauthToken.token.ext_expires_in,
"refresh_token": oauthToken.token.refresh_token,
"id_token": oauthToken.token.id_token,
"expires_at": new Date(oauthToken.token.expires_at).toDateString()
});
const postMSAuth = {
url: process.env.API_URL + "api/Companies/" + user.companyId + "/msauth",
method: 'POST',
body: dataMsAuth,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
request(postMSAuth, function(err, resp, body) {
if (err) return done(err, null);
var MSUser = server.models.MSUser;
var id = profile.oid;
var msuser = { profile, oauthToken, oid: id, email: profile.email }
MSUser.findById(id, function(err, msu) {
if (err) return done(err, null);
if (!msu) {
MSUser.create(msuser);
}
});
return done(null, msuser);
});
});
}
passport.use(new OIDCStrategy({
identityMetadata: `${process.env.OAUTH_AUTHORITY}${process.env.OAUTH_ID_METADATA}`,
clientID: process.env.OAUTH_APP_ID,
responseType: 'code id_token',
responseMode: 'form_post',
redirectUrl: process.env.OAUTH_REDIRECT_URI,
allowHttpForRedirectUrl: true,
clientSecret: process.env.OAUTH_APP_PASSWORD,
validateIssuer: false,
passReqToCallback: false,
scope: process.env.OAUTH_SCOPES.split(' ')
},
signInComplete
));
var app = express();
app.use(compression());
app.use(session({
secret: process.env.BOOKINGS_LOOPBACK_SECRET,
resave: false,
saveUninitialized: false,
unset: 'destroy'
}));
app.use("/result", express.static('client'));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors({
origin: '*'
}));
erouter.get('/API/bookings/:companyid', getBookings());
erouter.get('/auth/signin',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res,
prompt: 'login',
state: req.query.state,
failureRedirect: process.env.WEBSITE_URL + 'settings?error=incorrect_request',
successRedirect: process.env.WEBSITE_URL + 'settings?auth=success'
})(req, res, next);
}
);
erouter.post('/auth/callback',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res,
failureRedirect: process.env.WEBSITE_URL + 'settings?error=permission_denied',
successRedirect: process.env.WEBSITE_URL + 'settings?auth=success'
})(req, res, next);
}
);
app.use(erouter);
server.use(app);
server.use(router);
};
So my question is: "Is it possible to implement Microsoft Graph API in TypeScript using Loopback 4 or should I keep using Loopback 3 In JavaScript?"
Thanks in advance,
Billy Cottrell

How to refresh access token in electron app?google oauth2.0

I use this api to provide google login function for my electron app
https://github.com/googleapis/google-auth-library-nodejs
My access token expires after 3600 seconds
I don’t want my users to log in again after 3600 seconds
How can I make the token refresh automatically?
I try to use the document example code on the my app
But it doesn't seem to work
How can I get a new access_token
I try the code below to get a new access_token
But nothing happens
const { app, BrowserWindow, screen } = require('electron');
const fs = require('fs');
const { google } = require('googleapis'); // auth node js
googleOAuth2Login();
function googleOAuth2Login() {
const SCOPES = ['https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), showAccessToken);
});
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, content) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(content));
callback(JSON.parse(content))
oAuth2Client.on('tokens', (tokens) => {
//this handle not work
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
});
}
/**
* This method opens a new window to let users log-in the OAuth provider service,
* grant permissions to OAuth client service (this application),
* and returns OAuth code which can be exchanged for the real API access keys.
*
* #param {*} interactionWindow a window in which the user will have interaction with OAuth provider service.
* #param {*} authPageURL an URL of OAuth provider service, which will ask the user grants permission to us.
* #returns {Promise<string>}
*/
function getOAuthCodeByInteraction(interactionWindow, authPageURL) {
interactionWindow.loadURL(authPageURL, { userAgent: 'Chrome' });
return new Promise((resolve, reject) => {
const onclosed = () => {
reject('Interaction ended intentionally ;(');
};
interactionWindow.on('closed', onclosed);
interactionWindow.on('page-title-updated', (ev) => {
const url = new URL(ev.sender.getURL());
// console.log(url.searchParams)
if (url.searchParams.get('approvalCode')) {
console.log('allow')
interactionWindow.removeListener('closed', onclosed);
interactionWindow.close();
return resolve(url.searchParams.get('approvalCode'));
}
if ((url.searchParams.get('response') || '').startsWith('error=')) {
console.log('reject')
interactionWindow.removeListener('closed', onclosed);
interactionWindow.close();
return reject(url.searchParams.get('response'));
}
});
});
};
function executeAuthWindow(authWindow, authUrl) {
authWindow.setMenu(null);
authWindow.show();
return new Promise((resolve, reject) => {
getOAuthCodeByInteraction(authWindow, authUrl)
.then((res) => {
if (res != 'Interaction ended intentionally ;(') {
return resolve(res);
}
if (res == 'Interaction ended intentionally ;(') {
return reject('Fail:Authorization window colose');
}
}).catch((err) => {
if (err = 'error=access_denied') {
return reject('Fail: error=access_denied');
}
});
})
}
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
const authWindow = new BrowserWindow({
width: 600,
height: 800,
show: false,
'node-integration': false,
'web-security': false
});
executeAuthWindow(authWindow, authUrl)
.then((code) => {
//access_token: and refresh_token:
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
console.log('getToken')
console.log(token)
oAuth2Client.setCredentials(token);
console.log(oAuth2Client)
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
});
}).catch((err) => {
console.log(err)
})
}
// initOAuthClient
function showAccessToken(token) {
console.log(token)
}
}
credentials file
{
"installed": {
"client_id": "*******17079-*********gjlh6g2nnndhqotn3ij509k.apps.googleusercontent.com",
"project_id": "quickstart-**********",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "*********dNz3Gceo9F",
"redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob",
"http://localhost"
]
}
}

NestJS - Axios Oath2 get third party access token

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

NOT FOUND - The server has not found anything matching the requested URI

In my react website I login i want to generate a token. I'm calling my API and respone is undefined.
[object Error]{config: Object {...}, description: "Network Error",
message: "Network Error", name: "Error", request: XMLHttpRequest {...}, response: undefined, stack: "Error: Netw..."}
This is my react code.
const axios = require("axios");
const fakeAuth = {
isAuthenticated: false,
authenticate(cb: any) {
this.isAuthenticated = true;
axios.post('https://localhost:44310/api/Users/Token' )
.then((response : any) => {
console.log(response)
})
.catch((error : any) =>{
console.log(error)
})
},
signout(cb: any) {
this.isAuthenticated = false;
},
getValue() {
return this.isAuthenticated;
}
};
export default fakeAuth;
and this my API token method.
private string Token()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("qwertyuiopqwertyuiop"));
var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
issuer: "localhost",
audience: "localhost",
expires: DateTime.Now.AddMinutes(1),
signingCredentials: signInCred
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return tokenString;
}

Resources