Firebase Re-authentication & email Linking for Phone-Authenticated Users - node.js

When users sign up, they use Phone Auth. After using the app for a while, they are advised to link an (email & password) to their existing account.
The linking process fails because of the error (auth/requires-recent-login.) My code follows.
// The following generates the error: [auth/requires-recent-login] This operation is sensitive and requires recent authentication. Log in again before retrying this request.
const emailCredential = firebase.auth.EmailAuthProvider.credential(state.email, state.password);
const newCredential = await firebase.auth().currentUser.linkWithCredential(emailCredential);
To fix this error, I understand that I need to call reauthenticateWithCredential() before linking. However, I don't want to ask the user to log in again (receive & enter a verification code.) Is this at all possible?
I tried passing the result of currentUser.getIdToken(true) to PhoneAuthProvider.credential() I am not sure if this is right. Anyway, it generated an error (Cannot create PhoneAuthCredntial without either verificationProof, sessionInfo, temporary proof, or enrollment ID.).
My code follows.
// The following works:
const accessToken = await firebase.auth().currentUser.getIdToken(true);
// The following works:
const currentCredential = firebase.auth.PhoneAuthProvider.credential(accessToken);
// The following generates the error: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, temporary proof, or enrollment ID.
const abc = await firebase.auth().currentUser.reauthenticateWithCredential(currentCredential);
// The following is never reached:
const emailCredential = firebase.auth.EmailAuthProvider.credential(state.email, state.password);
const newCredential = await firebase.auth().currentUser.linkWithCredential(emailCredential);
Thank you for your effort and time to help me...

Important Information:
firebase.auth().currentUser.reauthenticateWithCredential(credential) requires the attribute credential
For users, who logged in using a Phone Number, I could not find a way to get this credential when required. By the way, it is possible to get it for users, who logged in using other providers, e.g. Facebook.
However, for users, who log in using a phone number, it is possible to get this credential during the login process. Check https://firebase.google.com/docs/auth/web/phone-auth.
So, I decided to save the credential for the user on their device during the login process. I am using Redux and Redux-Persist for that.
My code after fixing it.
// This is an extract from the login script:
firebase.auth().signInWithPhoneNumber(phoneNo)
.then(confirmResult => {
dispatch({ type: "PhoneNo_accepted", payload: { confirmResult: confirmResult } });
})
.catch(error => {
dispatch({ type: "display_message", payload: { messageText: `Phone Number Error: ${error.message}` } });
});
// Change#1. The following statement is a NEW step, which I added to get the credential during the login process.
const credential = firebase.auth.PhoneAuthProvider.credential(state.confirmResult.verificationId, state.codeInput);
state.confirmResult.confirm(state.codeInput)
.then( (user) => {
// Change#2. The following function would save the credential to the app's state, e.g. using Redux
_onAuthComplete(user, credential);
})
.catch( error => {
dispatch({ type: "display_message", payload: { messageText: `Verification Code Error: ${error.message}` } });
});
// // //
// This is an extract from the linking script:
// Change#3. props.credential is the credential, which was saved to the app's state.
await firebase.auth().currentUser.reauthenticateWithCredential(props.credential);
const emailCredential = firebase.auth.EmailAuthProvider.credential(state.email, state.password);
const newCredential = await firebase.auth().currentUser.linkWithCredential(emailCredential);

Related

node-ews returning 401 Unauthorized where as using the valid access token

