Skip to content
GitLab
    • Explore Projects Groups Snippets
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • O openapi-generator
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 3,476
    • Issues 3,476
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 402
    • Merge requests 402
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • OpenAPI Tools
  • openapi-generator
  • Merge requests
  • !1930

[Java] Add support for Bearer Auth

  • Review changes

  • Download
  • Email patches
  • Plain diff
Merged Administrator requested to merge github/fork/davidwcarlson/master into master 6 years ago
  • Overview 0
  • Commits 10
  • Pipelines 0
  • Changes 32

Created by: davidwcarlson

Fix proposed for Issue OpenAPITools#457 Similar to Issue OpenAPITools#1446 for typescript, Issue OpenAPITools#1577 for python

Specs defined as follows currently generate HttpBasicAuth and send an Authorization: Basic [base64Encode(username + ":" + password)] header

    components:
      securitySchemes:
        bearer:
          type: http
          scheme: bearer

This change will generate code which uses a new HttpBearerAuth class, which will send an Authorization: [scheme] [accessToken] header.

This change is slightly larger and more impactful than reusing the OAuth when CodegenSecurity.bearerBearer is true, but it allows for scheme values other than bearer.

This fix was enabled by the recent commit of OpenAPITools@80ca67c

This PR is an alternative to PR OpenAPITools#1972

