Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
Expand Down Expand Up @@ -1072,6 +1073,46 @@ public CodegenOperation fromOperation(String path,
return op;
}

/**
* Computes class-level auth switches from the security schemes actually referenced by the
* operations of the API class, rather than from every scheme declared in
* components.securitySchemes.
* <p>
* The generichost library declares a TokenProvider constructor dependency on an API class
* when the corresponding switch is set, so the switch must reflect the operations of that
* class only. The switches computed here are exposed with a "class" prefix to keep them
* independent from the document-wide switches added by the generator afterwards.
*/
@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<ModelMap> allModels) {
super.postProcessOperationsWithModels(objs, allModels);

if (objs != null && GENERICHOST.equals(getLibrary())) {
List<CodegenSecurity> classAuthMethods = objs.getOperations().getOperation().stream()
.filter(op -> op.hasAuthMethods && op.authMethods != null)
.flatMap(op -> op.authMethods.stream())
.collect(Collectors.toList());

if (ProcessUtils.hasApiKeyMethods(classAuthMethods)) {
objs.put("classHasApiKeyMethods", true);
}
if (ProcessUtils.hasHttpBearerMethods(classAuthMethods)) {
objs.put("classHasHttpBearerMethods", true);
}
if (ProcessUtils.hasHttpBasicMethods(classAuthMethods)) {
objs.put("classHasHttpBasicMethods", true);
}
if (ProcessUtils.hasHttpSignatureMethods(classAuthMethods)) {
objs.put("classHasHttpSignatureMethods", true);
}
if (ProcessUtils.hasOAuthMethods(classAuthMethods)) {
objs.put("classHasOAuthMethods", true);
}
}

return objs;
}

