Authentication for your application

20 Sep 2022
6 min read

Authentication

A process or act of proving something to be valid in general or verifying the identity of a particular user or validity of a process in application terms is what authentication is. But how exactly does one prove to be the person they claim to be in order to access the application or do specific tasks?

Well, there are certain methods one can incorporate to carry out authentication as follows-

Username/Email & Password-based Authentication:

This involves saving the username/email and password to a database which the user provided at the time of signing up on that application following which the user will log in using those credentials to perform registered user-specific actions.

Note:
Before the username and password get saved in the database,

  • The database is queried to check whether the email provided already exists or not.
  • Password provided by the user is hashed to provide immunity against any cyber attacks in which, if the database gets compromised, the original password won’t be leaked.

Following this, in order to perform user-specific tasks in that application, one must be logged in using their username/email and password.

Implementation

The following snippet demonstrates the server-side implementation of username/email and password-based authentication using Node.js and mongoDb

app.post("/register", async (req, res) => {
  try {
  
    // Username/email and password is collected from user input
    const {email, password } = req.body;

    if (!(email && password)) {
      res.status(400).send("All fields are required");
    }

    // Database is queried to check if email already exists or not
    const isPresent = await User.findOne({ email });

    // If already present then log error
    if (isPresent) {
      res.status(400).send("User already exists");
    }

    // Else hash the password
    const encPass = await bcrypt.hash(password, 10);

    // Finally create the user and save it in the database
    const user = await User.create({
      email,
      password: encPass,
    });
    
    res.status(201).json(user);
  } catch (error) {
    console.log(error);
  }
});

Now, as the user has been registered, they can log on to the application and perform actions they are authorized for.

Implementation

The following snippet demonstrates the server-side implementation of log-in functionality using Node.js and mongoDb

app.post("/login", async (req, res) => {
  try {
    // username and password is fetched from user input
    const { email, password } = req.body;
    
    // Database is queried to find user
    const user = await User.findOne({ email });
    
    // If user is found at first we remove the correct password for security concerns
    if (user && (await bcrypt.compare(password, user.password))) {
      user.password = undefined;

    } else {
      // If user not found then return error
      res.status(400).send("Password or username not matched");
    }
  } catch (error) {
    console.log(error);
  }
});

Social Media Authentication:

It provides an efficient way of user management and authentication procedure for the applications and also protects the user’s credentials in case of data leak or any cyberattacks on that application.

This social media authentication involves the creation of a single sign-on application which means that one can register for a number of applications or services without having to enter credentials every time and the respective credentials can be obtained from several social media sites such as Google, Facebook, Twitter etc.

Note: 
Admin can configure what details are required for the sign-up process and while the sign-up, the user is prompted to verify and grant the requested data.

The generic workflow of social media authentication is as follows:

  • While signing up as a new user or logging in as a repeat user, the user is provided with social media options which are configured by the admin.
  • When the user selects an option, the user is redirected to the consent screen or page of that particular social media requesting permission to share listed credentials with the application
  • On accepting you are redirected back to the application and if you are already a user, you’ll be granted access to the application to perform authorized actions else you will be registered as a new user.

Implementation

We can implement social media authentication using passport.js (middleware for authentication). The following demonstrates the implementation of google authentication using passport.js.

  • First of all, we configure the consent screen which asks for all the details required by the application. For this, you should log in or sign up to console.cloud.google.com and have a new project ready.

  • Moving on to the consent screen one can select internal or external based on the application’s status or further deployment plans.

  • On clicking create, we are prompted to modify the consent screen as per our needs. Fill the details accordingly.

  • Moving on to the scopes, here as the admin we are asked to configure what exactly we need from the user’s profile. Select the required and update the preferences.

  • Then move ahead to finally create the consent screen.

Now to configure your application to authenticate users using google with the help of this consent screen we are required to have an Oauth client Id which we can configure in the credentials section.

  • Configure the Oauth client id to redirect to your application after authentication and what will be the origin of the login or sign-up requests.
  • On creating a modal will display your client Id and client secret which we will use to configure our application.

Configuration

For google authentication using passport.js, we can use passport-google-oauth20. Since it is a middleware the authentication framework will be separate from the passport config and only used in the login and routes requiring authentication.

Note:
You can refer to the documentation as it’s very well written, else most welcome to follow ahead.

  • For which we install required packages, then configure the strategy and don’t forget to require the file which stores the strategy in the server/app/index.js or your source file.

const GoogleStrategy = require('passport-google-oauth20').Strategy;
const passport = require("passport");
passport.use(new GoogleStrategy({
//Obtained after creating Oauth client id
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: "http://www.example.com/auth/google/callback"
},
function(accessToken, refreshToken, profile, cb) {
// Database operations
}
));

  • Then embeds the middleware to the routes on which authentication will take place.
router.get("/google",
  passport.authenticate("google", {
    scope: ["profile", "email"],
  }),
  (req, res) => {
    res.send("login with google");
  }
);

// Callback route which we specified in the Oauth client ID

app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
});

Apart from these, there are several methodologies to implement authentication for your application such as authentication using magic links or just another social media medium which I haven’t implemented yet.

Discover more from Tech Shaadi

Subscribe now to keep reading and get access to the full archive.

Continue reading