跳過到頁腳內容
NODE 說明

oauth2orize NPM(開發者的使用方法)

動態內容創建和強大的安全性對於當今的 Web 應用至關重要。 OAuth 2.0 允許應用在不洩漏使用者憑證的情況下,代表使用者提供對資源的受限或有限存取權限,因此已成為安全授權的事實標準架構。 OAuth2orize 是一個適應性強的 Node.js 模組,它提供了一個強大的框架來管理基於安全存取權杖的身份驗證,從而簡化了 OAuth 2.0 授權伺服器的設定。

同時,包括報表製作和發票系統在內的多個領域的一個典型需求是能夠以程式設計方式產生和處理 PDF 文件。 IronPDF 是 Node.js 環境中的一個強大實用程序,它使簡單的 PDF 文件生成、編輯和渲染變得更加容易。

本教學結合 IronPDF 和 OAuth2orize 的最佳功能,建立一個動態且安全的 Node.js 應用程式。您將學習如何使用 OAuth2orize 設定 OAuth 2.0 伺服器來處理使用者驗證和授權。您還將學習如何使用 IronPDF 建立可透過需要驗證的 API 端點存取的 PDF 文件。

什麼是 OAuth2orize?

一個名為OAuth2orize的 Node.js 框架為開發人員提供了建立 OAuth 2.0 授權伺服器所需的資源。 它有助於處理和管理複雜的 OAuth 2.0 工作流程,包括刷新令牌的建立、驗證和管理。 由於該程式庫旨在與 Express 框架交互,因此已經熟悉 Express 的開發人員會發現它非常契合。

! oauth2orize NPM(開發者使用方法):圖 1 - OAuth2orize

OAuth2orize 的詳細特性與元件

資助類型支持

授予授權碼最適合伺服器端應用程序,客戶端可以安全地儲存授權碼,然後將其交換為存取權杖。

-隱式授權:適用於客戶端程序,例如單頁應用程序,其中客戶端會立即收到存取權杖。 -資源所有者密碼憑證授權:通常適用於第一方客戶,當資源所有者和客戶之間存在信任關係時,此功能非常有用。 -客戶端憑證授權:用於機器(伺服器和客戶端)之間的交互,其中客戶端需要使用 API 請求進行身份驗證以接收存取權杖。

中介軟體集成

  • Express 中間件:OAuth2orize 可以輕鬆與 Express 路由和中間件架構集成,在 Express 應用程式內部作為中間件運行。 -與 Passport.js 整合:OAuth2orize 與 Passport.js 無縫集成,Passport.js 是 Node.js 的一個功能豐富的身份驗證中間件,使開發人員除了 OAuth 2.0 之外,還可以使用各種身份驗證技術。

令牌管理

-存取令牌:授予資源存取權限的臨時令牌受到限制。 -刷新令牌:這些是有效期更長的令牌,允許使用者在無需重新驗證身份的情況下獲得新的存取令牌。

定制撥款和延期

由於 OAuth2orize 具有很強的適應性,開發人員可以建立客製化的授權類型和回應類型,以滿足特定應用程式的需求。

需要記住的安全要點

OAuth2orize 安全地管理令牌的頒發、驗證和撤銷,從而促進安全的 OAuth 2.0 應用程式。 建議開發者遵循 OAuth 2.0 最佳實踐,包括使用 HTTPS、驗證重定向 URI 以及將令牌儲存在安全位置。

建立和配置 OAuth2orize

請依照以下說明,使用 OAuth2orize 在 Node.js 中設定並建立 OAuth 2.0 授權伺服器。我們將定義授權類型,建立用於授權和令牌交換的 API,並建立授權伺服器。 在此配置中,將使用 Passport.js、OAuth2orize 和 Express 進行使用者身份驗證。

安裝依賴項

首先,初始化你的Node.js專案並安裝必要的依賴項。

npm install express 
npm install oauth2orize  
npm install passport 
npm install passport-local 
npm install passport-http  
npm install body-parser
npm install passport-http-bearer
npm install express-session uuid
npm install connect-ensure-login
npm install express 
npm install oauth2orize  
npm install passport 
npm install passport-local 
npm install passport-http  
npm install body-parser
npm install passport-http-bearer
npm install express-session uuid
npm install connect-ensure-login
SHELL

建立授權伺服器

