Skip to main content

14.1 - Session Based Authentication and Oauth Providers

In a backend system, authentication and middleware are critical components that ensure security, proper request handling, and smooth communication between the client and server.

What is Authentication?

Authentication is the process of verifying the identity of a user or system. When a user tries to access a resource, the backend needs to confirm that they are who they claim to be. This prevents unauthorized access to sensitive data and resources.

Roles of Authentication in the Backend

  • Identity Verification: Ensures that the user is legitimate, usually through credentials like usernames and passwords, tokens, or API keys.
  • Access Control: Once authenticated, the backend can control what the user is allowed to do based on their identity (this is known as authorization).
  • Session Management: Keeps track of the user's authenticated session, allowing them to continue interacting with the application without re-authenticating.

Common Use Cases

  • User Login: When a user logs in with their username and password.
  • API Access: Ensuring that API requests are coming from authorized users or systems.
  • Single Sign-On (SSO): Allowing users to log in once and gain access to multiple systems without re-entering credentials.

What is Middleware?

Middleware is software that acts as an intermediary between the server and the application logic. It intercepts requests and responses, allowing you to perform actions such as modifying the request, adding security layers, logging, or handling errors.

Roles of Middleware in the Backend

  • Request/Response Manipulation: Modify incoming requests or outgoing responses.
  • Security: Implement authentication, authorization, and other security measures.
  • Logging: Track requests, errors, and other important events.
  • Error Handling: Catch and handle errors before they reach the application logic.

Common Use Cases

  • Authentication Middleware: Checks if a user is authenticated before allowing access to certain routes.
  • Logging Middleware: Logs each request for debugging and monitoring purposes.
  • CORS Middleware: Manages Cross-Origin Resource Sharing (CORS) to control which domains can access your resources.

Session-Based and OAuth Providers

tip

OAuth and session-based access are two ways to manage user access.

Session-Based Access is like having a key to a single door. When a user logs in, the server gives them a session key that keeps them logged in as they move around the website. This method is simple and works well if the user is staying on one site but can be tricky if you need to work across different sites or services.

OAuth is like using a master key that lets you access multiple doors without needing separate keys for each one. It’s used when you want to allow an app to access your data on another service, like letting a fitness app see your Google Fit data. OAuth is good for connecting different services and for Single Sign-On (SSO), but it’s more complex to set up compared to session-based authentication.

Session-Based Access

Session-Based Access is one of the most traditional forms of authentication. It involves creating a session on the server after the user successfully logs in.

How It Works

  1. User Logs In: The user submits their credentials (username and password) to the server.
  2. Session Created: If the credentials are correct, the server creates a session, typically storing the session ID in memory or a database.
  3. Session ID Stored in Cookie: The server sends the session ID back to the client, usually stored in a cookie.
  4. Subsequent Requests: For each subsequent request, the client sends the session ID cookie, allowing the server to identify the user.
  5. Session Expiry: Sessions can expire after a certain period, requiring the user to log in again.

Use Cases

  • Web Applications: Commonly used in web apps where the server maintains user session states.
  • Internal Systems: Often used in corporate or internal applications where security is managed centrally.
Example: Express Session Middleware

In an Express.js application, you can use express-session to manage sessions:

import session from "express-session";

app.use(
session({
secret: "your-secret-key",
resave: false,
saveUninitialized: true,
cookie: { secure: true },
})
);

Session-Based Access: Configuration Options

In the express-session middleware configuration, you can specify several options to control session behavior:

  • secret: A secret key to sign the session ID cookie. This ensures the cookie's integrity and protects it from tampering.
  • resave: Forces the session to be saved back to the session store, even if it wasn't modified. This is useful to ensure that the session data is always up-to-date.
  • saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. This is useful if you want to create a session for every request, even if the user has not interacted with the session.
  • cookie: Configures the session ID cookie, including its security settings. You can set options like secure, httpOnly, and maxAge to control the cookie's behavior.

OAuth Providers

OAuth is an open standard for access delegation. It allows websites or applications to access a user's data without exposing their credentials. OAuth is commonly used for Single Sign-On (SSO) and for authorizing third-party applications to access a user's data.

How It Works

  1. User Initiates OAuth Flow: The user clicks a "Login with Google/Facebook" button.
  2. Redirect to OAuth Provider: The user is redirected to the OAuth provider (e.g., Google) to authenticate.
  3. Authorization Code: If the user consents, the OAuth provider redirects back to your application with an authorization code.
  4. Exchange for Token: Your application exchanges this authorization code for an access token.
  5. Access API with Token: The access token is used to authenticate API requests on behalf of the user.

Use Cases

  • Social Media Integration: Allowing users to log in with their social media accounts (Google, Facebook, Twitter).
  • Third-Party API Access: Authorizing third-party apps to access your account data (e.g., allowing an app to post on your behalf on Twitter).
  • Single Sign-On (SSO): Implementing single sign-on across multiple services, allowing users to log in once and gain access to multiple applications.
Example: Using OAuth with Passport.js

Passport.js is a popular middleware for authentication in Node.js, supporting various OAuth strategies.

import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";

passport.use(
new GoogleStrategy(
{
clientID: "YOUR_GOOGLE_CLIENT_ID",
clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
callbackURL: "http://yourdomain.com/auth/google/callback",
},
function (accessToken, refreshToken, profile, done) {
// Logic to find or create the user in your database
return done(null, profile);
}
)
);

// Route to initiate OAuth flow
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile", "email"] })
);

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

In this Example:

  • GoogleStrategy: Configures Passport to use Google OAuth 2.0 for authentication.
  • passport.authenticate: Handles the OAuth flow by redirecting users to Google for authentication and processing the callback.