.NET ヘルプ

DotnetOpenAuth .NET Core(開発者向けの仕組み)

更新済み 7月 1, 2024
共有:

DotNetOpenAuth .NET Coreは、.NET Core向けに適応されたオリジナルのDotNetOpenAuthライブラリのバージョンであり、強力な公開APIを提供します。 このライブラリは、OAuth2およびOpenIDを使用して.NETアプリケーションに認証を追加するのに役立ちます。 IronPDFは、.NETでPDFファイルを作成、読み取り、および編集するためのライブラリです。 これは、.NETアプリケーションから直接レポートや請求書のようなドキュメントを生成するのに役立ちます。

DotNetOpenAuth .NET Core と IronPDF を使用して、共有コードを利用し、新しい機能を実装するために、ウェブやデスクトップアプリケーションなどのさまざまな種類のプロジェクトに活用できます。 それらは、ソフトウェアにおける認証およびPDFドキュメント管理を扱う開発者にとって不可欠です。

DotNetOpenAuth .NET Coreの開始方法

.NETプロジェクトでDotNetOpenAuth .NET Coreを設定する

Microsoft テクノロジーによってサポートされている .NET プロジェクトで DotNetOpenAuth .NET Core を使用するには、次の手順に従ってください:

  1. Visual Studioでプロジェクトを開きます。

  2. ソリューションエクスプローラーに移動します。

  3. プロジェクト名を右クリックします。

  4. 「NuGet パッケージの管理」を選択してください。

  5. NuGetパッケージマネージャーで、DotNetOpenAuth.NetCoreおよびその他のNuGetパッケージを検索してください。

  6. Install をクリックしてプロジェクトに追加します。

    これにより、DotNetOpenAuth .NET Coreライブラリがプロジェクトに追加され、認証機能の統合がサポートされます。

DotNetOpenAuth .NET Coreを使用した基本的なコード例

以下は、DotNetOpenAuth .NET Coreを使用してアプリケーションにOAuth2認証を設定する方法を示す簡単な例です:

using DotNetOpenAuth.OAuth2;

// Initialize the OAuth2 client
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
IAuthorizationState state = client.ProcessUserAuthorization();
if (state != null && state.IsAuthorized)
{
    // Authorized successfully, now you can access protected resources
}
using DotNetOpenAuth.OAuth2;

// Initialize the OAuth2 client
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
IAuthorizationState state = client.ProcessUserAuthorization();
if (state != null && state.IsAuthorized)
{
    // Authorized successfully, now you can access protected resources
}
Imports DotNetOpenAuth.OAuth2

' Initialize the OAuth2 client
Private client = New WebServerClient(New AuthorizationServerDescription With {
	.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
Private state As IAuthorizationState = client.ProcessUserAuthorization()
If state IsNot Nothing AndAlso state.IsAuthorized Then
	' Authorized successfully, now you can access protected resources
End If
VB   C#

このコードスニペットは、DotNetOpenAuth .NET Coreを使用してOAuth2クライアントを設定し、認証サーバーに接続してユーザー認証を処理します。

DotNetOpenAuth .NET Core の機能を実装する

OpenID Connectの統合

DotNetOpenAuth .NET Coreを使用してOpenID Connectを統合するには、次の基本的なアプローチに従うことができます:

using DotNetOpenAuth.OAuth2;

// Configure the OpenID Connect client
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
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);
Imports DotNetOpenAuth.OAuth2

' Configure the OpenID Connect client
Private openIdClient = New WebServerClient(New AuthorizationServerDescription With {
	.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
Private authUri As Uri = openIdClient.GetAuthorizationRequestUri("openid email profile")
Response.Redirect(authUri.AbsoluteUri)
VB   C#

このコードはOpenID Connectクライアントを設定し、ユーザーをOpenIDプロバイダーの認証ページにリダイレクトします。

アクセストークンの処理

以下は、DotNetOpenAuth .NET Core でアクセス トークンを処理する方法です:

// After user is authenticated, process the authorization response
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 user is authenticated, process the authorization response
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 user is authenticated, process the authorization response
Dim authState As IAuthorizationState = openIdClient.ProcessUserAuthorization()
If authState IsNot Nothing AndAlso authState.IsAuthorized Then
	' Access token is available, and you can use it to make authenticated requests
	Dim accessToken As String = authState.AccessToken
End If
VB   C#

このスニペットは、ユーザー認証応答を処理し、アクセストークンを取得して使用します。

トークンの更新

トークンが期限切れになった場合にリフレッシュするには、次のコードを使用してください:

// 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
    }
}
' Check if the access token is expired and refresh it
If authState.AccessTokenExpirationUtc <= DateTime.UtcNow Then
	If openIdClient.RefreshAuthorization(authState) Then
		' Token refreshed successfully
	End If
End If
VB   C#

このコードは現在のトークンが期限切れかどうかを確認し、リフレッシュを試みます。

トークンの取り消し

トークンを取り消す必要がある場合は、以下のように実装してください:

// 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
}
' Revoke the access token
Dim success As Boolean = openIdClient.RevokeAuthorization(authState)
If success Then
	' Token revoked successfully