I am using node-ews to fetch emails from the Microsoft Exchange server.
It was working fine with basic auth.
But, as Microsoft disabled basic auth.
We are currently using the OAuth token (access token) from Graph Explorer to test.
But it's returning 401 Unauthorised error.
This is the sample code we are using to connect to the exchange server.
const ewsConfig = {
username: item.mail_username,
password: item.user_pass,
host: item.ews_host,
token: 'xxxxxxxxxxx',
auth: 'bearer'
};
// initialize node-ews
const options = {
rejectUnauthorized: false,
strictSSL: false
};
// initialize node-ews
const ews = new EWS(ewsConfig, options);
. We are currently using the OAuth token (access token) from Graph Explorer to test.
The Graph Explorer token won't have permissions for EWS only Graph, the only two permission that are valid in EWS are EWS.AccessAsUser.All or full_access_as_app if using the client credentials flow. https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth the Mail.Read etc permission don't work in EWS because it doesn't support the more restrictive authentication scheme that Graph supports (which is a reason to use the Graph over EWS)
If you want to accesstoken to test with use the EWSEditor https://github.com/dseph/EwsEditor/releases and grab its token
Part 1-1 - Setup application in AZURE that allows to generate MSAL-access token for EWS:
Login to MS AZURE portal.
Open "App registration" tool:
step2_img
Click "New Registration":
step3_img
Setup new App:
step4_img
After you click registrate button you will receive smtg like this:
step5_img
Open API permissions tab for previously created App + click Add permission and select MS Graph:
step6_img
Select Delegated permissions:
step7_img
Find User section and select User.Read + Add permission click:
step8_img
Add a permission again + APIs my organizaton uses tab(or find it) and find Office 365 Exchange Online:
step9_img
Part-1-2 - continue...
Part 2 - get accessToken by using userName + userPassword to email box:
import * as path from 'path';
import { ExchangeService, EmailMessage, MessageBody, OAuthCredentials, AutodiscoverService, Folder, Item, ExchangeVersion } from 'ews-javascript-api';
public async getEmailAccessToken(
clientId: string,
tenantId: string,
emailUserName: string,
emailUserPassword: string,
cacheFilePath: string = `.${path.sep}tokenCache.json`) {
const msal = require('#azure/msal-node');
const { promises: fs } = require('fs');
//Cache Plugin configuration
const beforeCacheAccess = async (cacheContext) => {
try {
const cacheFile = await fs.readFile(cacheFilePath, 'utf-8');
cacheContext.tokenCache.deserialize(cacheFile);
} catch (error) {
// if cache file doesn't exists, create it
cacheContext.tokenCache.deserialize(await fs.writeFile(cacheFilePath, ''));
}
};
const afterCacheAccess = async (cacheContext) => {
if (cacheContext.cacheHasChanged) {
try {
await fs.writeFile(cacheFilePath, cacheContext.tokenCache.serialize());
} catch (error) {
console.log(error);
}
}
};
const cachePlugin = {
beforeCacheAccess,
afterCacheAccess
};
const msalConfig = {
auth: {
clientId: clientId, // YOUR clientId
authority: `https://login.microsoftonline.com/${tenantId}` // YOUR tenantId
},
cache: {
cachePlugin
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose
}
}
};
const pca = new msal.PublicClientApplication(msalConfig);
const msalTokenCache = pca.getTokenCache();
const accounts = await msalTokenCache.getAllAccounts();
// Acquire Token Silently if an account is present
let accessToken = null;
if (accounts.length > 0) {
const silentRequest = {
account: accounts[0], // Index must match the account that is trying to acquire token silently
scopes: ['https://outlook.office365.com/EWS.AccessAsUser.All'],
};
const response = await pca.acquireTokenSilent(silentRequest);
accessToken = response.accessToken;
} else {
// fall back to username password if there is no account
const usernamePasswordRequest = {
scopes: ['https://outlook.office365.com/EWS.AccessAsUser.All'],
username: emailUserName, // Add your username here
password: emailUserPassword, // Add your password here
};
const response = await pca.acquireTokenByUsernamePassword(usernamePasswordRequest);
accessToken = response.accessToken;
}
return accessToken;
}
This method returns accessToken allows us to use EWS-api and also generates tokenCacheFile.json that will be used for silent usage in case of multiple calls.
Part 3 - connect to emailbox by using previously generated accessToken and ews-javascript-api :
import { ExchangeService, EmailMessage, MessageBody, OAuthCredentials, AutodiscoverService, Folder, Item, ExchangeVersion } from 'ews-javascript-api';
public async connectAndChangeAllEmailsFromBlaBla(
clientId: string,
tenantId: string,
exchangeServiceUrl: string = 'https://outlook.office365.com/Ews/Exchange.asmx',
emailUserName: string,
emailUserPassword: string,
searchMask: string = 'hasattachments:yes and from:NoReply#blabla.com and received:today') {
// get acces token by method written above in part 2
const emailAccessToken = await this.getEmailAccessToken(clientId, tenantId, emailUserName, emailUserPassword);
const ews = require('ews-javascript-api');
const service = new ExchangeService(ews.ExchangeVersion.Exchange2013);
// use emailAccesToken
service.Credentials = new OAuthCredentials(emailAccessToken);
service.Url = new ews.Uri(exchangeServiceUrl);
const mailInbox = await ews.Folder.Bind(service, ews.WellKnownFolderName.Inbox);
const loadPageSize = 1000; // 1 means load last email according to filter
const view = new ews.ItemView(loadPageSize);
view.PropertySet = new ews.PropertySet(ews.BasePropertySet.FirstClassProperties);
let mailItems;
// hasattachment:yes
// isread:false
// received:today or received:[date]
mailItems = await mailInbox.FindItems(searchMask, view);
console.log(`Emails were found before processing: ${mailItems.Items.length}`);
for (const item of mailItems.Items) {
// mark mail.item as read
item.IsRead = true;
await item.Update(1);
// Do what you want
}
return mailItems.Items.length;
}
Part 0 - Please find the solution we used to fix the same problem.
The solution consist of 3 parts:
Setup application in AZURE that allows to generate MSAL-access token for EWS.
Add code to get accessToken.
Made changes in old code to use previously received accessToken. I am usind ews-javascript-api. But I think previouse two steps will help you to get accessToken for EWS and you can use it with node-EWS.
Sorry for 3 posts, but as a new user I have a restrictions it impossible for new users to create posts with more than 8 links and etc... )
Part 1-2 - continue:
Find EWS section and select EWS.AccessAsUser.All and click Add permissons:
step10_img
Go to Authentication tab and click Add platform:
step11_img
Select Mobile and Desctop apps and click Save button:
step12_img
Select two options and click Configure:
step13-1_img
step13-2_img
Also on Authentication tab set "Supported accounts types" and "Allow public client flows" and click Save:
step14_img
Go to Overview tab you should see smthg like this:
clientID
tenantId
step15_img
THIS STEP should be made BY EACH USER that WILL USE this API - use USER credentials to open this link (or YOUR ADMIN should make bulk apply). Check made changes by opening next link in browser in incognito mode(FOR each user):
https://login.microsoftonline.com/ADD YOUR TENANTID/oauth2/v2.0/authorize?
client_id=ADD YOUR CLIENTID
&response_type=code
&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient
&response_mode=query
&scope=EWS.AccessAsUser.All
&state=12345
After the opening previously generated link you should login and then receive another link in browser which shoud contains generated code:
step16_img
Now we can start add code allows us to get accessToken