PR checklist

  • Read the contribution guidelines.
  • Ran the shell script under ./bin/ to update Petstore sample so that CIs can verify the change. (For instance, only need to run ./bin/{LANG}-petstore.sh and ./bin/security/{LANG}-petstore.sh if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in .\bin\windows\.
  • Filed the PR against the correct branch: master, 3.4.x, 4.0.x. Default: master.
  • Copied the technical committee to review the pull request if your PR is targeting a particular programming language.

Description of the PR

(details of the change, additional tests that have been done, reference to the issue for tracking, etc) Add a new Auth type for Bearer so that api specs using Bearer Authentication https://swagger.io/docs/specification/authentication/bearer-authentication/ use the correct auth (was BasicAuth).

Copying the Java technical committee as this is a change targeted to Java. @bbdouglas @JFCote @sreeshas @jfiala @lukoyanov @cbornet @jeff9finger

Compare
  • master (base)

and
  • latest version
    53566cb6
    10 commits, 2 years ago

32 files
+ 1198
- 5

    Preferences

    File browser
    Compare changes
modules/openap‎i-generator/src‎
ma‎in‎
java/org/openapitoo‎ls/codegen/languages‎
JavaClientC‎odegen.java‎ +1 -0
resourc‎es/Java‎
au‎th‎
HttpBearerA‎uth.mustache‎ +45 -0
libr‎aries‎
feign‎/auth‎
HttpBearerA‎uth.mustache‎ +43 -0
jer‎sey2‎
ApiClient‎.mustache‎ +18 -2
resttemp‎late/auth‎
HttpBearerA‎uth.mustache‎ +38 -0
retrof‎it/auth‎
HttpBearerA‎uth.mustache‎ +42 -0
retrofi‎t2/auth‎
HttpBearerA‎uth.mustache‎ +42 -0
vertx‎/auth‎
HttpBearerA‎uth.mustache‎ +39 -0
webclie‎nt/auth‎
HttpBearerA‎uth.mustache‎ +39 -0
ApiClient‎.mustache‎ +18 -2
test/java/org/opena‎pitools/codegen/java‎
JavaClientCod‎egenTest.java‎ +2 -1
samples/client‎/petstore/java‎
feign/src/main/…‎/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +43 -0
feign10x/src/main‎/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +43 -0
jersey1/src/…/…/…/‎openapitools/client‎
au‎th‎
HttpBeare‎rAuth.java‎ +56 -0
ApiClie‎nt.java‎ +15 -0
jersey2-java6/sr‎c/…/…/…/…/client‎
au‎th‎
HttpBeare‎rAuth.java‎ +56 -0
ApiClie‎nt.java‎ +15 -0
jersey2-java8/sr‎c/…/…/…/…/client‎
au‎th‎
HttpBeare‎rAuth.java‎ +56 -0
ApiClie‎nt.java‎ +15 -0
jersey2/src/…/…/…/‎openapitools/client‎
au‎th‎
HttpBeare‎rAuth.java‎ +56 -0
ApiClie‎nt.java‎ +15 -0
okhttp-gson/src/mai‎n/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +56 -0
resteasy/src/main‎/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +56 -0
resttemplate-withXm‎l/src/…/…/…/…/…/auth‎
HttpBeare‎rAuth.java‎ +38 -0
resttemplate/src/ma‎in/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +38 -0
retrofit/src/main‎/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +42 -0
retrofit2/src/main‎/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +42 -0
retrofit2rx/src/mai‎n/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +42 -0
retrofit2rx2/src/ma‎in/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +42 -0
vertx/src/main/…‎/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +50 -0
webclient/src/main‎/…/…/…/client/auth‎
HttpBeare‎rAuth.java‎ +39 -0
…/…/…/…‎/…/…/…/…‎
HttpBeare‎rAuth.java‎ +56 -0
modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java
+ 1
- 0
  • View file @ 53566cb6

  • Edit in single-file editor

  • Open in Web IDE


@@ -246,6 +246,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
// NOTE: below moved to postProcessOperationsWithModels
//supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
modules/openapi-generator/src/main/resources/Java/auth/HttpBearerAuth.mustache 0 → 100644
+ 45
- 0
  • View file @ 53566cb6

  • Edit in single-file editor

  • Open in Web IDE

{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
{{>generatedAnnotation}}
public class HttpBearerAuth implements Authentication {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token, which together with the scheme, will be sent as the value of the Authorization header.
*/
public String getBearerToken() {
return bearerToken;
}
/**
* Sets the token, which together with the scheme, will be sent as the value of the Authorization header.
*/
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if(bearerToken == null) {
return;
}
headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}
modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/HttpBearerAuth.mustache 0 → 100644
+ 43
- 0
  • View file @ 53566cb6

  • Edit in single-file editor

  • Open in Web IDE

package {{invokerPackage}}.auth;
import feign.RequestInterceptor;
import feign.RequestTemplate;
/**
* An interceptor that adds the request header needed to use HTTP bearer authentication.
*/
public class HttpBearerAuth implements RequestInterceptor {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token, which together with the scheme, will be sent as the value of the Authorization header.
*/
public String getBearerToken() {
return bearerToken;
}
/**
* Sets the token, which together with the scheme, will be sent as the value of the Authorization header.
*/
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void apply(RequestTemplate template) {
if(bearerToken == null) {
return;
}
template.header("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}
modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache
+ 18
- 2
  • View file @ 53566cb6

  • Edit in single-file editor

  • Open in Web IDE


@@ -53,6 +53,7 @@ import java.util.regex.Pattern;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.OAuth;
@@ -84,8 +85,9 @@ public class ApiClient {
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
@@ -193,6 +195,20 @@ public class ApiClient {
}
{{#hasOAuthMethods}}
/**
* Helper method to set bearer token for the first Bearer authentication.
* @param bearerToken Bearer token
*/
public void setBearerToken(String bearerToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBearerAuth) {
((HttpBearerAuth) auth).setBearerToken(bearerToken);
return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
* @param accessToken Access token
modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/auth/HttpBearerAuth.mustache 0 → 100644
+ 38
- 0
  • View file @ 53566cb6

  • Edit in single-file editor

  • Open in Web IDE

package {{invokerPackage}}.auth;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Base64Utils;
import org.springframework.util.MultiValueMap;
{{>generatedAnnotation}}
public class HttpBearerAuth implements Authentication {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
public String getBearerToken() {
return bearerToken;
}
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
if (bearerToken == null) {
return;
}
headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}
0 Assignees
None
Assign to
0 Reviewers
None
Request review from
Labels
2
Client: Java Enhancement: Security
2
Client: Java Enhancement: Security
    Assign labels
  • Manage project labels

Milestone
4.0.0
4.0.0 (expired)
None
Time tracking
No estimate or time spent
Lock merge request
Unlocked
1
1 participant
Administrator
Reference: OpenAPITools/openapi-generator!1930
Source branch: github/fork/davidwcarlson/master

Menu

Explore Projects Groups Snippets