End If
VB   C#

このスニペットは認証を取り消し、アクセス トークンを無効にします。

トークンリクエストのカスタマイズ

特定のニーズに合わせてトークンリクエストをカスタマイズするには、追加のパラメーターを追加します:

// Customize the token request
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
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
Dim additionalParams = New Dictionary(Of String, String) From {
	{"custom_parameter", "value"}
}
Dim customizedState As IAuthorizationState = openIdClient.ProcessUserAuthorization(additionalParams)
If customizedState IsNot Nothing AndAlso customizedState.IsAuthorized Then
	' Token request customized and processed successfully
End If
VB   C#

このコードはトークンリクエストにカスタムパラメータを追加します。これは、認可サーバーの特定の要件に対処するのに役立ちます。

DotNetOpenAuth .NET Core と IronPDF

IronPDFは、開発者が.NET環境でPDFファイルを作成、読み取り、操作できる包括的なライブラリです。 HTMLから、またはURLから直接PDFを生成するのに特に役立ちます。これは、レポート作成、請求書の生成、またはウェブページを静的な形式で保存するのに最適です。 DotNetOpenAuth .NET Coreと統合すると、これらの機能が安全であり、認証されたユーザーのみにアクセス可能であることが保証されます。

IronPDFとDotNetOpenAuth .NET Coreの統合使用例

IronPDFとDotNetOpenAuth .NET Coreを統合する実際的な使用例は、認証されたユーザーが個別化されたレポートを生成してダウンロードする必要があるWebアプリケーションです。 たとえば、ユーザーがアプリケーションにログインして、PDFとして自分の財務報告書にアクセスするシナリオを想像してください。 DotNetOpenAuthはユーザーが適切に認証および認可されて、彼らのドキュメントにアクセスできるようにし、一方でIronPDFがこれらのパーソナライズされたPDFの作成と配信を担当します。

使用例のコード例

これを実装する方法を示す完全なコード例を見てみましょう。 次に、.NET Coreでユーザーを認証し、その後IronPDFを使用してPDFレポートを生成するシンプルなWeb APIを作成します:

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");
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Authorization

<Route("api/[controller]")>
<ApiController>
Public Class ReportController
	Inherits ControllerBase

	<Authorize>
	<HttpGet("download-pdf")>
	Public Function DownloadPdfReport() As IActionResult
		' Authentication is handled by DotNetOpenAuth .NET Core
		Dim currentUser = HttpContext.User.Identity.Name

		' Generate PDF content using IronPDF
		Dim Renderer = New ChromePdfRenderer()
		Dim 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
		Dim 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")
	End Function
End Class
VB   C#

この例では、次の [認証]認証されたユーザーのみがPDF生成エンドポイントにアクセスできるようにするために、属性を使用してください。 IronPDFのChromePdfRendererクラスは、HTMLコンテンツからPDFを作成するために使用されます。この場合、HTMLコンテンツはユーザーの名前で動的に個別化されています。

DotNetOpenAuth .NET Core(開発者向けしくみ):図1

結論

DotNetOpenAuth .NET Core と IronPDF を統合することで、.NET アプリケーションのセキュリティおよび機能性を強化する強力なソリューションを提供します。 これらの技術を活用することにより、動的PDF生成を通じて機密データを効果的に保護し、パーソナライズされたユーザー体験を提供できます。

IronPDFは汎用性が高いだけでなく、開発者に優しいため、.NETアプリケーション内でPDFファイルを作成および管理するためのシンプルなアプローチを提供します。 プロジェクトにIronPDFを導入することを検討している場合、無料トライアルとライセンスオプションが提供されていることに満足されるでしょう。

< 以前
開発者向けSpecFlow C#の仕組み
次へ >
OpenTelemetry .NET(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >