Logo

dev-resources.site

for different kinds of informations.

Authentication & Authorization

Published at
7/8/2024
Categories
authjs
javascript
webdev
backenddevelopment
Author
suhaspalani
Author
11 person written this
suhaspalani
open
Authentication & Authorization
  • Topic: "Implementing Authentication with JWT"
  • Description: How to implement authentication and authorization using JSON Web Tokens (JWT).

Content:

1. Introduction to JWT

  • What is JWT: Explain JSON Web Tokens and their structure.
  • Why JWT: Discuss the benefits of using JWT for authentication.

2. Setting Up JWT

  • Install Dependencies:

    npm install jsonwebtoken bcryptjs
    
  • Configure JWT:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const secret = 'your_jwt_secret'; // Use an environment variable in real applications
```
Enter fullscreen mode Exit fullscreen mode

3. User Model and Registration

  • Define User Schema:

    const userSchema = new mongoose.Schema({
      username: { type: String, required: true, unique: true },
      password: { type: String, required: true }
    });
    
    userSchema.pre('save', async function(next) {
      if (this.isModified('password')) {
        this.password = await bcrypt.hash(this.password, 10);
      }
      next();
    });
    
    const User = mongoose.model('User', userSchema);
    
  • User Registration Endpoint:

    app.post('/register', async (req, res) => {
      const user = new User(req.body);
      try {
        await user.save();
        res.status(201).json(user);
      } catch (err) {
        res.status(400).json({ error: err.message });
      }
    });
    

4. User Login and Token Generation

  • Login Endpoint:

    app.post('/login', async (req, res) => {
      const { username, password } = req.body;
      try {
        const user = await User.findOne({ username });
        if (user && await bcrypt.compare(password, user.password)) {
          const token = jwt.sign({ id: user._id, username: user.username }, secret, { expiresIn: '1h' });
          res.json({ token });
        } else {
          res.status(401).send('Invalid credentials');
        }
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    

5. Protecting Routes with Middleware

  • Authentication Middleware:

    const authMiddleware = (req, res, next) => {
      const token = req.header('Authorization').replace('Bearer ', '');
      if (!token) {
        return res.status(401).send('Access denied');
      }
      try {
        const decoded = jwt.verify(token, secret);
        req.user = decoded;
        next();
      } catch (err) {
        res.status(400).send('Invalid token');
      }
    };
    
  • Protecting an Endpoint:

    app.get('/profile', authMiddleware, async (req, res) => {
      try {
        const user = await User.findById(req.user.id);
        res.json(user);
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    

6. Testing Authentication

  • Using Postman: Demonstrate how to register a user, log in to receive a JWT, and use the JWT to access protected routes.
  • Example Workflow:
    1. Register a new user at /register.
    2. Log in with the new user at /login to get a token.
    3. Access the protected /profile route using the token in the Authorization header.

This detailed breakdown for weeks 7 to 10 includes explanations and hands-on code examples to provide a comprehensive learning experience.

authjs Article's
30 articles in total
Favicon
Authentication System Using NodeJS
Favicon
Add Authjs to Next.js 15 app router with GitHub Authentication
Favicon
Master Authentication with Auth.js, Next.js, and PostgreSQL: A Comprehensive Guide
Favicon
Nuxt Authorization: How to Implement Team Role-Based Access Control in Nuxt 3
Favicon
Mastering Authentication in Next.js: A Step-by-Step Guide to GitHub Login with Auth.js
Favicon
User Authentication with Auth.js in Next.js App Router
Favicon
Lucia Auth is getting deprected
Favicon
Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide
Favicon
Simple Next.js Magic Link JWT Authentication with Prisma, PostgreSQL, and Resend
Favicon
Password Authentication with Auth.js in Astro and Customizing Session Information (auth-astro)
Favicon
Basic Authentication for Nuxt.js (JSON Web Token + Local Storage)
Favicon
Implementing Federated Sign-Out with Auth.js in Next.js 14 App Router
Favicon
Integrating LinkedIn Authentication with NextAuth.js: A Step-by-Step Guide
Favicon
Implementing auth.js v5 with Prisma and Supabase in Next.js
Favicon
Auth, OAuth, and Auth0: What is what?
Favicon
JWT Authentication and Cookie Management in Web Applications
Favicon
๐Ÿš€ Exciting News!
Favicon
Data Persistence (Cookies, Sessions, Tokens, LocalStorage and SessionStorage)
Favicon
Fashion website
Favicon
The Firebase Shortcut: Simplifying Next.js Authentication
Favicon
Authentication system in Next.Js using Auth.js
Favicon
Roles based authentication using Nextauth and next.js
Favicon
Authentication & Authorization
Favicon
Top User Authentication Tools for Developers
Favicon
Comprehensive Guide to SvelteKitAuth: Secure Authentication for SvelteKit Apps
Favicon
Building a Secure OTP-based Login System in Next.js
Favicon
Implementing Secure Authentication in Next.js with JWT and MongoDB. Protect Routes using middleware
Favicon
Next.js 14 and NextAuth v4 : Credentials Authentication A Detailed Step-by-Step Guide
Favicon
Building a Secure OTP-based Login System in Next.js
Favicon
Web3Auth(ๆฌกใฎjs)ใ‚’ไฝฟ็”จใ—ใŸXRP Ledgerใ‚ขใ‚ซใ‚ฆใƒณใƒˆใฎไฝœๆˆ:ใ‚นใƒ†ใƒƒใƒ—ใƒใ‚คใ‚นใƒ†ใƒƒใƒ—ใ‚ฌใ‚คใƒ‰

Featured ones: