Authentication and Access Control
1.1 Overview
1.2 Key Components of the Security Protocol
Used for secure delegation, OAuth2 enables users to authorize third-party applications to access their resources without sharing credentials.
1.3 OAuth2 Implementation Guide
OAuth2 is a widely used standard for delegated access, allowing users to grant applications access to resources without exposing passwords. Here’s an example of an OAuth2 flow with access token generation.
1.3.1 Request Authorization Code
GET /authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=read_profile&state=1234xyz HTTP/1.1
Host: authorization-server.com
Parameters:
response_type=code
: Specifies that the response should be an authorization code.client_id
: Client ID of the application.redirect_uri
: Redirect URI for post-authorization response.scope
: The level of access the application requests.state
: A unique string to prevent CSRF attacks.
1.3.2 Obtain Access Token Using Authorization Code
POST /token HTTP/1.1
Host: authorization-server.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=AUTH_CODE_HERE&redirect_uri=YOUR_REDIRECT_URI&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
1.4 JWT Integration Guide
Generating JWT Tokens
A JWT typically consists of:
Header: Specifies the type of token (JWT) and the algorithm used for signing.
Payload: Contains user claims, such as
user_id
,role
, and token expiry.Signature: Created by hashing the header and payload with a secret key, verifying data integrity.
1.4.1 Generating JWT in Node.js
const jwt = require('jsonwebtoken');
function generateToken(user) {
const payload = {
userId: user.id,
role: user.role,
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour expiration
};
const secretKey = "YOUR_SECRET_KEY";
const token = jwt.sign(payload, secretKey);
return token;
}
// Usage
const token = generateToken({ id: "12345", role: "user" });
console.log(token);
1.4.2 Verifying JWT Tokens
function verifyToken(token) {
try {
const decoded = jwt.verify(token, "YOUR_SECRET_KEY");
console.log("Token is valid:", decoded);
return decoded;
} catch (error) {
console.error("Invalid token:", error);
return null;
}
}
// Usage
const decodedPayload = verifyToken(token);
1.5 Applying OAuth2 and JWT Together
For additional security and session management, OAuth2 can issue JWT tokens as access tokens. When integrating both protocols:
OAuth2 server generates a JWT as an access token.
JWT is passed to client applications to be stored and used as a bearer token for authorized requests.
Expiration and Refresh: When JWT expires, the application can use the OAuth2 refresh token to obtain a new JWT without re-authentication.
1.6 API Endpoint Access with Bearer JWT
GET /user/profile HTTP/1.1
Host: api.capsurelabs.com
Authorization: Bearer ACCESS_TOKEN_HERE
Last updated