要配置伺服器,請建立一個名為server.js文件,並將以下程式碼新增至該文件:

const express = require('express');
const oauth2orize = require('oauth2orize');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const BasicStrategy = require('passport-http').BasicStrategy;
const BearerStrategy = require('passport-http-bearer').Strategy;
const bodyParser = require('body-parser');
const session = require('express-session');
const { v4: uuidv4 } = require('uuid');

// In-memory data storage (use a database in production)
const users = [{ id: '1', username: 'user', password: 'pass' }];
const clients = [{ id: 'client', secret: 'secret', redirectUris: ['http://localhost:3000/cb'] }];
const tokens = [];

// Passport configuration for session management
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
    const user = users.find(user => user.id === id);
    done(null, user);
});

// Local strategy for username and password login
passport.use(new LocalStrategy((username, password, done) => {
    const user = users.find(user => user.username === username && user.password === password);
    if (user) return done(null, user);
    return done(null, false);
}));

// Basic strategy for client ID and secret authentication
passport.use(new BasicStrategy((clientId, clientSecret, done) => {
    const client = clients.find(client => client.id === clientId && client.secret === clientSecret);
    if (client) return done(null, client);
    return done(null, false);
}));

// Bearer strategy for access token authentication
passport.use(new BearerStrategy((token, done) => {
    const accessToken = tokens.find(t => t.accessToken === token);
    if (accessToken) {
        const user = users.find(user => user.id === accessToken.userId);
        if (user) return done(null, user);
    }
    return done(null, false);
}));

// Create OAuth 2.0 server
const server = oauth2orize.createServer();

// Grant authorization codes
server.grant(oauth2orize.grant.code((client, redirectUri, user, ares, done) => {
    const code = uuidv4();
    tokens.push({ code, clientId: client.id, redirectUri, userId: user.id });
    done(null, code);
}));

// Exchange authorization codes for access tokens
server.exchange(oauth2orize.exchange.code((client, code, redirectUri, done) => {
    const token = tokens.find(t => t.code === code && t.clientId === client.id && t.redirectUri === redirectUri);
    if (!token) return done(null, false);
    const accessToken = uuidv4();
    tokens.push({ accessToken, userId: token.userId, clientId: client.id });
    done(null, accessToken);
}));

// Express application setup
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Authorization endpoint
app.get('/authorize', (req, res) => {
    res.send('<form action="/authorize/decision" method="post"><button type="submit">Allow</button></form>');
});

// Decision endpoint for authorization
app.post('/authorize/decision', (req, res, next) => {
    server.decision()(req, res, next);
});

// Token endpoint for exchanging authorization codes for access tokens
app.post('/token', 
    passport.authenticate('basic', { session: false }),
    server.token(),
    server.errorHandler()
);

// Protected resource endpoint
app.get('/resource', passport.authenticate('bearer', { session: false }), (req, res) => {
    res.json({ message: 'Access granted to protected resource!' });
});

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`OAuth2orize server is running on http://localhost:${port}`);
});

您已成功使用 Node.js 中的 OAuth2orize 依照下列步驟建立和設定 OAuth 2.0 授權伺服器。 此配置顯示如何管理授權碼的授予,將其轉換為存取令牌,並使用持有者令牌來保護 API 端點。 考慮在生產環境中實施適當的錯誤處理、保護敏感數據,並將使用者、客戶端和令牌儲存在持久資料庫中。

! oauth2orize NPM(開發者使用方法):圖 2 - 授權輸出

開始

要開始在 Node.js 應用程式中整合 OAuth2orize 和 IronPDF,您必須先使用 OAuth2orize 建立 OAuth 2.0 授權伺服器,並使用 IronPDF 來實作 PDF 產生。 下面提供了一個詳細的教程,可以幫助您實現這一目標。

什麼是適用於Node.js的IronPDF

IronPDF for Node.js是一個 NPM 包,它讓建立和修改 PDF 檔案變得更加容易。 開發人員可以使用此工具新增頁首和浮水印、合併多個 PDF 頁面、從 HTML 文件中提取文字和圖像,以及執行其他幾項任務。 IronPDF 的使用者友善 API 和豐富的文件使開發人員能夠輕鬆地自動建立高品質的 PDF 文件。 IronPDF 具備增強文件工作流程和在各種情況下提供卓越使用者體驗所需的所有功能和特性,包括建立發票、報告和文件。

