跳至頁尾內容
.NET 幫助

Dotnetopenauth .NET Core(開發者使用方法)

DotNetOpenAuth .NET Core 是原始 DotNetOpenAuth 庫的適配版本,為 .NET Core 提供強大的公共 API。 這個函式庫可協助您在 .NET 應用程式中加入 OAuth2 與 OpenID 的驗證功能。 IronPDF 是用於在 .NET 中建立、閱讀和編輯 PDF 檔案的函式庫。 它對於直接從您的 .NET 應用程式產生報告和發票等文件非常有用。

您可以在各種類型的專案(如 Web 和桌面應用程式)中使用 DotNetOpenAuth .NET Core 和 IronPDF for .NET,以充分利用共用程式碼並實現新功能。 對於希望在軟體中處理驗證和 PDF 文件管理的開發人員而言,這些工具是不可或缺的。

開始使用 DotNetOpenAuth .NET Core。

在 .NET 專案中設定 DotNetOpenAuth .NET Core。

若要在 Microsoft 技術支援的 .NET 專案中開始使用 DotNetOpenAuth .NET Core,請遵循下列步驟:

1.在 Visual Studio 中開啟您的專案。 2.前往解決方案總管。 3.在專案名稱上按一下滑鼠右鍵。 4.選擇 Manage NuGet Packages。 5.在 NuGet 套件管理員中,搜尋 DotNetOpenAuth.NetCore 及其他 NuGet 套件。 6.按一下 Install 將其新增至您的專案。

這將會在您的專案中加入 DotNetOpenAuth .NET Core 函式庫,提供整合驗證功能的支援。

使用 DotNetOpenAuth .NET Core 的基本程式碼範例

以下是一個簡單的範例,說明如何使用 DotNetOpenAuth .NET Core 在應用程式中設定 OAuth2 驗證:

using DotNetOpenAuth.OAuth2;

// Initialize the OAuth2 client with the authorization server details
var client = new WebServerClient(new AuthorizationServerDescription
{
    TokenEndpoint = new Uri("https://your-auth-server.com/token"),
    AuthorizationEndpoint = new Uri("https://your-auth-server.com/authorize")
}, "your-client-id", "your-client-secret");

// Start the authentication process and get the authorization state
IAuthorizationState state = client.ProcessUserAuthorization();
if (state != null && state.IsAuthorized)
{
    // Authorized successfully, now you can access protected resources
}
using DotNetOpenAuth.OAuth2;

// Initialize the OAuth2 client with the authorization server details
var client = new WebServerClient(new AuthorizationServerDescription
{
    TokenEndpoint = new Uri("https://your-auth-server.com/token"),
    AuthorizationEndpoint = new Uri("https://your-auth-server.com/authorize")
}, "your-client-id", "your-client-secret");

// Start the authentication process and get the authorization state
IAuthorizationState state = client.ProcessUserAuthorization();
if (state != null && state.IsAuthorized)
{
    // Authorized successfully, now you can access protected resources
}
$vbLabelText   $csharpLabel

此程式碼片段使用 DotNetOpenAuth .NET Core 設定 OAuth2 用戶端,連接到授權伺服器,並處理使用者授權。

實現 DotNetOpenAuth .NET Core 的功能

整合 OpenID Connect

要使用 DotNetOpenAuth .NET Core 整合 OpenID Connect,您可以遵循以下基本方法:

using DotNetOpenAuth.OAuth2;

// Configure the OpenID Connect client with authority details
var openIdClient = new WebServerClient(new AuthorizationServerDescription
{
    TokenEndpoint = new Uri("https://your-openid-provider.com/token"),
    AuthorizationEndpoint = new Uri("https://your-openid-provider.com/authorize")
}, "your-client-id");

// Redirect user for authentication
Uri authUri = openIdClient.GetAuthorizationRequestUri("openid email profile");
Response.Redirect(authUri.AbsoluteUri);
using DotNetOpenAuth.OAuth2;

// Configure the OpenID Connect client with authority details
var openIdClient = new WebServerClient(new AuthorizationServerDescription
{
    TokenEndpoint = new Uri("https://your-openid-provider.com/token"),
    AuthorizationEndpoint = new Uri("https://your-openid-provider.com/authorize")
}, "your-client-id");

// Redirect user for authentication
Uri authUri = openIdClient.GetAuthorizationRequestUri("openid email profile");
Response.Redirect(authUri.AbsoluteUri);
$vbLabelText   $csharpLabel