#azure/msal-node: Is there a way to log out / invalidate tokens?

I'm using the #azure/msal-node package in a node application to enable my users to log in using their AzureAD credentials. Logging in and acquiring session tokens works fine, but I cannot find a way to invalidate a session / log out a user - am I overlooking something obvious here?
Just for context, here's how I'm getting my tokens:
// msalConfig is my valid config object
const msalApp = new msal.ConfidentialClientApplication(msalConfig);
const authCodeUrlParameters = {
scopes: ['user.read'],
redirectUri: BASE_URL + '/msal-redirect'
};
try {
const authCodeResponse = await msalApp.getAuthCodeUrl(authCodeUrlParameters);
reply.redirect(authCodeResponse);
} catch (e) {
logError('auth code redirect error', e);
}
In the redirect handler, I'm doing this:
const tokenResponse = await msalApp.acquireTokenByCode({
code: request.query.code,
scopes: ['user.read'],
redirectUri: BASE_URL + '/msal-redirect'
});
and then I'm using that token to display the logged in user etc.
What I'm missing is something like msalApp.logout() - what am I not seeing here?
Unfortunately MSAL does not currently contain an msalApp.logout() API. Instead, you will have to manually implement the steps.
A logout operation will contain multiple steps:
Removing the account and the tokens from the msal application cache.
Redirecting to the AAD logout endpoint so the user logs out and AAD cookies are deleted.
If your webapp has a session, invalidating it.
For removing the account and tokens from the msal application cache, you can do something along the lines of:
const accounts = msalApp.getTokenCache().getAllAccounts();
// filter on the account that you want to delete from the cache.
// I take the first one here to keep the code sample short
const account = accounts[0];
msalApp.getTokenCache().removeAccount(account);
For logging out from AAD, you'll have to redirect the user to the Azure AD logout endpoint. The documentation here should explain how to craft this request.
In answer of sgonzalez, I can see the error in "accounts". This const is a Promisse:
const accounts = msalApp.getTokenCache().getAllAccounts(); // <- is a Promisse
// filter on the account that you want to delete from the cache.
// I take the first one here to keep the code sample short
const account = accounts[0];
msalApp.getTokenCache().removeAccount(account);
Correcting:
pca.getTokenCache().getAllAccounts().then((response) => {
const account = response[0];
pca.getTokenCache().removeAccount(account).then(() => {
res.sendStatus(200);
}).catch((error) => {
res.status(500).send({error});
});
}).catch((error) => {
res.status(500).send(error);
});
I don't know if this is the best way to implement it, but it worked for me.

