Actually explain about user login any website .How the authentication works in the server side.

Have you ever wondered how authentication works? what’s behind of the complexity.Actually,nothing magic.When you login to any website using E-mail and Password.It’s a way of encrypting a value, in turn creating unique token that will be identifiers correct User (or) Not.How create token to user, I’ll explain everything below.

This will be step by step process first register and login to any website.The user E-mail and Password add token based authentication to an existing REST API. The authentication strategy in question is JWT(JSON web Token).

The official definition of JWT:

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claim JSON Web Signature (JWS) structure or as the plain text of a JSON Web Encryption (JWE), enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

-Internet Engineering Task Force(IETF)

In simple one statement looks like. A JWT is an encoded string of characters which is safe to send between two computers both have HTTPS. A token represent a value that is accessible only by the computer that is secret key which as encrypted.

Think in application view? Let’s consider user register and login account to website. After time user wants sign in to website.They send a request with the required credential such as email and password to the server. The server checks to see credential valid. If there, the server creates a token using the payload and secret key. Then server token send it back to the client. The client, in turn saves the token to use it in every other request the user will send.If user wants see their credential adding token to request headers is a way of authorizing the user credentials.

Okay,before going dirty your hands by coding. I will except you already basic ideal given below resources. If not, I am strongly recommend knowing resources before dying coding part. They are:

  • Node.js
  • mlab
  • Visual Studio Code
  • Postman

Let’s start writing some code, shall we?

well,, not yet actually. We need set up environment in the visual studio code looks like

In visual studio code editor left hand side will be location path folders,right hand side top window will be actually writing coding and below that terminal window actually install any packages and server running in this terminal.

Jump over to mlab, create an account on database, and open up your dashboard. Create a new, name a new database, name it as you wise and proceed to its configuration page. Add a database user to your database and copy the connection string from the dashboard to your code.

All you need to do now is to change the placeholder values for <duser> and <dbpassword>. Replace them with in the username and password of the user create for the database.

Finally, some code.

Well, first of all we want to add user authentication. Meaning, implement a system for registering and logging user in. In Visual studio code terminal window type below sentence one after one execution once completed.

npm init
npm i express gravatar bcryptjs jsonwebtoken passport
npm i validator mongoose body-parser

Let’s open file in visual studio code server.js. Here server.js is name of the file,name it as you wise.In above all the packages install in the package.json. All the packages used in your code and also REST api call used crud application.

You should see Express server listening on port 5000 get logged to the terminal.

  • Add this demo piece of code to the top the server.js
const express = require("express");
const mongoose = require("mongoose");
const app=express();
app.get('/',(req,res)=>{
res.json({message:"Get posts working"});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port'+port);

Save file run in the terminal window type by below sentence.

$ node server

Let’s say the user I created for the database is named awesome with a password of awesome123. Having that in mind, the keys.js that willl be open new folder in that save file.

  • Add piece of code adding to keys.js
module.exports = {
mongoURI:
"mongodb://awesome:awesome123@ds121183.mlab.com:21183/create",
secretOrKey: "secret"
};
  • Add remaining piece of code to server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routers/api/users");
const app = express();
// Passport middleware
app.use(passport.initialize());
// Passport Config
require("./config/passport")(passport);
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// Use Routes
app.use("/api/users", users);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port'+port);

Now entering into user register in any website.

Let’s start you’re ready to start adding the register logic.Create a folder named routers in that other folder api and start out by adding a file named users.js.

  • Add this piece of code to the top of the users.js
const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const passport = require("passport");
const User = require("../../models/User");

That’s all the module we need to implement our desired register. Now you’re ready to create a /register endpoint. Add this piece of code to your users.js.

// Load Input Validation
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
router.post("/register", (req, res) => {
const { errors, isValid } = validateRegisterInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({ email: req.body.email }).then(user => {
if (user) {
errors.email = "Email already exists";
return res.status(400).json(errors);
} else {
const avatar = gravatar.url(req.body.email, {
s: "200", // Size
r: "pg", // Rating
d: "mm" // Default
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
module.exports = router;
  • Let’s start you’re ready to start adding the User Schema.Create a folder named models start out by adding a file named User.js. In this User Schema what are the minimum requirements of the user information that create register to website.
  • Add this piece of code to the User.js.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("users", UserSchema);

Let’s test in the Postman.

open up your REST API testing tool of choice,I use Postman if any other application like Insomnia free to use.

If check it once server running or not in terminal window. If not running terminal window type.

$ node server

Open up postman and hit the register endpoint (/api/users/register). Make sure to pick POST method and x-www-form-url-encoded. Now, if not adding anything in the body. Showing minimum requirement information about user mandatory looks like given below.

Let’s added body information like name,email,password and after that again send request in the postman.It’s looks like register completed.

Now entering into user login in website

Let’s start you’re ready to start adding the login logic.Create a folder named routers in that other folder api and start out by adding a file named users.js.

  • Add this piece of code to the top of the users.js
// @route   GET api/users/login
// @desc Login User / Returning JWT Token
// @access Public
router.post("/login", (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
// Find user by email
User.findOne({ email }).then(user => {
// Check for user
if (!user) {
errors.email = "User not found";
return res.status(404).json(errors);
}
// Check Password
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User Matched
const payload = { id: user.id, name: user.name, avatar: user.avatar }; // Create JWT Payload
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
errors.password = "Password incorrect";
return res.status(400).json(errors);
}
});
});
});
module.exports = router;

Let’s test in the Postman.

open up your REST API testing tool of choice,I use Postman if any other use any other application like Insomnia free to use.

If check it once server running or not in terminal window. If not running terminal window type.

$ node server

Open up postman and hit the register endpoint (/api/users/login). Make sure to pick POST method and x-www-form-url-encoded. After implementing the registration, we should create a way for existing users to log in. Server check user login credential matches users register stored in database. If they match we .sign() a token. That’s pretty much it. Let’s try it out.

Let’s start you’re ready to start adding the password logic.Create a folder named config start out by adding a file named password.js.

  • Add this piece of code to the top of the password.js
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const mongoose = require("mongoose");
const User = mongoose.model("users");
const keys = require("../config/keys");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
})
);
};

Let’s start you’re ready to start adding the login logic.Create a folder named routers in that other folder api and start out by adding a file named users.js In this check authenticate work retrieve user data from the token.

  • Add this piece of code to the top of the users.js
// @route   GET api/users/current
// @desc Return current user
// @access Private
router.get(
"/current",
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
}
);
module.exports = router;

Let’s test in the Postman.

Open up postman and hit the current endpoint (/api/users/current). Make sure to pick GET method. After implementing login user we generating token. The token added to the Headers part, in the body part make sure Key will be Authorization added and value will be token of the user added.This is way user check information obtain token. It’s working awesome.

Wrap Up

I am sharing my experience. Some of the concepts are hard to understand. I am recommend you go through the code by yourself and try your best to get it to work.Again, here’s here’s the GitHub repository.This first blog writing medium.com if any mistakes in the blog sorry for that.

Do you think this tutorial will be of help to someone? Do not hesitate to share.

Thank you for sending your valuable time reading in this Blog. 👍 👍 👍