此程式碼會設定 OpenID Connect 客戶端,並將使用者重定向至 OpenID 提供者的驗證頁面。

處理存取代號

以下是如何使用 DotNetOpenAuth .NET Core 處理存取權標:

// After the user is authenticated, process the authorization response to retrieve the token
IAuthorizationState authState = openIdClient.ProcessUserAuthorization();
if (authState != null && authState.IsAuthorized)
{
    // Access token is available, and you can use it to make authenticated requests
    string accessToken = authState.AccessToken;
}
// After the user is authenticated, process the authorization response to retrieve the token
IAuthorizationState authState = openIdClient.ProcessUserAuthorization();
if (authState != null && authState.IsAuthorized)
{
    // Access token is available, and you can use it to make authenticated requests
    string accessToken = authState.AccessToken;
}
$vbLabelText   $csharpLabel

此片段會處理使用者授權回應,以擷取並使用存取標記。

刷新代幣

若要在代幣過期時刷新代幣,請使用下列程式碼:

// Check if the access token is expired and refresh it
if (authState.AccessTokenExpirationUtc <= DateTime.UtcNow)
{
    if (openIdClient.RefreshAuthorization(authState))
    {
        // Token refreshed successfully
    }
}
// Check if the access token is expired and refresh it
if (authState.AccessTokenExpirationUtc <= DateTime.UtcNow)
{
    if (openIdClient.RefreshAuthorization(authState))
    {
        // Token refreshed successfully
    }
}
$vbLabelText   $csharpLabel

此程式碼會檢查目前的標記是否已過期,並嘗試刷新它。

撤銷代幣

如果您需要撤銷代號,請如下所示執行:

// Revoke the access token
bool success = openIdClient.RevokeAuthorization(authState);
if (success)
{
    // Token revoked successfully
}
// Revoke the access token
bool success = openIdClient.RevokeAuthorization(authState);
if (success)
{
    // Token revoked successfully
}
$vbLabelText   $csharpLabel

此片段撤銷授權,有效地使存取標記失效。

自訂令牌請求

針對特定需求客製化令牌請求,例如新增額外參數:

// Customize the token request with additional parameters
var additionalParams = new Dictionary<string, string>
{
    {"custom_parameter", "value"}
};
IAuthorizationState customizedState = openIdClient.ProcessUserAuthorization(additionalParams);
if (customizedState != null && customizedState.IsAuthorized)
{
    // Token request customized and processed successfully
}
// Customize the token request with additional parameters
var additionalParams = new Dictionary<string, string>
{
    {"custom_parameter", "value"}
};
IAuthorizationState customizedState = openIdClient.ProcessUserAuthorization(additionalParams);
if (customizedState != null && customizedState.IsAuthorized)
{
    // Token request customized and processed successfully
}
$vbLabelText   $csharpLabel

此代碼會在令牌請求中加入自訂參數,有助於處理授權伺服器的特定需求。

DotNetOpenAuth .NET Core 與 IronPDF for .NET

IronPDF for .NET 是一個全面的函式庫,可讓開發人員在 .NET 環境中建立、讀取和處理 PDF 檔案。 它特別適用於從 HTML 或直接從 URL 產生 PDF,這對於報告、產生發票或只是以靜態格式儲存網頁都有很大的幫助。 當與 DotNetOpenAuth .NET Core 整合時,可確保這些功能是安全的,只有經過驗證的使用者才能存取。

將 IronPDF 與 DotNetOpenAuth .NET Core 合併的使用案例。

將 IronPDF 與 DotNetOpenAuth .NET Core 合併的一個實際用例是在一個 Web 應用程式中,經過驗證的使用者需要產生並下載個人化的報告。 例如,假設使用者登入您的應用程式,並以 PDF 格式存取財務報告。 DotNetOpenAuth 可確保使用者經過正確的驗證與授權,才能存取他們的文件,而 IronPDF 則負責這些個人化 PDF 的建立與傳送。

使用個案的程式碼範例

讓我們來看看一個完整的程式碼範例,看看如何實作。 我們將在 .NET Core 中建立一個簡單的 Web API,驗證使用者身份,然後用 IronPDF for .NET 產生 PDF 報告:

using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

