Implementing Authentication and Authorisation in Full Stack Projects

Full-Stack-Projects

Introduction  

Implementing authentication and authorization in full-stack projects is essential to ensure the security and proper functioning of your application. Authentication verifies a user’s identity, while authorisation determines what resources a user can access. Both concepts play a pivotal role in safeguarding data, user information, and application integrity and are key topics covered in any standard Java full stack developer course. Let us dive into how to implement these processes effectively in a full-stack project.

Understanding Authentication and Authorization

Authentication is the process of verifying who a user is. It involves checking credentials like usernames and passwords or leveraging other methods like social logins (Google, Facebook) and biometric scans.

Authorization, on the other hand, determines what authenticated users can access. It sets rules and permissions, ensuring that users have the appropriate level of access to resources or functionalities within an application.

Common Authentication Methods

While most application developers will be conversant with the following common authentication techniques, a quick revisit will be useful before you enroll in a Java full stack developer course just to ensure that the concepts are quite clear before you step into practice-oriented lessons.

  • Username and Password: The most basic form of authentication where users register with an email/username and password.
  • OAuth: A popular open standard for access delegation. It allows users to log in using third-party services like Google, Facebook, or GitHub.
  • JSON Web Tokens (JWT): JWTs are often used for stateless authentication. Once logged in, users receive a token, which they present with every subsequent request.
  • Multi-Factor Authentication (MFA): Combines multiple verification methods (e.g., password and SMS code) to enhance security.

Implementing Authentication in a Full Stack Project

In this section, we will go through the steps involved in implementing authentication using Node.js (backend) and React (frontend), focusing on JWT for stateless authentication in the lines usually followed in the course curriculum of an inclusive technical course for full-stack developers, a full stack developer course in Bangalore, for instance.

Step 1: Setting Up the Backend with Node.js and Express

Install required packages:

bash

Copy code

npm install express jsonwebtoken bcryptjs cors mongoose

jsonwebtoken: Handles the creation and verification of JWTs.

bcryptjs: Used for hashing passwords.

Create a User Model (MongoDB example):

javascript

Copy code

const mongoose = require(‘mongoose’);

const userSchema = new mongoose.Schema({

    username: { type: String, required: true, unique: true },

    password: { type: String, required: true },

});

module.exports = mongoose.model(‘User’, userSchema);

Set Up Authentication Routes:

Register Route:

javascript

Copy code

const express = require(‘express’);

const bcrypt = require(‘bcryptjs’);

const User = require(‘./models/User’);

const router = express.Router();

router.post(‘/register’, async (req, res) => {

    const { username, password } = req.body;

    const hashedPassword = await bcrypt.hash(password, 10);

    const newUser = new User({ username, password: hashedPassword });

    await newUser.save();

    res.status(201).send(“User registered”);

});

Login Route:

javascript

Copy code

const jwt = require(‘jsonwebtoken’);

router.post(‘/login’, async (req, res) => {

    const { username, password } = req.body;

    const user = await User.findOne({ username });

 

    if (user && (await bcrypt.compare(password, user.password))) {

        const token = jwt.sign({ id: user._id }, ‘secretKey’, { expiresIn: ‘1h’ });

        res.json({ token });

    } else {

        res.status(400).send(‘Invalid credentials’);

    }

});

Step 2: Protecting Routes with Authorisation Middleware

To ensure only authenticated users can access certain routes:

Create Authorisation Middleware:

javascript

Copy code

const authenticateToken = (req, res, next) => {

    const token = req.header(‘Authorization’).split(‘ ‘)[1];

    if (!token) return res.status(401).send(‘Access Denied’);

 

    jwt.verify(token, ‘secretKey’, (err, user) => {

        if (err) return res.status(403).send(‘Invalid Token’);

        req.user = user;

        next();

    });

};

Apply Middleware to Protected Routes:

javascript

Copy code

router.get(‘/dashboard’, authenticateToken, (req, res) => {

    res.send(‘Welcome to the Dashboard’);

});

Step 3: Setting Up the Frontend with React

Install Axios for making HTTP requests:

bash

Copy code

npm install axios

Creating Authentication Functions:

Login Function:

javascript

Copy code

import axios from ‘axios’;

const loginUser = async (username, password) => {

    try {

        const response = await axios.post(‘http://localhost:5000/login’, { username, password });

        localStorage.setItem(‘token’, response.data.token);

        return response.data;

    } catch (error) {

        console.error(‘Login failed:’, error);

    }

};

Accessing Protected Resources:

javascript

Copy code

const fetchDashboardData = async () => {

    const token = localStorage.getItem(‘token’);

    const response = await axios.get(‘http://localhost:5000/dashboard’, {

        headers: { Authorization: `Bearer ${token}` }

    });

    return response.data;

};

Implementing Authorisation

Authorisation ensures that users have specific permissions based on their roles (e.g., admin, user).

Role-Based Access Control (RBAC)

Assign Roles: Extend the user model to include roles:

javascript

Copy code

const userSchema = new mongoose.Schema({

    username: String,

    password: String,

    role: { type: String, enum: [‘user’, ‘admin’], default: ‘user’ }

});

Protect Routes Based on Roles: Modify the authenticateToken middleware:

javascript

Copy code

const authorizeRoles = (roles) => (req, res, next) => {

    if (!roles.includes(req.user.role)) {

        return res.status(403).send(‘Access Denied’);

    }

    next();

};

 

router.get(‘/admin’, authenticateToken, authorizeRoles([‘admin’]), (req, res) => {

    res.send(‘Admin Dashboard’);

});

Best Practices for Authentication and Authorization

One of the main benefits of enrolling in technical courses such as a Java full stack developer course in reputed learning centres is that the course will include lessons on best practices delivered by experts having experience in relevant technologies.  Here are some best practice tips covered in a standard technical course for full-stack developers:         

  • Hash Passwords: Always hash passwords before storing them in the database using libraries like bcrypt.
  • Use HTTPS: Ensure all data, especially sensitive information, is transmitted over HTTPS.
  • Implement MFA: Multi-factor authentication adds an extra layer of security.
  • Set Token Expiry: JWTs should have expiration times to limit the risk of token misuse.
  • Refresh Tokens: Use refresh tokens to allow users to stay logged in without constantly requesting credentials.

Conclusion

Implementing authentication and authorisation is critical for any full-stack project. It ensures that only verified and authorised users can access and interact with your application. By using tools like JWT, bcrypt, and middleware in frameworks such as Express and React, professional full-stack developers who have the learning from a full stack developer course in Bangalore and such technical learning hubs can create a secure and efficient authentication and authorisation system. Remember, security should always be a top priority in your application to protect user data and ensure seamless and secure access to resources.

Business Name: ExcelR – Full Stack Developer And Business Analyst Course in Bangalore

Address: 10, 3rd floor, Safeway Plaza, 27th Main Rd, Old Madiwala, Jay Bheema Nagar, 1st Stage, BTM 1st Stage, Bengaluru, Karnataka 560068

Phone: 7353006061

Business Email: enquiry@excelr.com