Caution
Do not use this example in production 1:1. It is meant for educational purposes and needs to be adapted to your specific use case. It is a minimal example that does not include all necessary security measures.
The authorization code workflow is described in RFC 6749, section 4.1:
+----------+
| Resource |
| Owner |
| |
+----------+
^
|
(B)
+----|-----+ Client Identifier +---------------+
| -+----(A)-- & Redirection URI ---->| |
| User- | | Authorization |
| Agent -+----(B)-- User authenticates --->| Server |
| | | |
| -+----(C)-- Authorization Code ---<| |
+-|----|---+ +---------------+
| | ^ v
(A) (C) | |
| | | |
^ v | |
+---------+ | |
| |>---(D)-- Authorization Code ---------' |
| Client | & Redirection URI |
| | |
| |<---(E)----- Access Token -------------------'
+---------+ (w/ Optional Refresh Token)
- @node-oauth/express-oauth-server (uses @node-oauth/oauth2-server)
- express
- body-parser
- cors
- express
- ejs
- Install dependencies in both provider and client directories:
cd provider && npm install
cd ../client && npm install- Create a
.envfile in the authorization-code/provider directory:
CLIENT_ID=testclient
CLIENT_SECRET=testsecret
REDIRECT_URI=http://localhost:3000/callback
USER_ID=user1
OAUTH_USERNAME=demo
OAUTH_PASSWORD=demo
- Create a
.envfile in the authorization-code/client directory:
AUTH_SERVER=http://localhost:8080
CLIENT_ID=testclient
CLIENT_SECRET=testsecret
REDIRECT_URI=http://localhost:3000/callback
- Start the provider (authorization server + resource server):
cd provider && npm start- Start the client application:
cd client && npm start- Visit http://localhost:3000 to start the authorization code flow.
This example demonstrates a clear separation between the OAuth2 provider (authorization server + resource server) and the client application. Unlike other examples that might combine both roles in a single application, this example shows:
- Provider (port 8080): Acts as both authorization server and resource server
- Client (port 3000): A separate web application that consumes OAuth2 services
This separation makes it easier to understand what the @node-oauth/oauth2-server library supports and what it doesn't.
- User visits the client application at http://localhost:3000
- User clicks "Login" to start the authorization flow
- User is redirected to the provider's authorization page
- User enters credentials and grants authorization
- User is redirected back to the client with an authorization code
- Client exchanges the code for an access token
- Client can now access protected resources using the access token