[Route("api/[controller]")]
[ApiController]
public class ReportController : ControllerBase
{
    [Authorize]
    [HttpGet("download-pdf")]
    public IActionResult DownloadPdfReport()
    {
        // Authentication is handled by DotNetOpenAuth .NET Core
        var currentUser = HttpContext.User.Identity.Name;

        // Generate PDF content using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf($"<h1>Report for {currentUser}</h1><p>This is your personalized financial report.</p>");

        // Set file name and content type for the PDF
        var outputFileName = $"Report-{currentUser}.pdf";
        Response.Headers.Add("Content-Disposition", $"attachment; filename={outputFileName}");
        Response.ContentType = "application/pdf";

        // Return the generated PDF file
        return File(PDF.Stream.ToArray(), "application/pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

[Route("api/[controller]")]
[ApiController]
public class ReportController : ControllerBase
{
    [Authorize]
    [HttpGet("download-pdf")]
    public IActionResult DownloadPdfReport()
    {
        // Authentication is handled by DotNetOpenAuth .NET Core
        var currentUser = HttpContext.User.Identity.Name;

        // Generate PDF content using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf($"<h1>Report for {currentUser}</h1><p>This is your personalized financial report.</p>");

        // Set file name and content type for the PDF
        var outputFileName = $"Report-{currentUser}.pdf";
        Response.Headers.Add("Content-Disposition", $"attachment; filename={outputFileName}");
        Response.ContentType = "application/pdf";

        // Return the generated PDF file
        return File(PDF.Stream.ToArray(), "application/pdf");
    }
}
$vbLabelText   $csharpLabel

在這個範例中,我們使用 [Authorize] 屬性來確保只有經過認證的使用者才能存取 PDF 產生端點。 IronPDF 中的 ChromePdfRenderer 類用於從 HTML 內容建立 PDF,在本例中,會動態個人化使用者的姓名。

DotNetOpenAuth .NET Core (How It Works For Developers):圖 1

結論

將 DotNetOpenAuth .NET Core 與 IronPDF 整合,可為增強 .NET 應用程式的安全性和功能性提供強大的解決方案。 利用這些技術,您可以有效保護敏感資料,並透過動態 PDF 生成提供個人化的使用者體驗。

IronPDF for .NET 不僅功能多樣,而且對開發人員也很友善,提供在 .NET 應用程式中建立和管理 PDF 檔案的直接方法。 如果您正在考慮將 IronPDF 納入您的專案,建議探索 IronPDF 的官方網站,以取得免費試用和授權選項。

常見問題解答

DotNetOpenAuth .NET Core 是做什麼用的?

DotNetOpenAuth .NET Core 用於將 OAuth2 和 OpenID 驗證功能整合到 .NET 應用程式中,從而在 Web 和桌面環境中實現安全的身份驗證流程。

如何為我的 .NET 應用程式新增 OAuth2 身份驗證?

要新增 OAuth2 驗證,請使用 DotNetOpenAuth .NET Core 初始化 WebServerClient,並新增您的授權伺服器詳細信息,然後引導使用者完成驗證程序並處理其授權回應。

我可以在帶有身份驗證的 .NET 應用程式中建立 PDF 文件嗎?

是的,透過整合 DotNetOpenAuth .NET Core 進行身份驗證和 IronPDF 進行 PDF 生成,您可以建立安全、經過驗證的 PDF 文檔,例如個人化報告和發票。

如何在.NET應用程式中管理存取權杖?

DotNetOpenAuth .NET Core 透過處理授權回應來管理存取權杖,讓您可以擷取和使用存取權杖以進行安全、經過驗證的請求。

如何在.NET Core中刷新存取令牌?

若要在 .NET Core 中刷新存取令牌,請檢查令牌是否已過期,並使用 `RefreshAuthorization` 方法取得新令牌,以確保持續安全存取。

將 DotNetOpenAuth 與 PDF 生成整合有什麼好處?

將 DotNetOpenAuth 與 PDF 生成功能集成,可安全地存取敏感文檔,使經過驗證的使用者能夠產生和下載個人化 PDF,例如報告和發票。

如何在.NET應用程式中撤銷令牌?

透過在 DotNetOpenAuth .NET Core 中實作 `RevokeAuthorization` 方法來撤銷令牌,該方法會使存取令牌失效,從而防止進一步的未經授權的請求。

如何在.NET身份驗證中自訂令牌請求?

您可以為令牌處理代碼新增其他參數來自訂令牌請求,以滿足授權伺服器的特定要求。

在.NET專案中設定OpenID Connect需要哪些步驟?

要設定 OpenID Connect,請設定 OpenID Connect 用戶端,提供所需的授權詳細信息,並引導使用者透過 OpenID 提供者進行身份驗證,同時與 DotNetOpenAuth .NET Core 整合以實現無縫身份驗證。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。