You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手开发简单REST API,如何用OpenID Connect/OAuth保护并求实现代码示例

OpenID Connect Implementation Example for Securing a REST API

Hey there! Since you're new to securing REST APIs with OpenID Connect (OIDC), let's walk through a practical, beginner-friendly example using Node.js and Express. We'll leverage the express-openid-connect library—it abstracts most of the OIDC protocol complexity so you can focus on your API logic.

Prerequisites

First, you'll need an OIDC provider (like Auth0, Okta, or Keycloak). Sign up for a free account, create an application (choose "Regular Web Application" since we're building an API backend), and note these values:

  • Client ID
  • Client Secret
  • Issuer URL (looks like https://your-domain.auth0.com/)
  • Callback URL (we'll use http://localhost:3000/callback for this example)

Step 1: Set Up the Project

Initialize a new Node.js project and install dependencies:

npm init -y
npm install express express-openid-connect dotenv

Step 2: Configure Environment Variables

Create a .env file in your project root to store sensitive OIDC configs:

CLIENT_ID=your-client-id-here
CLIENT_SECRET=your-client-secret-here
ISSUER_BASE_URL=https://your-issuer-domain.com
BASE_URL=http://localhost:3000
CALLBACK_URL=http://localhost:3000/callback

Step 3: Write the API Server Code

Create a server.js file with the following code:

require('dotenv').config();
const express = require('express');
const { auth, requiresAuth } = require('express-openid-connect');

const app = express();

// Configure OIDC middleware
app.use(auth({
  authRequired: false, // Don't force auth on all routes
  auth0Logout: true,
  issuerBaseURL: process.env.ISSUER_BASE_URL,
  baseURL: process.env.BASE_URL,
  clientID: process.env.CLIENT_ID,
  secret: process.env.CLIENT_SECRET,
  idpLogout: true
}));

// Public route (no auth needed)
app.get('/', (req, res) => {
  res.send('Hello! This is a public endpoint.');
});

// Protected API endpoint (requires valid OIDC token)
app.get('/api/data', requiresAuth(), (req, res) => {
  // Access user info from the request object
  res.json({
    message: 'This is protected data!',
    user: req.oidc.user
  });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

How It Works

  • The auth middleware handles redirecting users to your OIDC provider for login, validating ID tokens, and managing user sessions.
  • The requiresAuth() middleware ensures only authenticated users can access the /api/data endpoint.
  • When a user logs in successfully, their user info (like email, user ID) is available in req.oidc.user.

Testing the API

  1. Start the server:
node server.js
  1. Visit http://localhost:3000/api/data in your browser—you'll be redirected to your OIDC provider's login page.
  2. After logging in, you'll be redirected back to the /api/data endpoint, which returns the protected data and user info.

For Other Tech Stacks

If you're using a different framework, here are some popular OIDC libraries to check out:

  • Python/Flask: Use flask-oidc
  • Java/Spring: Use Spring Security with OAuth2/OIDC support
  • Django: Use mozilla-django-oidc

Just remember, the core idea is always the same: validate incoming ID tokens from your OIDC provider to ensure only authorized users can access protected API routes.

内容的提问来源于stack exchange,提问作者Navjyot Kaur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:30:11