Skip to content
Draft
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
1 change: 1 addition & 0 deletions .github/workflows/samples-spring.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ jobs:
- samples/server/petstore/springboot-useoptional
- samples/server/petstore/springboot-virtualan
- samples/openapi3/server/petstore/spring-boot-oneof-interface
- samples/client/petstore/spring-http-interface-oauth
steps:
- uses: actions/checkout@v5
- uses: actions/setup-java@v5
Expand Down
12 changes: 12 additions & 0 deletions bin/configs/spring-http-interface-oauth.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
generatorName: spring
library: spring-http-interface
outputDir: samples/client/petstore/spring-http-interface-oauth
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: spring-http-interface-oauth
snapshotVersion: "true"
hideGenerationTimestamp: "true"
modelNameSuffix: 'Dto'
generatedConstructorWithRequiredArgs: "false"
clientRegistrationId: "petstore-oauth"
1 change: 1 addition & 0 deletions docs/generators/java-camel.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|camelSecurityDefinitions|generate camel security definitions| |true|
|camelUseDefaultValidationErrorProcessor|generate default validation error processor| |true|
|camelValidationErrorProcessor|validation error processor bean name| |validationErrorProcessor|
|clientRegistrationId|Client registration ID for OAuth2 in Spring HTTP Interface (@ClientRegistrationId annotation).| |null|
|configPackage|configuration package for generated code| |org.openapitools.configuration|
|containerDefaultToNull|Set containers (array, set, map) default to null| |false|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app only)</dd><dt>**legacy**</dt><dd>Legacy java.util.Date</dd><dt>**java8-localdatetime**</dt><dd>Java 8 using LocalDateTime (for legacy app only)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for jdk 1.8+)</dd></dl>|java8|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/spring.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false|
|booleanGetterPrefix|Set booleanGetterPrefix| |get|
|camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false|
|clientRegistrationId|Client registration ID for OAuth2 in Spring HTTP Interface (@ClientRegistrationId annotation).| |null|
|configPackage|configuration package for generated code| |org.openapitools.configuration|
|containerDefaultToNull|Set containers (array, set, map) default to null| |false|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app only)</dd><dt>**legacy**</dt><dd>Legacy java.util.Date</dd><dt>**java8-localdatetime**</dt><dd>Java 8 using LocalDateTime (for legacy app only)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for jdk 1.8+)</dd></dl>|java8|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public static final String GENERATE_SORT_VALIDATION = "generateSortValidation";
public static final String GENERATE_PAGEABLE_CONSTRAINT_VALIDATION = "generatePageableConstraintValidation";
public static final String SUBSTITUTE_GENERIC_PAGED_MODEL = "substituteGenericPagedModel";
public static final String CLIENT_REGISTRATION_ID = "clientRegistrationId";

