Next.js course ยท Module 7: Authentication and Authorization

Authentication strategies

5 min read ยท
In this lesson6

In previous parts, we discussed the basics of authentication and implemented simple authorization using JWT. Now we will dive into different authentication strategies you can apply in your applications.

Token-based vs. session-based authentication

The two main approaches to authentication are:

1. Session-based Authentication

In this approach, the server maintains session state for each logged-in user:

// Example session configuration in Express
import express from 'express';
import session from 'express-session';

const app = express();

app.use(session({
  secret: 'secret-session-key',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, maxAge: 3600000 } // 1 hour
}));

app.post('/login', (req, res) => {
  // After successful authentication
  req.session.authenticated = true;
  req.session.userId = user.id;
  res.send({ success: true });
});

app.get('/protected', (req, res) => {
  if (req.session.authenticated) {
    // User has a valid session
    res.send('Protected data');
  } else {
    res.status(401).send('Access denied');
  }
});

Advantages:

  • Ease of implementation and maintenance
  • Ability to immediately invalidate a session
  • Does not require additional processing on the client side

Disadvantages:

  • Server load (state storage)
  • Scalability issues in distributed architecture
  • Difficulties in implementation for mobile applications

2. Token-based Authentication

In this approach, the server generates a token that the client stores and sends with each request:

// Example JWT implementation in Express
import express from 'express';
import jwt from 'jsonwebtoken';

const app = express();
const JWT_SECRET = 'secret-jwt-key';

app.post('/login', (req, res) => {
  // After successful authentication
  const token = jwt.sign(
    { userId: user.id, email: user.email },
    JWT_SECRET,
    { expiresIn: '1h' }
  );

  res.send({ token });
});

// Token verification middleware
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).send('Missing authorization token');
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).send('Invalid token');
  }
};

app.get('/protected', verifyToken, (req, res) => {
  res.send('Protected data');
});

Advantages:

  • Statelessness - easier scaling
  • Works well in mobile apps and SPAs
  • Ability to store additional information in the token

Disadvantages:

  • More difficult to invalidate a token before expiration
  • Vulnerability to theft (if adequate security measures are not applied)
  • Larger tokens may increase network load

OAuth 2.0 and social authentication

OAuth 2.0 is an authorization protocol standard that allows applications to access user resources on another server without sharing credentials.

Implementing authentication with Google

// OAuth implementation with Google in Express and Passport
import express from 'express';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

const app = express();

// Passport configuration
passport.use(new GoogleStrategy({
    clientID: 'YOUR_GOOGLE_CLIENT_ID',
    clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  },
  function(accessToken, refreshToken, profile, done) {
    // Find or create the user in the database
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

// Authentication routes
app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    // Redirect after successful authentication
    res.redirect('/dashboard');
  }
);

Multi-factor authentication (MFA)

Multi-Factor Authentication (MFA) increases security by requiring the user to provide two or more proofs of identity.

Example MFA implementation using TOTP (Time-based One-Time Password)

// 2FA implementation with TOTP in Node.js
import express from 'express';
import speakeasy from 'speakeasy';
import QRCode from 'qrcode';

const app = express();
app.use(express.json());

// Generating a secret key for the user
app.post('/generate-2fa', (req, res) => {
  const secret = speakeasy.generateSecret({
    name: 'MyApp:' + req.user.email
  });

  // Save secret.base32 in the database for this user
  saveUserSecret(req.user.id, secret.base32);

  // Generate the QR code
  QRCode.toDataURL(secret.otpauth_url, (err, imageUrl) => {
    if (err) {
      return res.status(500).send('QR code generation error');
    }

    res.json({
      secret: secret.base32,
      qrCode: imageUrl
    });
  });
});

// One-time code verification
app.post('/verify-2fa', (req, res) => {
  const { token } = req.body;

  // Fetch the user's secret from the database
  const userSecret = getUserSecret(req.user.id);

  const verified = speakeasy.totp.verify({
    secret: userSecret,
    encoding: 'base32',
    token: token
  });

  if (verified) {
    // Enable 2FA for the user in the database
    enableUser2FA(req.user.id);
    res.json({ success: true });
  } else {
    res.status(400).json({ success: false, message: 'Invalid code' });
  }
});

Single Sign-On (SSO)

Single Sign-On is an authentication process that allows a user to access multiple applications after a single login.

Implementing SSO with SAML

// Example SAML SSO implementation in Express
import express from 'express';
import passport from 'passport';
import { Strategy as SAMLStrategy } from 'passport-saml';

const app = express();

passport.use(new SAMLStrategy({
  path: '/login/callback',
  entryPoint: 'https://sso.example.com/saml2/idp/SSOService.php',
  issuer: 'my-application',
  cert: 'IDENTITY_PROVIDER_CERTIFICATE'
}, (profile, done) => {
  // Find or create the user in the database
  return done(null, {
    id: profile.nameID,
    email: profile.email,
    name: profile.displayName
  });
}));

app.get('/login',
  passport.authenticate('saml', { failureRedirect: '/login/fail' }),
  (req, res) => res.redirect('/')
);

app.post('/login/callback',
  passport.authenticate('saml', { failureRedirect: '/login/fail' }),
  (req, res) => res.redirect('/')
);

Authentication security best practices

  1. Secure passwords

    • Require strong passwords (length, complexity)
    • Store only encrypted passwords (use strong algorithms like bcrypt)
    • Implement login attempt limits
  2. Token security

    • Store JWT tokens securely (HttpOnly cookies)
    • Use short token validity periods
    • Implement token rotation and invalidation
  3. Transport

    • Always use HTTPS to transmit credentials
    • Implement HSTS (HTTP Strict Transport Security)
    • Secure cookies with the Secure and SameSite flags
  4. General rules

    • Regularly perform security audits
    • Implement activity logging and monitoring
    • Always apply the principle of least privilege

Summary

Choosing the right authentication strategy depends on many factors, such as:

  • Application security requirements
  • Target user group
  • Type of application (mobile, web, hybrid)
  • Scalability and performance

Remember that authentication security is an ongoing process requiring regular updates and adaptation to new threats and security standards.

In the next lessons, we will move on to implementing advanced authorization mechanisms and user permission management.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. NextAuth.js is:

  2. 2. JWT (JSON Web Token) is:

Hands-on tasks in the game

  • Vertical ordering

    Arrange the stages of OAuth 2.0 Authorization Code Flow:

  • Click in order

    Arrange the useSession destructuring syntax in NextAuth

  1. QuestionNextAuth.js is:
  2. QuestionJWT (JSON Web Token) is:
  3. Put in orderStages of OAuth 2.0 Authorization Code Flow
  4. Click in orderOrder: const โ†’ { โ†’ data:

Useful articles