Umgang mit AUTHN mit .NET OpenAPI -GeneratorC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Umgang mit AUTHN mit .NET OpenAPI -Generator

Post by Anonymous »

Ich habe ein Projekt, das das Tool von Microsoft.Dotnet-OpenAPI verwendet, um typisierte httpclients aus einer OpenAPI-Spezifikation zu generieren. Einige Endpunkte erfordern ein devToken und einige benötigen ein OAuth Zugriffs-Token.

Code: Select all

// AutoGenerated class we cannot change
public partial class ClientApi
{
public ClientApi(HttpClient httpClient)
{
// Some initializers
}

partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url);

public async Task Controller_GetEndpointThatRequiresAuth(string id)
{
// ...Some code that prepares the request
PrepareRequest(client, request, url); // Called before request
// ...Send request
return "data from request";
}
}
Das Problem, auf das ich begegnet bin, ist, dass ich der methode prepareRequest () entweder die devToken oder den oAuth token verwenden kann.

Code: Select all

public partial class ClientApi
{
private string _token;
private readonly ClientApiOptions _options;

public ClientApi(HttpClient httpClient, ClientApiOptions options)
{
_httpClient = httpClient;
_options = options;
_token = options.DevKey;
}

partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
}

public IClientApi UseToken(string token)
{
_token = token;
return this;
}
}
, in dem das Builder-Muster und eine USEToken () -Methode verwendet werden, die vor einer Anforderung an Controller_getendPointThatRiresAuth () ._client.UseToken(token).Controller_GetEndpointThatRequiresAuth(id)
< /code>
Obwohl dieser Ansatz funktioniert, habe ich das Gefühl, dass es einen besseren Ansatz gibt, den ich fehlt, und ich kann es nicht herausfinden. Wie würden Sie für diese API mit einem Auth -Token umgehen?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post