mygenericapiserver
v1.0.6
Published
A generic API server with pluggable authentication
Downloads
24
Maintainers
Readme
MyGenericAPIServer
MyGenericAPIServer is a generic API server template built with Node.js and Express. It features a pluggable authentication system that allows you to choose between basic authentication, token-based authentication, and OAuth2 authentication. This repository serves as a starting point for creating new API servers with different authentication mechanisms.
Introduction
MyGenericAPIServer
is a Node.js library designed to provide a quick and easy way to set up an API server with pluggable authentication mechanisms. This library allows developers to choose between basic authentication, token-based authentication, and OAuth2 authentication with minimal configuration. By abstracting the complexity of setting up authentication, MyGenericAPIServer
enables developers to focus on building their application logic and endpoints.
Table of Contents
- MyGenericAPIServer
- Introduction
- Table of Contents
- Installation
- Configuration
- Usage
- Authentication Types
- Example: Creating a New Project with MyGenericAPIServer
Installation
Create a new project:
mkdir NewAPIServer cd NewAPIServer npm init -y npm install mygenericapiserver
Configuration
Create a
.env
file:Create a
.env
file in the root directory to store environment variables.touch .env
Add the following content to
.env
:AUTH_TYPE=basic # or token, oauth2 OAUTH2_AUTHORIZATION_URL=https://authorization-server.com/auth OAUTH2_TOKEN_URL=https://authorization-server.com/token OAUTH2_CLIENT_ID=your-client-id OAUTH2_CLIENT_SECRET=your-client-secret OAUTH2_CALLBACK_URL=http://localhost:3000/auth/oauth2/callback
Usage
Initialize the Server
To initialize the server, require the package and call initializeServer
. Then use addPublicEndpoint
and addPrivateEndpoint
to define your endpoints, and finally call startServer
to start the server.
Example server.js
:
const { initializeServer, startServer, addPublicEndpoint, addPrivateEndpoint, getExpressInstance } = require('mygenericapiserver');
// Initialize the server
initializeServer();
// Add public and private endpoints
addPublicEndpoint('public', (req, res) => {
res.json({ message: `This is the public endpoint: public` });
});
addPrivateEndpoint('private', (req, res) => {
res.json({ message: `This is the private endpoint: private` });
});
// Add a new public endpoint that returns the HTML file
addPublicEndpoint('mytest', (req, res) => {
res.sendFile(__dirname + '/public/test.html');
});
// Start the server
startServer();
Add Public Endpoint
To add a public endpoint, use the addPublicEndpoint function. This function takes an endpoint name and a handler function as parameters and defines a public route.
addPublicEndpoint('public', (req, res) => {
res.json({ message: `This is the public endpoint: public` });
});
Add Private Endpoint
To add a private endpoint, use the addPrivateEndpoint function. This function takes an endpoint name and a handler function as parameters and defines a private route protected by the chosen authentication mechanism.
addPrivateEndpoint('private', (req, res) => {
res.json({ message: `This is the private endpoint: private` });
});
Access Express Instance
If you need to access the Express instance for additional configuration, use the getExpressInstance function.
const app = getExpressInstance();
// Example: Adding a new middleware
app.use((req, res, next) => {
console.log('Request URL:', req.url);
next();
});
Authentication Types
Basic Authentication
Basic Authentication uses a username and password for authentication.
Set AUTH_TYPE=basic in your .env file. The default credentials are:
- Username: admin
- Password: secret
Token-based Authentication
Token-based Authentication uses a predefined list of valid tokens.
Set AUTH_TYPE=token in your .env file. The default valid tokens are:
- token123
- token456
OAuth2 Authentication
OAuth2 Authentication uses the OAuth2 protocol for authentication.
- Set AUTH_TYPE=oauth2 in your .env file.
- Configure the following OAuth2 environment variables in your .env file:
- OAUTH2_AUTHORIZATION_URL: URL to the authorization server
- OAUTH2_TOKEN_URL: URL to get the access token
- OAUTH2_CLIENT_ID: Your OAuth2 client ID
- OAUTH2_CLIENT_SECRET: Your OAuth2 client secret
- OAUTH2_CALLBACK_URL: Callback URL for OAuth2 authentication
- OAuth2 Flow:
- Navigate to /auth/oauth2 to initiate the OAuth2 authentication process.
- After successful authentication, you will be redirected to /auth/oauth2/callback.
Example: Creating a New Project with MyGenericAPIServer
This example demonstrates how to create a new project, install MyGenericAPIServer, and add both a public endpoint and a private endpoint, each returning an HTML file.
Step 1: Create a New Project
Create a new project directory and initialize it:
mkdir NewAPIServer
cd NewAPIServer
npm init -y
Step 2: Install MyGenericAPIServer
Install the mygenericapiserver package:
npm install mygenericapiserver
Step 3: Create the .env File
Create a .env file in the root directory to specify the authentication type:
.env
AUTH_TYPE=basic # or token, oauth2
Step 4: Create HTML Files
Create a directory named public and add HTML files for the endpoints:
Create the public directory:
mkdir public
Create public-endpoint.html:
echo "<!DOCTYPE html><html><body>Public Endpoint Content</body></html>" > public/public-endpoint.html
Create the private directory:
mkdir private
Create private-endpoint.html:
echo "<!DOCTYPE html><html><body>Private Endpoint Content</body></html>" > private/private-endpoint.html
Step 5: Create the Main Server File
Create the main server file server.js:
server.js
const { initializeServer, startServer, addPublicEndpoint, addPrivateEndpoint } = require('mygenericapiserver');
// Initialize the server
initializeServer();
// Add public and private endpoints
addPublicEndpoint('public-endpoint', (req, res) => {
res.sendFile(__dirname + '/public/public-endpoint.html');
});
addPrivateEndpoint('private-endpoint', (req, res) => {
res.sendFile(__dirname + '/private/private-endpoint.html');
});
// Start the server
startServer();
Step 6: Start the Server
Start the server:
node server.js
Step 7: Test the Endpoints
- Navigate to http://localhost:3000/public-endpoint to see the public HTML content.
- Navigate to http://localhost:3000/private-endpoint to see the private HTML content. Note that you will need to provide the correct credentials to access the private endpoint if basic authentication is used.
Example Directory Structure
NewAPIServer/
├── .env
├── node_modules/
├── package.json
├── public/
│ └── public-endpoint.html
├── private/
│ └── private-endpoint.html
└── server.js
Explanation
- Initialize Server: The initializeServer function sets up the Express application with session management and passport.
- Add Endpoints: The addPublicEndpoint and addPrivateEndpoint functions are used to define the public and private endpoints, respectively, serving the appropriate HTML files.
- Start Server: The startServer function starts the server on the specified port.