Introduction
Nowadays we are spotting Node.Js everywhere in the software industry. The demand for Node.Js developers is increasing day by day. Node.Js is the most popular JavaScript framework and an open source server environment that allows you to run JavaScript on the server.
In this article, we will build a Xamarin.Forms authentication app with the help of Node JS with Mongo DB. We will develop our backend API in Node.JS with No SQL database and then consume this REST'ful API in our client app Xamarin.Forms. In this post, I will teach you how to build this app exactly with all frontend and backend-coding. So, let's get started.
Prerequisites
You are required to have basic knowledge of Node JS and intermediate level knowledge of Xamarin.Forms and a basic idea of NoSQL databases like Mongodb.
In the initial stage, you must have installed mongodb and Node on your local PC. I am skipping the installation process of Node and Mongodb.
Backend API (Server Side Application)
Step 1 - Create Database
In this step, we will create a new database in Mongodb for storing user information. Open your Mongodb folder and copy the path. Go to -> C: drive and open your program files and search MongoDB and open this folder inside this open server folder and then go to the bin folder.
C:\Program Files\MongoDB\Server\4.2\bin

Open your command prompt as administrator and hit the follwing commands.
- enter -> cd /d C:\Program Files\MongoDB\Server\4.2\bin
- enter -> mongo
- enter -> use DatabaseName //Write database name in place of DatabaseName whatever you want.
- enter -> db.createCollection('user') //user is Collection Name (Like In SQL Table)

Step 2 - Create Node Project
Create a new folder with your project name and copy the path of your project. Hit the npm init command for creating your node project.

