新手开发简单REST API,如何用OpenID Connect/OAuth保护并求实现代码示例
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/callbackfor 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
authmiddleware 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/dataendpoint. - When a user logs in successfully, their user info (like email, user ID) is available in
req.oidc.user.
Testing the API
- Start the server:
node server.js
- Visit
http://localhost:3000/api/datain your browser—you'll be redirected to your OIDC provider's login page. - After logging in, you'll be redirected back to the
/api/dataendpoint, 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