! oauth2orize NPM(開發者使用方法):圖 3 - IronPDF

IronPDF 的特點

-將 HTML 轉換為 PDF :一種快速簡便的方法來處理任何類型的 HTML 文本,包括 CSS 和 JavaScript。

  • PDF 文件合併:將多個 PDF 文件合併為一個 PDF 文件,以簡化文件管理任務。 -文字和圖像提取:從 PDF 文件中刪除文字和圖像,以便您可以利用它們進行進一步的分析或資料處理。 -浮水印:您可以為 PDF 頁面新增文字或影像浮水印,以達到品牌推廣或安全目的。 -新增頁首和頁尾:您可以為 PDF 文件的頁首和頁尾新增個人化訊息或頁碼。

安裝 IronPDF

若要啟用 IronPDF 功能,請使用 node 套件管理器安裝必要的 Node.js 套件。

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
SHELL

將 OAuth2orize Node.js 與 IronPDF 集成

將以下程式碼新增至 OAuth 2.0 授權伺服器程式碼中,以整合 IronPDF 產生 PDF。

const IronPdf = require("@ironsoftware/ironpdf");
const document = IronPdf.PdfDocument;

// Protected resource endpoint to generate PDF
app.get('/generate-pdf', passport.authenticate('bearer', { session: false }), async (req, res) => {
    // Example HTML content for PDF generation
    const htmlContent = `
    <html>
    <head>
        <title>PDF Report</title>
    </head>
    <body>
        <h1>Secure PDF Report</h1>
        <p>This PDF was generated by IronPDF.</p>
    </body>
    </html>
    `;
    try {
        // Convert HTML content to a PDF document
        const pdf = await document.fromHtml(htmlContent);
        const pdfBuffer = await pdf.saveAsBuffer();
        // Send the PDF as a response
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=report.pdf',
            'Content-Length': pdfBuffer.length
        });
        res.end(pdfBuffer);
    } catch (error) {
        res.status(500).send('Error generating PDF');
    }
});

提供的程式碼展示如何整合 IronPDF 以進行動態 PDF 生成,以及如何使用 Node.js 中的 OAuth2orize 建立 OAuth 2.0 授權伺服器。 設定中包含了 Express、Passport 和 UUID 等必要依賴項。為簡化操作,使用者和客戶端資訊保存在記憶體數組中; 但是,資料庫應該在生產環境中使用。

該程式碼透過定義多種 Passport 技術來處理用戶端驗證和使用者身份驗證。 授權碼授權(即使用者允許用戶端代表其存取資源)由 OAuth2orize 處理。用戶端取得存取權杖後,可以用授權碼將其兌換為存取權杖。 由於使用了 Bearer 令牌技術來保護/generate-pdf端點,因此只有經過驗證的請求才能建立 PDF。

端點使用 IronPDF 將 HTML 內容轉換為PDF 文檔,然後將其傳回給客戶端。 此整合提供了一個範例,說明如何使用 OAuth 2.0 來保護 API 端點並以可擴展和安全的方式交付動態內容。

! oauth2orize NPM(開發者使用方法):圖 4 - OAuth2orize 與 IronPDF 輸出

結論

總之,在Node.js應用程式中使用OAuth2orize和IronPDF可以安全可靠地產生高品質的PDF檔案。 由於 OAuth2orize 提供強大的 OAuth 2.0 授權,敏感資料受到保護,保證只有經過授權和身份驗證的使用者才能使用 PDF 建立服務。 另一方面,IronPDF 可以輕鬆有效地將 HTML 資訊轉換為專業品質的 PDF 檔案。

該集成為開發人員提供了一個可擴展且易於實施的解決方案,同時也提高了安全性、靈活性和使用者體驗。 借助這些技術,開發者可以開發出使用者友好、可靠、安全且符合當代安全和功能標準的應用程式。

透過將 IronPDF 和 Iron Software 技術添加到您的企業應用程式開發堆疊中,IronPDF 可以確保為客戶和最終用戶提供功能豐富的高階軟體解決方案。 此外,有了這個堅實的基礎,各項措施、後端系統和流程優化都將變得更加容易。 IronPDF提供$799版本。 這些技術擁有豐富的文件、活躍的線上開發者社群和定期升級,因此是現代軟體開發專案的絕佳選擇。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。