Tech Shaadi

Authentication for your application

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,

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:

Implementation

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

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.

  • 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.

Exit mobile version