@Getter
public enum RequestMappingMode {
Expand Down Expand Up @@ -196,6 +197,8 @@ public enum RequestMappingMode {
@Setter protected boolean generateSortValidation = false;
@Setter protected boolean generatePageableConstraintValidation = false;
@Setter protected boolean substituteGenericPagedModel = false;
@Getter @Setter
protected String clientRegistrationId = null;

// Map from operationId to allowed sort values for @ValidSort annotation generation
private Map<String, List<String>> sortValidationEnums = new HashMap<>();
Expand Down Expand Up @@ -344,6 +347,7 @@ public SpringCodegen() {
.defaultValue("false")
);
cliOptions.add(CliOption.newBoolean(USE_JSPECIFY, "Use Jspecify for null checks", useJspecify));
cliOptions.add(CliOption.newString(CLIENT_REGISTRATION_ID, "Client registration ID for OAuth2 in Spring HTTP Interface (@ClientRegistrationId annotation)."));
supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY,
"Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
Expand Down Expand Up @@ -566,6 +570,7 @@ public void processOpts() {
convertPropertyToBooleanAndWriteBack(OPTIONAL_ACCEPT_NULLABLE, this::setOptionalAcceptNullable);
convertPropertyToBooleanAndWriteBack(USE_SPRING_BUILT_IN_VALIDATION, this::setUseSpringBuiltInValidation);
convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_DEDUCTION_FOR_ONE_OF_INTERFACES, this::setUseDeductionForOneOfInterfaces);
convertPropertyToStringAndWriteBack(CLIENT_REGISTRATION_ID, this::setClientRegistrationId);

additionalProperties.put("springHttpStatus", new SpringHttpStatusLambda());

Expand Down Expand Up @@ -1012,6 +1017,11 @@ public void setIsVoid(boolean isVoid) {
// But use a sensible tag name if there is none
objs.put("tagName", "default".equals(firstTagName) ? firstOperation.baseName : firstTagName);
objs.put("tagDescription", escapeText(firstTag.getDescription()));

// Add clientRegistrationId for spring-http-interface with OAuth
if (SPRING_HTTP_INTERFACE.equals(library) && clientRegistrationId != null && !clientRegistrationId.isEmpty()) {
operations.put("clientRegistrationId", clientRegistrationId);
}
}

removeImport(objs, "java.util.List");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import org.springframework.http.ResponseEntity;
{{/useResponseEntity}}
import org.springframework.web.bind.annotation.*;
import org.springframework.web.service.annotation.*;
{{#clientRegistrationId}}
import org.springframework.security.oauth2.client.annotation.ClientRegistrationId;
{{/clientRegistrationId}}
import org.springframework.web.multipart.MultipartFile;
{{#useBeanValidation}}
import {{javaxPackage}}.validation.Valid;
Expand All @@ -38,6 +41,9 @@ import {{javaxPackage}}.annotation.Generated;
{{>generatedAnnotation}}

{{#operations}}
{{#clientRegistrationId}}
@ClientRegistrationId("{{clientRegistrationId}}")
{{/clientRegistrationId}}
public interface {{classname}} {
{{#operation}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.13</version>
<version>3.5.0</version>
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like updating this will break current supported use cases: https://github.com/OpenAPITools/openapi-generator/actions/runs/26022364837/job/76486919726?pr=23807

so i suggest we update this and address any broken code in a separate PR instead.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update: filed #23809 to update it and the templates (which broke) as well and all tests passed

<relativePath/> <!-- lookup parent from repository -->
</parent>
{{/parentOverridden}}
Expand Down Expand Up @@ -91,6 +91,13 @@
<version>0.2.10</version>
</dependency>
{{/openApiNullable}}
{{#clientRegistrationId}}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
<version>4.0.6</version>
</dependency>
{{/clientRegistrationId}}
{{#useJspecify}}
<dependency>
<groupId>org.jspecify</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6584,6 +6584,33 @@ public void shouldAddNullableImportForArrayTypeModels() throws IOException {
.hasImports("org.springframework.lang.Nullable");
}

@Test
public void testClientRegistrationIdAnnotation() throws IOException {
final SpringCodegen codegen = new SpringCodegen();
codegen.setLibrary("spring-http-interface");
codegen.setClientRegistrationId("my-oauth-client");

final Map<String, File> files = generateFiles(codegen, "src/test/resources/3_0/petstore.yaml");

// Check that the @ClientRegistrationId annotation is generated at class level
JavaFileAssert.assertThat(files.get("PetApi.java"))
.hasImports("org.springframework.security.oauth2.client.annotation.ClientRegistrationId")
.assertTypeAnnotations()
.containsWithNameAndAttributes("ClientRegistrationId", ImmutableMap.of("value", "\"my-oauth-client\""));
}

@Test
public void testClientRegistrationIdAnnotationNotPresentWhenNotConfigured() throws IOException {
final SpringCodegen codegen = new SpringCodegen();
codegen.setLibrary("spring-http-interface");
// clientRegistrationId not set

final Map<String, File> files = generateFiles(codegen, "src/test/resources/3_0/petstore.yaml");

// Check that the @ClientRegistrationId annotation is NOT generated
assertFileNotContains(files.get("PetApi.java").toPath(), "@ClientRegistrationId", "ClientRegistrationId");
}

@Test
public void shouldRefuseJackson3WithoutSpringboot4() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.13</version>
<version>3.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.13</version>
<version>3.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

# Preserve custom OAuth2 documentation
README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
pom.xml
src/main/java/org/openapitools/api/AnotherFakeApi.java
src/main/java/org/openapitools/api/FakeApi.java
src/main/java/org/openapitools/api/FakeClassnameTags123Api.java
src/main/java/org/openapitools/api/PetApi.java
src/main/java/org/openapitools/api/StoreApi.java
src/main/java/org/openapitools/api/UserApi.java
src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java
src/main/java/org/openapitools/model/AdditionalPropertiesAnyTypeDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesArrayDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesBooleanDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesClassDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesIntegerDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesNumberDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesObjectDto.java
src/main/java/org/openapitools/model/AdditionalPropertiesStringDto.java
src/main/java/org/openapitools/model/AnimalDto.java
src/main/java/org/openapitools/model/ApiResponseDto.java
src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnlyDto.java
src/main/java/org/openapitools/model/ArrayOfNumberOnlyDto.java
src/main/java/org/openapitools/model/ArrayTestDto.java
src/main/java/org/openapitools/model/BigCatDto.java
src/main/java/org/openapitools/model/CapitalizationDto.java
src/main/java/org/openapitools/model/CatDto.java
src/main/java/org/openapitools/model/CategoryDto.java
src/main/java/org/openapitools/model/ChildWithNullableDto.java
src/main/java/org/openapitools/model/ClassModelDto.java
src/main/java/org/openapitools/model/ClientDto.java
src/main/java/org/openapitools/model/ContainerDefaultValueDto.java
src/main/java/org/openapitools/model/DogDto.java
src/main/java/org/openapitools/model/EnumArraysDto.java
src/main/java/org/openapitools/model/EnumClassDto.java
src/main/java/org/openapitools/model/EnumTestDto.java
src/main/java/org/openapitools/model/FileDto.java
src/main/java/org/openapitools/model/FileSchemaTestClassDto.java
src/main/java/org/openapitools/model/FormatTestDto.java
src/main/java/org/openapitools/model/HasOnlyReadOnlyDto.java
src/main/java/org/openapitools/model/ListDto.java
src/main/java/org/openapitools/model/MapTestDto.java
src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClassDto.java
src/main/java/org/openapitools/model/Model200ResponseDto.java
src/main/java/org/openapitools/model/NameDto.java
src/main/java/org/openapitools/model/NullableMapPropertyDto.java
src/main/java/org/openapitools/model/NumberOnlyDto.java
src/main/java/org/openapitools/model/OrderDto.java
src/main/java/org/openapitools/model/OuterCompositeDto.java
src/main/java/org/openapitools/model/OuterEnumDto.java
src/main/java/org/openapitools/model/ParentWithNullableDto.java
src/main/java/org/openapitools/model/PetDto.java
src/main/java/org/openapitools/model/ReadOnlyFirstDto.java
src/main/java/org/openapitools/model/ResponseObjectWithDifferentFieldNamesDto.java
src/main/java/org/openapitools/model/ReturnDto.java
src/main/java/org/openapitools/model/SpecialModelNameDto.java
src/main/java/org/openapitools/model/TagDto.java
src/main/java/org/openapitools/model/TypeHolderDefaultDto.java
src/main/java/org/openapitools/model/TypeHolderExampleDto.java
src/main/java/org/openapitools/model/UserDto.java
src/main/java/org/openapitools/model/XmlItemDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
7.23.0-SNAPSHOT
108 changes: 108 additions & 0 deletions samples/client/petstore/spring-http-interface-oauth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Spring HTTP Interface with OAuth2 (@ClientRegistrationId)

This sample demonstrates the use of the `@ClientRegistrationId` annotation with Spring HTTP Interface clients.

## Overview

This code was generated by the [OpenAPI Generator](https://openapi-generator.tech) project.
When generating Spring HTTP Interface clients, you can specify a `clientRegistrationId` parameter to automatically add the `@ClientRegistrationId` annotation to all generated API interfaces.

## Configuration

Add the `clientRegistrationId` property to your generator configuration:

```yaml
generatorName: spring
library: spring-http-interface
additionalProperties:
clientRegistrationId: "petstore-oauth"
```

Or via command line:

```bash
openapi-generator-cli generate \
-g spring \
--library spring-http-interface \
--additional-properties clientRegistrationId=petstore-oauth \
-i petstore.yaml \
-o ./output
```

## Generated Code

The generated interface will include the `@ClientRegistrationId` annotation at the class level:

```java
@ClientRegistrationId("petstore-oauth")
public interface PetApi {

@HttpExchange(
method = "GET",
value = "/pet/{petId}",
accept = { "application/json" }
)
ResponseEntity<PetDto> getPetById(@PathVariable("petId") Long petId);
}
```

## Spring Security Integration

This annotation is part of Spring Security's OAuth2 integration for HTTP Service Clients. It automatically associates OAuth2 tokens with HTTP requests.

### Requirements

- Spring Boot 3.5+
- Spring Security 6.5+
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The documented minimum Spring Security version is incorrect for @ClientRegistrationId; this annotation is available starting in Spring Security 7.0.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At samples/client/petstore/spring-http-interface-oauth/README.md, line 56:

<comment>The documented minimum Spring Security version is incorrect for `@ClientRegistrationId`; this annotation is available starting in Spring Security 7.0.</comment>

<file context>
@@ -0,0 +1,108 @@
+### Requirements
+
+- Spring Boot 3.5+
+- Spring Security 6.5+
+
+### Application Properties
</file context>


### Application Properties

Configure your Spring application with the OAuth2 client registration:

```yaml
spring:
security:
oauth2:
client:
registration:
petstore-oauth:
client-id: your-client-id
client-secret: your-client-secret
authorization-grant-type: client_credentials
scope: read,write
provider:
petstore-oauth:
token-uri: https://auth.example.com/oauth/token
```

### Bean Configuration

Configure your HTTP Interface beans with OAuth2 support using `RestClient` and the `OAuth2ClientHttpRequestInterceptor`:

```java
@Configuration
public class HttpInterfaceConfig {

@Bean
public PetApi petApi(RestClient.Builder builder, OAuth2AuthorizedClientManager authorizedClientManager) {
OAuth2ClientHttpRequestInterceptor interceptor =
new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);

RestClient restClient = builder
.baseUrl("https://petstore.example.com/v2")
.requestInterceptor(interceptor)
.build();

HttpServiceProxyFactory factory = HttpServiceProxyFactory
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The configuration example is incomplete for @ClientRegistrationId: it adds the OAuth2 interceptor but does not configure HttpServiceProxyFactory with ClientRegistrationIdProcessor.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At samples/client/petstore/spring-http-interface-oauth/README.md, line 96:

<comment>The configuration example is incomplete for `@ClientRegistrationId`: it adds the OAuth2 interceptor but does not configure `HttpServiceProxyFactory` with `ClientRegistrationIdProcessor`.</comment>

<file context>
@@ -0,0 +1,108 @@
+            .requestInterceptor(interceptor)
+            .build();
+
+        HttpServiceProxyFactory factory = HttpServiceProxyFactory
+            .builderFor(RestClientAdapter.create(restClient))
+            .build();
</file context>

.builderFor(RestClientAdapter.create(restClient))
.build();

return factory.createClient(PetApi.class);
}
}
```

## References

- [Spring Security HTTP Service Client Integration](https://docs.spring.io/spring-security/reference/servlet/oauth2/client/http-service-client.html)
- [Spring Framework HTTP Interface](https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-http-interface)
Loading
Loading