API authentication and authorization are critical aspects of securing web services and APIs.

Node.js - Types of authentication and authorization and JSON Web Tokens (JWTs)
JWT Authentication & Authorization
First, you need to install the jsonwebtoken library in your Node.js project. You can do this with npm:
Example 1:
npm install jsonwebtoken
Import the jsonwebtoken library:
In your Node.js application, import the jsonwebtoken library as follows:
const jwt = require('jsonwebtoken');
Creating a JWT (Token Signing):
To create a JWT, you can use the jwt.sign method. You'll typically include the payload (data to be stored in the token), a secret key, and optional options such as the token's expiration time.
const payload = {
user_id: 123,
username: 'exampleUser',
};
const secretKey = 'your_secret_key';
const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
In this example, the payload is an object with data you want to store in the token. The secretKey is a secret string that you should keep secure. The expiresIn option specifies how long the token will be valid.
Example 2:
const jwt = require("jsonwebtoken");
const secret = "horse battery staple";
Creating a JWT (Token Signing):
To create a JWT, you can use the jwt.sign method. You'll typically include the payload (data to be stored in the token), a secret key, and optional options such as the token's expiration time.
const users = [
{ username: "Alice", password: "password", role: "admin" },
{ username: "Bob", password: "password", role: "user" },
];
app.post("/api/login", function (req, res) {
const { username, password } = req.body;
const user = users.find(function (u) {
return u.username === username && u.password === password;
});
if (user) {
const token = jwt.sign( user, secret, {expiresIn: "1h"});
res.json({ token });
} else {
res.sendStatus(401);
}
});
Request
POST /api/login
Content-type: appliction/json
{ username: "Bob", password: "password" }
Response
Token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkJvYiIsInBhc3
N3b3JkIjoicGFzc3dvcmQiLCJyb2xlIjoidXNlciIsImlhdCI6MTYwMDc2MzI1NiwiZ
XhwIjoxNjAwNzY2ODU2fQ.-OBn8nIEmJqdNc9XfoUVVcZc7PEVUWHVQOP85YIlygo
Example 3: With middleware
function auth(req, res, next) {
const authHeader = req.headers["authorization"];
if(!authHeader) return res.sendStatus(401);
//Authorization: Bearer [token]
const [ type, token ] = authHeader.split(" ");
if(type !== "Bearer") return res.sendStatus(401);
jwt.verify(token, secret, function(err, data) {
if(err) res.sendStatus(401);
else next();
});
}
app.get("/api/records", auth, function(req, res){
//…
});
Example 4: With multiple middleware
function onlyAdmin(req, res, next) {
const [ type, token ] = req.headers["authorization"].split(" ");
jwt.verify(token, secret, function(err, user) {
if(user.role === "admin") next();
else res.sendStatus(403);
});
}
function auth(req, res, next) {
const authHeader = req.headers["authorization"];
if(!authHeader) return res.sendStatus(401);
//Authorization: Bearer [token]
const [ type, token ] = authHeader.split(" ");
if(type !== "Bearer") return res.sendStatus(401);
jwt.verify(token, secret, function(err, data) {
if(err) res.sendStatus(401);
else next();
});
}
app.delete("/api/records/:id", auth, onlyAdmin, function(req, res) {
//…
});
Types of authentication and authorization
API authentication and authorization are critical aspects of securing web services and APIs. There are various methods and types of authentication and authorization that you can implement in your APIs, depending on your use case and security requirements. Here are some common API authentication and authorization types:
Authentication Types:
API Key: Clients include an API key in their requests, which is validated on the server to grant or deny access. API keys are simple but may lack security if not handled properly.
OAuth 2.0: OAuth 2.0 is a widely used protocol for authentication and authorization. It allows for secure delegation of access to resources, often used with social login providers and single sign-on (SSO).
Token-Based Authentication: This involves the use of tokens (e.g., JSON Web Tokens or OAuth tokens) that are issued to authenticated users. Tokens are included in requests for validation.
Basic Authentication: This method involves sending a username and password with each request. It's less secure than other methods and should be used with HTTPS.
Bearer Token: A bearer token is a type of access token used in OAuth 2.0. The client presents this token with each request to access protected resources.
API Authentication with Cookies: Similar to web-based authentication, cookies can be used for API authentication, especially for server-rendered web applications.
Authorization Types:
Role-Based Access Control (RBAC): Users or clients are assigned roles, and permissions are associated with these roles. Access to resources is determined by the user's role.
Attribute-Based Access Control (ABAC): ABAC evaluates access control decisions based on attributes of the user, the resource, and the environment. This allows for fine-grained access control.
Token-Based Authorization: Access tokens often contain information about what the client is allowed to do. This information is validated during each API request.
OAuth 2.0 Scopes: OAuth 2.0 defines scopes that can be used to limit access to specific resources or actions. Clients request specific scopes during the authentication process.
Custom Authorization Logic: You can implement custom authorization logic based on your application's specific needs, such as business rules or user-specific permissions.
External Authorization Servers: Sometimes, authorization decisions are offloaded to external authorization servers, which are responsible for determining whether a client has the necessary permissions.
Attribute-Based Authorization Policies: These policies define conditions based on attributes of the request, user, or resource. Policies are evaluated to make access control decisions.
Time-Based Authorization: Access to resources can be limited based on specific timeframes or expiration dates.
The choice of authentication and authorization methods depends on the security and access control requirements of your API. In many cases, a combination of these methods may be used to provide a robust security layer for your API, ensuring that only authorized users or clients can access specific resources and perform actions as permitted by your application's policies.
JSON Web Tokens (JWTs) are a widely used method for securely transmitting information between parties as a compact and self-contained token. In a Node.js application, you can use the jsonwebtoken library to create and verify JWTs. Below is a step-by-step guide on how to use JSON Web Tokens in a Node.js application.

#HIRE ME
Ko Aung Thu Oo
Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...
View detail