After creating your node project add the follwing npm packages to your node project.
- npm install mongodb //For mongodb connection
- npm install crypto //To encrypt user's password
- npm install express //To create RRSTFul API
- npm install body-parser //For parsing the user form
Open your project folder, add a new js file with name index.js and the following code.
- //Import Packages
- var mongodb = require('mongodb');
- var ObjectID = mongodb.ObjectID;
- var crypto = require('crypto');
- var express = require('express');
- var bodyParser = require('body-parser');
- //Password Utils
- //Create Function to Random Salt
- var generateRandomString = function(length) {
- return crypto.randomBytes(Math.ceil(length / 2)).toString('hex') /* Convert to hexa formate */ .slice(0, length);
- };
- var sha512 = function(password, salt) {
- var hash = crypto.createHmac('sha512', salt);
- hash.update(password);
- var value = hash.digest('hex');
- return {
- salt: salt,
- passwordHash: value
- }
- };
- function saltHashPassword(userPassword) {
- var salt = generateRandomString(16);
- var passwordData = sha512(userPassword, salt);
- return passwordData;
- }
- function checkHashPassword(userPassword, salt) {
- var passwordData = sha512(userPassword, salt);
- return passwordData;
- }
- //Create Express Service
- var app = express();
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({
- extended: true
- }));
- //Create MongoDB Client
- var MongoClient = mongodb.MongoClient;
- //Connection URL
- var url = 'mongodb://localhost:27017' //27017 is default port
- MongoClient.connect(url, {
- useNewUrlParser: true,
- useUnifiedTopology: true
- }, function(err, client) {
- if (err) {
- console.log('Unable to connect to MongoDB server.Error', err);
- } else {
- //Start Web Server
- app.listen(3000, () => {
- console.log('Connected to MongoDb server, Webservice running on on port 3000');
- });
- }
- //Register
- app.post('/register', (request, response, next) => {
- var post_data = request.body;
- var plain_password = post_data.password;
- var hash_data = saltHashPassword(plain_password);
- var password = hash_data.passwordHash;
- var salt = hash_data.salt;
- var firstname = post_data.firstname;
- var lastname = post_data.lastname;
- var mobile = post_data.mobile;
- var email = post_data.email;
- var insertJson = {
- 'firstname': firstname,
- 'lastname': lastname,
- 'email': email,
- 'mobile': mobile,
- 'password': password,
- 'salt': salt
- };
- var db = client.db('ahsannodejs');
- //Check Already Exist Email
- db.collection('user').find({
- 'email': email
- }).count(function(err, number) {
- if (number != 0) {
- console.log('User Email already exist!');
- response.json('User Email already exist!');
- } else {
- //Insert data
- db.collection('user').insertOne(insertJson, function(err, res) {
- console.log('User Registration Successful..');
- response.json('User Registration Successful..');
- });
- }
- });
- });
- //Login
- app.post('/login', (request, response, next) => {
- var post_data = request.body;
- var email = post_data.email;
- var userPassword = post_data.password;
- var db = client.db('ahsannodejs');
- //Check Already Exist Email
- db.collection('user').find({
- 'email': email
- }).count(function(err, number) {
- if (number == 0) {
- console.log('User Email not exist!');
- response.json('User Email not exist!');
- } else {
- //Insert data
- db.collection('user').findOne({
- 'email': email
- }, function(err, user) {
- var salt = user.salt;
- var hashed_password = checkHashPassword(userPassword, salt).passwordHash; //Hash Password with Salt
- var encrypted_password = user.password; //Get Password from user
- if (hashed_password == encrypted_password) {
- console.log('User Login Successful..');
- response.json('User Login Successful..');
- } else {
- console.log('Login Failed Wrong Password..');
- response.json('Login Failed Wrong Password..');
- }
- });
- }
- });
- });
- });
Step 3 - Build and Run
Copy your project path and run your command prompt as administrator and hit node index.js to Run your server.
Client Application
Step 1 - Create a Mobile App (Xamarin.Forms) Project
Open Visual Studio-> New Project-> Templates-> Mobile App-> Xamarin.Forms-> Blank app and give the project name AuthNodeJsMongoXamarin.
(ProjectName: AuthNodeJsMongoXamarin)
Step 2 - Add NuGet Package
After creating a blank project, first, add Refit NuGet package to this project by right-clicking on References and select manage NuGet packages.
Step 3 - Create Login Page
Next, open Solution Explorer-> Project Name-> MainPage.xaml. Open MainPage.xaml file and add the following code.
(FileName: MainPage.xaml)
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:d="http://xamarin.com/schemas/2014/forms/design"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- x:Class="AuthNodeJsMongoXamarin.MainPage">
- <StackLayout HorizontalOptions="Center" VerticalOptions="Start">
- <Image x:Name="imgBanner" Source="NodeJs.jpg" ></Image>
- <Label Margin="0,0,0,10" Text="Authentication with Mongo Using Node.Js" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
- <StackLayout Padding="10,10,10,10">
- <Entry x:Name="txtEmail" Placeholder="Enter Email"></Entry>
- <Entry x:Name="txtPassword" Placeholder="Enter Password" IsPassword="True"></Entry>
- <Label FontSize="Caption" Text="If you don't have credentials to SignIn? Please click on Registeration button."/>
- </StackLayout>
- <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
- <Button BackgroundColor="Beige" x:Name="btnSignIn" WidthRequest="200" Text="SignIn" Clicked="btnSignIn_Clicked" />
- <Button BackgroundColor="LightSeaGreen" x:Name="btnRegister" WidthRequest="200" Text="Registeration" Clicked="btnRegister_Clicked" />
- </StackLayout>
- <Label HorizontalTextAlignment="Center" Margin="0,0,0,10" x:Name="txtSignInResult" TextColor="Black" FontSize="Large"/>
- </StackLayout>
- </ContentPage>
Step 3 - Create Registration Page
Add a new ContentPage by going to Solution Explorer-> Project Name. Right click to add a new item, select ContentPage, and give it the name RegisterPage.xaml
Open this layout file and add the following code.




tomoo rizardoPosted Jun 17, 2020, 6:12 AM
Hi @Ahsan Siddique. I followed exactly your code. i have a problem with the registration page, after I hit register it doesn't push to mainpage again. It only stays in the registration page. other than that the code is so clean. thank you in advance