How do I enable devToken for a StreamChat?

I am trying to initialize a new chat using a devToken to allow client-side generated tokens by coding the following inside an async function:
let chatClient = await new StreamChat(apiKey);
await chatClient.updateAppSettings({
disable_auth_checks: true,
});
await chatClient.setUser(
{
id: 'user-0',
name: random-user-name,
},
chatClient.devToken('user-0'),
);
but am getting the error that "Both secret and user tokens are not set", despite using a devToken. The error stops the code from running once it hits
await chatClient.updateAppSettings({
disable_auth_checks: true,
});
, which is supposed to allow me to use the .devToken in place of a userToken.
So I added my secretKey to new StreamChat
let chatClient = await new StreamChat(apiKey, secretKey);
however, then I get the error "TypeError: Cannot read property 'sign' of null at JWTServerToken" right after that line runs.
And if I try to generate a userToken and replace chatClient.devToken('user-0') with userToken like this
let userToken = await chatClient.createToken("user-0");
I get the error "Error: tokens can only be created server-side using the API Secret", which is what I was trying to avoid.
Does anyone know how to correctly enable .devTokens so that the chatClient can be set without generating a token server-side?
Thanks!
This needs to be done via the dashboard. First, make sure your app is in development mode.
Then, navigate to the app's chat overview page and enable "Disable Auth Checks". Hit save.

firebase-admin: Get token of failed notification delivery result