public void addSupportingFiles(final String clientPackageDir, final String packageFolder,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) {
final String library = getLibrary();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,32 +179,32 @@ namespace {{packageName}}.{{apiPackage}}
/// <summary>
/// The class containing the events
/// </summary>
public {{classname}}Events Events { get; }{{#hasApiKeyMethods}}
public {{classname}}Events Events { get; }{{#classHasApiKeyMethods}}

/// <summary>
/// A token provider of type <see cref="ApiKeyProvider"/>
/// </summary>
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }{{/classHasApiKeyMethods}}{{#classHasHttpBearerMethods}}

/// <summary>
/// A token provider of type <see cref="BearerToken"/>
/// </summary>
public TokenProvider<BearerToken> BearerTokenProvider { get; }{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}}
public TokenProvider<BearerToken> BearerTokenProvider { get; }{{/classHasHttpBearerMethods}}{{#classHasHttpBasicMethods}}

/// <summary>
/// A token provider of type <see cref="BasicTokenProvider"/>
/// </summary>
public TokenProvider<BasicToken> BasicTokenProvider { get; }{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}}
public TokenProvider<BasicToken> BasicTokenProvider { get; }{{/classHasHttpBasicMethods}}{{#classHasHttpSignatureMethods}}

/// <summary>
/// A token provider of type <see cref="HttpSignatureTokenProvider"/>
/// </summary>
public TokenProvider<HttpSignatureToken> HttpSignatureTokenProvider { get; }{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}
public TokenProvider<HttpSignatureToken> HttpSignatureTokenProvider { get; }{{/classHasHttpSignatureMethods}}{{#classHasOAuthMethods}}

/// <summary>
/// A token provider of type <see cref="OauthTokenProvider"/>
/// </summary>
public TokenProvider<OAuthToken> OauthTokenProvider { get; }{{/hasOAuthMethods}}
public TokenProvider<OAuthToken> OauthTokenProvider { get; }{{/classHasOAuthMethods}}

{{#net80OrLater}}
{{#lambda.unique}}
Expand All @@ -223,23 +223,23 @@ namespace {{packageName}}.{{apiPackage}}
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <returns></returns>
public {{classname}}(ILogger<{{classname}}> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#hasApiKeyMethods}},
TokenProvider<ApiKeyToken> apiKeyProvider{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}},
TokenProvider<BearerToken> bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}},
TokenProvider<BasicToken> basicTokenProvider{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}},
TokenProvider<HttpSignatureToken> httpSignatureTokenProvider{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}},
TokenProvider<OAuthToken> oauthTokenProvider{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}},
public {{classname}}(ILogger<{{classname}}> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#classHasApiKeyMethods}},
TokenProvider<ApiKeyToken> apiKeyProvider{{/classHasApiKeyMethods}}{{#classHasHttpBearerMethods}},
TokenProvider<BearerToken> bearerTokenProvider{{/classHasHttpBearerMethods}}{{#classHasHttpBasicMethods}},
TokenProvider<BasicToken> basicTokenProvider{{/classHasHttpBasicMethods}}{{#classHasHttpSignatureMethods}},
TokenProvider<HttpSignatureToken> httpSignatureTokenProvider{{/classHasHttpSignatureMethods}}{{#classHasOAuthMethods}},
TokenProvider<OAuthToken> oauthTokenProvider{{/classHasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}},
{{packageName}}.{{clientPackage}}.CookieContainer cookieContainer{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}})
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
Logger = logger;
HttpClient = httpClient;
Events = {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}};{{#hasApiKeyMethods}}
ApiKeyProvider = apiKeyProvider;{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}
BearerTokenProvider = bearerTokenProvider;{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}}
BasicTokenProvider = basicTokenProvider;{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}}
HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}
OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}}
Events = {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}};{{#classHasApiKeyMethods}}
ApiKeyProvider = apiKeyProvider;{{/classHasApiKeyMethods}}{{#classHasHttpBearerMethods}}
BearerTokenProvider = bearerTokenProvider;{{/classHasHttpBearerMethods}}{{#classHasHttpBasicMethods}}
BasicTokenProvider = basicTokenProvider;{{/classHasHttpBasicMethods}}{{#classHasHttpSignatureMethods}}
HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/classHasHttpSignatureMethods}}{{#classHasOAuthMethods}}
OauthTokenProvider = oauthTokenProvider;{{/classHasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}}
CookieContainer = cookieContainer;{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}}
}
{{#operation}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2026 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.openapitools.codegen.csharpnetcore;

import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.testng.annotations.Test;

import java.nio.file.Path;

import static org.openapitools.codegen.TestUtils.assertFileContains;
import static org.openapitools.codegen.TestUtils.assertFileNotContains;
import static org.openapitools.codegen.TestUtils.newTempFolder;

public class CSharpGenericHostSecuritySchemeTest {
@Test
public void testUnusedSecuritySchemeDoesNotRequireTokenProvider() throws Exception {
Path output = newTempFolder();
CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("csharp").setLibrary("generichost")
.setInputSpec("src/test/resources/3_0/csharp/unused-security-scheme.yaml")
.setOutputDir(output.toString());
new DefaultGenerator().opts(config.toClientOptInput()).generate();

assertFileNotContains(output.resolve("src/Org.OpenAPITools/Api/ThingsApi.cs"),
"public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }",
"TokenProvider<ApiKeyToken> apiKeyProvider");
}

@Test
public void testTokenProviderOnlyAddedToApisUsingTheScheme() throws Exception {
Path output = newTempFolder();
CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("csharp").setLibrary("generichost")
.setInputSpec("src/test/resources/3_0/csharp/mixed-security-scheme.yaml")
.setOutputDir(output.toString());
new DefaultGenerator().opts(config.toClientOptInput()).generate();

assertFileContains(output.resolve("src/Org.OpenAPITools/Api/SecuredApi.cs"),
"public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }",
"TokenProvider<ApiKeyToken> apiKeyProvider",
"await ApiKeyProvider.GetAsync(\"X-API-KEY\"");
assertFileNotContains(output.resolve("src/Org.OpenAPITools/Api/OpenApi.cs"),
"public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }",
"TokenProvider<ApiKeyToken> apiKeyProvider");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
openapi: 3.0.3
info:
title: Mixed Security Scheme Usage
version: "1"
paths:
/secured:
get:
tags:
- secured
operationId: GetSecured
security:
- api_key: []
responses:
"200":
description: ok
/open:
get:
tags:
- open
operationId: GetOpen
responses:
"200":
description: ok
components:
securitySchemes:
api_key:
type: apiKey
in: header
name: X-API-KEY
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
openapi: 3.0.3
info:
title: Unused Security Scheme
version: "1"
paths:
/things:
get:
tags:
- things
operationId: GetThings
responses:
"200":
description: ok
content:
application/json:
schema:
type: array
items:
type: string
components:
securitySchemes:
api_key:
type: apiKey
in: header
name: X-API-KEY
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,16 @@ public sealed partial class APIKEYSApi : IAPIKEYSApi
/// </summary>
public APIKEYSApiEvents Events { get; }

/// <summary>
/// A token provider of type <see cref="ApiKeyProvider"/>
/// </summary>
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }

/// <summary>
/// Initializes a new instance of the <see cref="APIKEYSApi"/> class.
/// </summary>
/// <returns></returns>
public APIKEYSApi(ILogger<APIKEYSApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKEYSApiEvents aPIKEYSApiEvents,
TokenProvider<ApiKeyToken> apiKeyProvider)
public APIKEYSApi(ILogger<APIKEYSApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKEYSApiEvents aPIKEYSApiEvents)
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
Logger = logger;
HttpClient = httpClient;
Events = aPIKEYSApiEvents;
ApiKeyProvider = apiKeyProvider;
}

partial void FormatGetApiKeysId(ref int id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,16 @@ public sealed partial class APIKeysApi : IAPIKeysApi
/// </summary>
public APIKeysApiEvents Events { get; }

/// <summary>
/// A token provider of type <see cref="ApiKeyProvider"/>
/// </summary>
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }

/// <summary>
/// Initializes a new instance of the <see cref="APIKeysApi"/> class.
/// </summary>
/// <returns></returns>
public APIKeysApi(ILogger<APIKeysApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKeysApiEvents aPIKeysApiEvents,
TokenProvider<ApiKeyToken> apiKeyProvider)
public APIKeysApi(ILogger<APIKeysApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKeysApiEvents aPIKeysApiEvents)
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
Logger = logger;
HttpClient = httpClient;
Events = aPIKeysApiEvents;
ApiKeyProvider = apiKeyProvider;
}

partial void FormatGetApiKeysId(ref int id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,16 @@ public sealed partial class ApiKeysApi : IApiKeysApi
/// </summary>
public ApiKeysApiEvents Events { get; }

/// <summary>
/// A token provider of type <see cref="ApiKeyProvider"/>
/// </summary>
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }

/// <summary>
/// Initializes a new instance of the <see cref="ApiKeysApi"/> class.
/// </summary>
/// <returns></returns>
public ApiKeysApi(ILogger<ApiKeysApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ApiKeysApiEvents apiKeysApiEvents,
TokenProvider<ApiKeyToken> apiKeyProvider)
public ApiKeysApi(ILogger<ApiKeysApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ApiKeysApiEvents apiKeysApiEvents)
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
Logger = logger;
HttpClient = httpClient;
Events = apiKeysApiEvents;
ApiKeyProvider = apiKeyProvider;
}

partial void FormatGetApiKeysId(ref int id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,51 +122,16 @@ public sealed partial class AnotherFakeApi : IAnotherFakeApi
/// </summary>
public AnotherFakeApiEvents Events { get; }

/// <summary>
/// A token provider of type <see cref="ApiKeyProvider"/>
/// </summary>
public TokenProvider<ApiKeyToken> ApiKeyProvider { get; }

/// <summary>
/// A token provider of type <see cref="BearerToken"/>
/// </summary>
public TokenProvider<BearerToken> BearerTokenProvider { get; }

/// <summary>
/// A token provider of type <see cref="BasicTokenProvider"/>
/// </summary>
public TokenProvider<BasicToken> BasicTokenProvider { get; }

/// <summary>
/// A token provider of type <see cref="HttpSignatureTokenProvider"/>
/// </summary>
public TokenProvider<HttpSignatureToken> HttpSignatureTokenProvider { get; }

/// <summary>
/// A token provider of type <see cref="OauthTokenProvider"/>
/// </summary>
public TokenProvider<OAuthToken> OauthTokenProvider { get; }

/// <summary>
/// Initializes a new instance of the <see cref="AnotherFakeApi"/> class.
/// </summary>
/// <returns></returns>
public AnotherFakeApi(ILogger<AnotherFakeApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AnotherFakeApiEvents anotherFakeApiEvents,
TokenProvider<ApiKeyToken> apiKeyProvider,
TokenProvider<BearerToken> bearerTokenProvider,
TokenProvider<BasicToken> basicTokenProvider,
TokenProvider<HttpSignatureToken> httpSignatureTokenProvider,
TokenProvider<OAuthToken> oauthTokenProvider)
public AnotherFakeApi(ILogger<AnotherFakeApi> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AnotherFakeApiEvents anotherFakeApiEvents)
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
Logger = logger;
HttpClient = httpClient;
Events = anotherFakeApiEvents;
ApiKeyProvider = apiKeyProvider;
BearerTokenProvider = bearerTokenProvider;
BasicTokenProvider = basicTokenProvider;
HttpSignatureTokenProvider = httpSignatureTokenProvider;
OauthTokenProvider = oauthTokenProvider;
}

partial void FormatCall123TestSpecialTags(ModelClient modelClient);
Expand Down
Loading
Loading