I am managing an application written in Node.js (restful backend) and React (frontend) and use AWS Cognito for user authentication.
In the frontend, I have a form which requests my backend to delete a user. The only information the frontend can send me is the username (email in my case) and an access token which I sent to the frontend after a successful login.
Now I want to delete a user. Until now, I tried it with the deleteUser method (see Use case 13 in the js documentation).:
const poolData = {
UserPoolId: process.env.COGNITO_USER_POOL_ID,
ClientId: process.env.CLIENT_ID
};
AWS.config.region = process.env.AWS_DEFAULT_REGION;
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
// ...
router.post('/deleteUser', (req, res) => {
var userData = {
Username: req.body.email,
Pool: userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
if (cognitoUser == null) {
res.status(400).send('User not found');
return;
}
cognitoUser.deleteUser(function(err, result) {
if (err) {
res.status(400).send('Could not delete user');
} else {
res.status(200).send('Deleted user');
}
});
});
This throws an error in the error block of deleteUser section with Error: User is not authenticated. I need to firstly authenticate the user but I won't get the password from the frontend to do so. I just have the access token it can provide me.
How can I authenticate the user with the provided token? Or am I misunderstanding a concept here? If so, what am I doing wrong?
Any help will much appreciated.
Related
I am trying to build a Node.js server-side signup function for user authentication. The data for the user is being sent via "req.body" and the authentication database is provided by Appwrite.
The signup function should:
Create a user with the credentials provided in the request body.
Return the user details, such as the username and email.
Generate and return a token (cookie/JWT)
I am encountering issues with the Appwrite documentation and would appreciate guidance on building this function.
When trying to POST a new user using the Users API, an error of
createJWT is not a function
is produced, and when using the Account API, an error of
User (role: guests) missing scope (account)
is produced.
Here's the code I have:
const sdk = require('node-appwrite')
const client = sdk.Client()
client
.setEndpoint(endpoint)
.setProject(projectId)
.setKey('...')
const users = sdk.Users(client)
async function signup(req, res) {
try {
const { email, username } = req.body
let { password } = req.body
password = await bcrypt.hash(password, SALT_ROUNDS)
const result = await users.createBcryptUser("unique()", email, password, username)
// Create a token
// Combine data
res.send(userWithToken)
} catch (err) {
error('Failed to signup', err)
throw new Error(err)
}
}
The Users API is intended to be used in an admin perspective rather than as a user. You can use the Account API to execute things on behalf of a user, but the JWT token is typically generated client side and passed to the server, where you can call client.setJWT().
At the moment I am creating a Firebase API on nodejs. I would like to handle all Firebase stuff (like authentication) with firebase-admin on nodejs. But what is the correct way to authenticate a user over nodejs in firebase-admin without the Javascript Firebase SDK on the client side? On the official documentation for admin I didn't find a function called signInWithEmailAndPassword (like as on the client side SDK) for nodejs. There is only a function called: "getUserByEmail", but this function doesn't check if the user has entered the correct password.
This is my form:
<form class="sign-box" action="/login" method="post">
<div class="form-group">
<input id="username" name="username" type="text" class="form-control" placeholder="E-Mail"/>
</div>
<div class="form-group">
<input id="password" name="password" type="password" class="form-control" placeholder="Password"/>
</div>
<button type="submit" class="btn btn-rounded">Sign in</button>
</form>
Once the form is submitted I pass the values to my API in nodejs:
app.post('/login', urlencodedParser, function (req, res) {
// getting the values
response = {
username: req.body.username,
password: req.body.password
};
// authenticate the user here, but how ?
});
My first idea was to use the Firebase SDK on the client side to sign in with signInWithEmailAndPassword and to get the uid. Once I had the UID I wanted to sent the UID to nodejs and call the function createCustomToken and to return the generated token (with some additional claims) back to the client. Once I get the token back I would use the function signWithCustomToken (on the client side) to authenticate the user. Is this way correct or is there a better way ?
Actually for authentication you will need to use the firebase regular api, no the admin.
First this will give you a refreshed firebase token, not a custom token.
If you like you can do the same to obtain a custom token, if you need a custom token, I also have an example.
npm install firebase --save
const firebase = require("firebase");
const config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
I am posting my login firebase function but you will be able to change it to express easily.
exports.login = functions.https.onRequest((req, rsp)=>{
const email = req.body.email;
const password = req.body.password;
const key = req.body.key;
const _key = '_my_key_';
let token = '';
if(key === _key){
firebase.auth().signInWithEmailAndPassword(email,password).then((user)=>{
//The promise sends me a user object, now I get the token, and refresh it by sending true (obviously another promise)
user.getIdToken(true).then((token)=>{
rsp.writeHead(200, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({token:token}));
}).catch((err)=>{
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({error:err}));
});
}).catch((err)=>{
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({error:err}));
});
} else {
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify('error - no key'));
}
});
NOTE: I am using this login function to test my other functions with Postman, so that is why i am sending a key, so I can use this privately.
Now combining the ADMIN and FIREBASE node apy I am able to do a lot of very interesting stuff with HTTP functions on my firebase.
Hope it helps somehow.
For Any Server Side React Users
I was brought here because I was attempting to authenticate users in firebase without the Javascript Firebase SDK on the client side as well. I am building a server side rendered react app. The client-side firebase.auth() does not work on a server-side node environment.
It turns out that you can run firebase.auth() commands inside of componentDidMount(), because that does not run on the server. This is where you can authenticate and get your user's token, and then send it to a cloud function for any server-side rendering that requires user authentication.
On the server side, you can then verify the token with the admin sdk.
You will also need to require firebase/app and firebase/auth, and initialize firebase in your browser-specific bundle.js, so that it is not included in your server's bundle.js
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("User signed in!");
} else {
console.log("User NOT signed in!");
}
});
}
The officially recommended and supported way is to use ID TOKENS
From the official docs:
If your Firebase client app communicates with a custom backend server, you might need to identify the currently signed-in user on that server. To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.
The workflow is:
Use the Firebase Web SDK in your client
The user logs in with any of the authentication methods
Retrieve the ID token on the client
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
Send this token to the server
Server verifies the ID token with the Firebase Admin SDK
// idToken comes from the client app
getAuth()
.verifyIdToken(idToken)
.then((decodedToken) => {
const uid = decodedToken.uid;
// ...
})
.catch((error) => {
// Handle error
});
your user is securely authenticated and uniquely identified
This is my solution, maybe it can help someone (Node/react). For some reason the client side method signInWithEmailAndPassword seems to work both on the client AND server. Basically this lets you keep the default security rule ".read": "auth != null" without having to use signInAnonymously() hence avoid creating an infinite number of stale users.
server:
const { firebase } = require('../../firebase/frontend');
const { firebase: admin } = require('../../firebase/backend');
const email = process.env.READ_ONLY_EMAIL;
const password = process.env.READ_ONLY_PASSWORD;
export default async (req, res) => {
try {
const { user } = await firebase.auth().signInWithEmailAndPassword(email, password);
const customToken = await admin.auth().createCustomToken(user.uid);
return res.status(200).send(JSON.stringify(customToken));
} catch (error) {
return res.status(404).send(error);
}
};
client:
import fetch from 'isomorphic-unfetch';
import { useState, useEffect } from 'react';
import { firebase } from '../firebase/frontend';
const useUser = (props) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [isAnonymous, setIsAnonymous] = useState(true);
const getCustomToken = async () => {
const response = await fetch('/api/auth', { method: 'POST' });
const json = await response.json();
return json;
};
useEffect(() => {
try {
const unsubscribe = firebase.auth().onAuthStateChanged(async (user) => {
// user exists
if (user && user.email !== 'readonly#myEmailAddress.com') {
setUser(user);
setIsAnonymous(false);
// else sign in user "anonymously"
} else {
setIsAnonymous(true);
const token = await getCustomToken();
firebase.auth().signInWithCustomToken(token);
}
setLoading(false);
});
return () => unsubscribe();
} catch (error) {
console.log('Error signing in user', error);
}
}, []);
return {
user,
isAnonymous,
loading
// etc...
};
};
export default useUser;
I am using reactjs and node for server side.
As you can see in the "mfa required" part of the code below, if this is all on node, then I can't really do "prompt" the user for the code, I have to pass this back to the front end.
Tried solution: If I do pass the MFA required to front end and get the users input then send it back to node to call "respondToAuth" I am getting two MFA codes in my SMS message.
Have I tried other solutions?
I am hesitant to use amplify because everything is on the front end, I would ideally like to do my authentication on the back end (thus node).
Another option I am leaning towards is just using initiateAuth api instead of "cognitoUser.AuthenticateUser". This way I can get the challenge response and pass it on in sequence. But as per my initial question, I am wondering if I can implement the below code and be able to route users to input MFA code (without duplicating MFA sms message)
AWS.config.update({
region: process.env.Region
});
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const poolData = { //--Moved to env variables
UserPoolId: process.env.UserPoolId, // your user pool id here
ClientId: process.env.ClientId // your app client id here
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
router.post('/api/authenticateuser', (req, res) => {
const val = req.body;
var userData = {
Username: val.value.user, // your username here
Pool: userPool
};
var authenticationData = {
Username: val.value.user, // your username here
Password: val.value.pass, // your password here
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('You are now logged in.');
console.log(result);
const accessToken = result.getAccessToken().getJwtToken();
const idToken = result.getIdToken().getJwtToken();
res.json({
accessToken,
idToken
});
},
onFailure: function(err) {
res.json(err);
},
mfaRequired: function(codeDeliveryDetails) {
// console.log("mfa enabled");
// var verificationCode = prompt('Please input verification code' ,'');
// cognitoUser.sendMFACode(verificationCode, this);
// res.json({ MFA:codeDeliveryDetails})
}
});
})
I'm using amazon-cognito-identity-js to authenticate my user pool users.And after authenticating it's passing access token, id token and refresh token.And also the user id is there(user's id in user pool).Is there any way to get user attributes like(nick name,birthday,address) with these tokens or the with the user id in aws-cognito
Oh it's straight forward with aws sdk CognitoIdentityServiceProvider class.Can use the same access token that we are getting from the user authentication
var params = {
AccessToken: "string"
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.getUser(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} // an error occurred
else{
console.log(data);
} // successful response
})
At the moment I am creating a Firebase API on nodejs. I would like to handle all Firebase stuff (like authentication) with firebase-admin on nodejs. But what is the correct way to authenticate a user over nodejs in firebase-admin without the Javascript Firebase SDK on the client side? On the official documentation for admin I didn't find a function called signInWithEmailAndPassword (like as on the client side SDK) for nodejs. There is only a function called: "getUserByEmail", but this function doesn't check if the user has entered the correct password.
This is my form:
<form class="sign-box" action="/login" method="post">
<div class="form-group">
<input id="username" name="username" type="text" class="form-control" placeholder="E-Mail"/>
</div>
<div class="form-group">
<input id="password" name="password" type="password" class="form-control" placeholder="Password"/>
</div>
<button type="submit" class="btn btn-rounded">Sign in</button>
</form>
Once the form is submitted I pass the values to my API in nodejs:
app.post('/login', urlencodedParser, function (req, res) {
// getting the values
response = {
username: req.body.username,
password: req.body.password
};
// authenticate the user here, but how ?
});
My first idea was to use the Firebase SDK on the client side to sign in with signInWithEmailAndPassword and to get the uid. Once I had the UID I wanted to sent the UID to nodejs and call the function createCustomToken and to return the generated token (with some additional claims) back to the client. Once I get the token back I would use the function signWithCustomToken (on the client side) to authenticate the user. Is this way correct or is there a better way ?
Actually for authentication you will need to use the firebase regular api, no the admin.
First this will give you a refreshed firebase token, not a custom token.
If you like you can do the same to obtain a custom token, if you need a custom token, I also have an example.
npm install firebase --save
const firebase = require("firebase");
const config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
I am posting my login firebase function but you will be able to change it to express easily.
exports.login = functions.https.onRequest((req, rsp)=>{
const email = req.body.email;
const password = req.body.password;
const key = req.body.key;
const _key = '_my_key_';
let token = '';
if(key === _key){
firebase.auth().signInWithEmailAndPassword(email,password).then((user)=>{
//The promise sends me a user object, now I get the token, and refresh it by sending true (obviously another promise)
user.getIdToken(true).then((token)=>{
rsp.writeHead(200, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({token:token}));
}).catch((err)=>{
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({error:err}));
});
}).catch((err)=>{
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify({error:err}));
});
} else {
rsp.writeHead(500, {"Content-Type": "application/json"});
rsp.end(JSON.stringify('error - no key'));
}
});
NOTE: I am using this login function to test my other functions with Postman, so that is why i am sending a key, so I can use this privately.
Now combining the ADMIN and FIREBASE node apy I am able to do a lot of very interesting stuff with HTTP functions on my firebase.
Hope it helps somehow.
For Any Server Side React Users
I was brought here because I was attempting to authenticate users in firebase without the Javascript Firebase SDK on the client side as well. I am building a server side rendered react app. The client-side firebase.auth() does not work on a server-side node environment.
It turns out that you can run firebase.auth() commands inside of componentDidMount(), because that does not run on the server. This is where you can authenticate and get your user's token, and then send it to a cloud function for any server-side rendering that requires user authentication.
On the server side, you can then verify the token with the admin sdk.
You will also need to require firebase/app and firebase/auth, and initialize firebase in your browser-specific bundle.js, so that it is not included in your server's bundle.js
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("User signed in!");
} else {
console.log("User NOT signed in!");
}
});
}
The officially recommended and supported way is to use ID TOKENS
From the official docs:
If your Firebase client app communicates with a custom backend server, you might need to identify the currently signed-in user on that server. To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.
The workflow is:
Use the Firebase Web SDK in your client
The user logs in with any of the authentication methods
Retrieve the ID token on the client
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
Send this token to the server
Server verifies the ID token with the Firebase Admin SDK
// idToken comes from the client app
getAuth()
.verifyIdToken(idToken)
.then((decodedToken) => {
const uid = decodedToken.uid;
// ...
})
.catch((error) => {
// Handle error
});
your user is securely authenticated and uniquely identified
This is my solution, maybe it can help someone (Node/react). For some reason the client side method signInWithEmailAndPassword seems to work both on the client AND server. Basically this lets you keep the default security rule ".read": "auth != null" without having to use signInAnonymously() hence avoid creating an infinite number of stale users.
server:
const { firebase } = require('../../firebase/frontend');
const { firebase: admin } = require('../../firebase/backend');
const email = process.env.READ_ONLY_EMAIL;
const password = process.env.READ_ONLY_PASSWORD;
export default async (req, res) => {
try {
const { user } = await firebase.auth().signInWithEmailAndPassword(email, password);
const customToken = await admin.auth().createCustomToken(user.uid);
return res.status(200).send(JSON.stringify(customToken));
} catch (error) {
return res.status(404).send(error);
}
};
client:
import fetch from 'isomorphic-unfetch';
import { useState, useEffect } from 'react';
import { firebase } from '../firebase/frontend';
const useUser = (props) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [isAnonymous, setIsAnonymous] = useState(true);
const getCustomToken = async () => {
const response = await fetch('/api/auth', { method: 'POST' });
const json = await response.json();
return json;
};
useEffect(() => {
try {
const unsubscribe = firebase.auth().onAuthStateChanged(async (user) => {
// user exists
if (user && user.email !== 'readonly#myEmailAddress.com') {
setUser(user);
setIsAnonymous(false);
// else sign in user "anonymously"
} else {
setIsAnonymous(true);
const token = await getCustomToken();
firebase.auth().signInWithCustomToken(token);
}
setLoading(false);
});
return () => unsubscribe();
} catch (error) {
console.log('Error signing in user', error);
}
}, []);
return {
user,
isAnonymous,
loading
// etc...
};
};
export default useUser;