Let's say we want to send a notification to two registrationTokens (only Android devices, no iOS) like this:
const tokens = ['tokenA', 'tokenB'];
const payload = {badge: 1, title: 'Hello', body: 'world'};
const options = {priority: 'high',contentAvailable: false, timeToLive: 60 * 60 * 24};
const admin = FirebaseAdmin.initializeApp({/*config here...*/});
admin.messaging().sendToDevice(deviceTokens, payload, options)
.then((response) => {
response.results.forEach((deviceResult) => {
if (deviceResult.error) {
console.log('Delivery failed. Showing result:\n', deviceResult);
}
});
});
The user who's device once registered with tokenB deleted the app from his device. Therefore the token is not registered anymore with firebase.
The error object looks like this then:
Delivery failed. Showing result:
{"error":
{
"code":"messaging/registration-token-not-registered",
"message":"The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages."
}
}
The Problem:
My problem is, that I only know that one of the deliveries failed. But I don't know to which token the error is related. Therefore I cannot remove the outdated token from the database.
The Question:
Is there a way to find out for which tokens the deliveries have failed?
Github Issue Link: https://github.com/firebase/firebase-admin-node/issues/600
You need to use the index in forEach and get the token from your array you passed in sendToDevice.
Official docs: https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingDevicesResponse
This seems like a hack but it works for me when I have multiple device tokens of a single user as I have to store new one whenever they login.
const tokens = ['tokenA', 'tokenB'];
const payload = {badge: 1, title: 'Hello', body: 'world'};
const options = {priority: 'high',contentAvailable: false, timeToLive: 60 * 60 * 24};
const admin = FirebaseAdmin.initializeApp({/*config here...*/});
admin.messaging().sendToDevice(deviceTokens, payload, options)
.then((response) => {
response.results.forEach((deviceResult,index) => {
if (deviceResult.error) {
let failedToken = tokens[index];
// Now use this token to delete it from your DB, or mark it failed according to your requirements.
}
});
});
This method is also used in firbease samples as well: https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js

Access Facebook Messenger User Profile API in DialogFlow

I'm building a cross-platform chatbot in Google's DialogFlow. I'd like to access the Facebook User Profile API to learn the user's first name.
I'm struggling to find advice on how (or if) I can make this happen.
https://developers.facebook.com/docs/messenger-platform/identity/user-profile/
Has anybody here achieved this?
I did that for one of my bots yesterday, you need 2 things, first the Page Token and second is the psid which is Page scope user ID.
On dialogflow, you will receive the request block with psid as sender id. You can find it at:
agent.originalRequest.payload.data.sender.id
This psid needs to be passed to api get request at
/$psid?fields=first_name with your page Token as accessToken to get the first name in response.
You need to make a call to Facebook Graph API in order to get user's profile.
Facebook offers some SDKs for this, but their official JavaScript SDK is more intended to be on a web client, not on a server. They mention some 3rd party Node.js libraries on that link. I'm particularly using fbgraph (at the time of writing, it's the only one that seems to be "kind of" maintained).
So, you need a Page Token to make the calls. While developing, you can get one from here:
https://developers.facebook.com/apps/<your app id>/messenger/settings/
Here's some example code:
const { promisify } = require('util');
let graph = require('fbgraph'); // facebook graph library
const fbGraph = {
get: promisify(graph.get)
}
graph.setAccessToken(FACEBOOK_PAGE_TOKEN); // <--- your facebook page token
graph.setVersion("3.2");
// gets profile from facebook
// user must have initiated contact for sender id to be available
// returns: facebook profile object, if any
async function getFacebookProfile(agent) {
let ctx = agent.context.get('generic');
let fbSenderID = ctx ? ctx.parameters.facebook_sender_id : undefined;
let payload;
console.log('FACEBOOK SENDER ID: ' + fbSenderID);
if ( fbSenderID ) {
try { payload = await fbGraph.get(fbSenderID) }
catch (err) { console.warn( err ) }
}
return payload;
}
Notice you don't always have access to the sender id, and in case you do, you don't always have access to the profile. For some fields like email, you need to request special permissions. Regular fields like name and profile picture are usually available if the user is the one who initiates the conversation. More info here.
Hope it helps.
Edit
Promise instead of async:
function getFacebookProfile(agent) {
return new Promise( (resolve, reject) => {
let ctx = agent.context.get('generic');
let fbSenderID = ctx ? ctx.parameters.facebook_sender_id : undefined;
console.log('FACEBOOK SENDER ID: ' + fbSenderID);
fbGraph.get( fbSenderID )
.then( payload => {
console.log('all fine: ' + payload);
resolve( payload );
})
.catch( err => {
console.warn( err );
reject( err );
});
});
}

Resources