swagger-codegen
swagger-codegen copied to clipboard
[JAVA] JWT Bearer token auth not implemented
Description
Defining a security scheme as type: bearer does not generate an appropriate OkHttpClient Interceptor. It has OAuth2, Basic & ApiKey but not any others.
Swagger-codegen version
3.0.34
Swagger declaration file content or url
...
"securitySchemes": {
"Bearer": {
"type": "http",
"description": "Bearer Authentication with JWT Token",
"scheme": "bearer",
"bearerFormat": "JWT"
}
},
"security": [
{
"Bearer": []
}
]
Command line used for generation
{
"modelPackage": "redacted",
"apiPackage": "redacted",
"artifactId": "redacted",
"artifactVersion": "1.0.0",
"library": "retrofit2",
"useRxJava2": "true",
"dateLibrary": "java8",
"java8": "true"
}
Steps to reproduce
Related issues/PRs
Suggest a fix/enhancement
Add a simple Interceptor that adds the Authorization: Bearer <token> header and make ApiClient#setAccessToken look for that interceptor.
BearerTokenAuth.java
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class BearerTokenAuth implements Interceptor {
private String token;
public String getAccessToken() {
return token;
}
public void setAccessToken(String token) {
this.token = token;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header("Authorization") == null) {
request = request.newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
}
return chain.proceed(request);
}
}
ApiClient.java
public ApiClient(String[] authNames) {
this();
for (String authName : authNames) {
Interceptor auth = null;
if ("Bearer".equals(authName)) {
auth = new BearerTokenAuth();
} else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);
}
}
...
/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
*
* @param accessToken Access token
* @return ApiClient
*/
public ApiClient setAccessToken(String accessToken) {
for (Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken);
return this;
} else if (apiAuthorization instanceof BearerTokenAuth) {
final BearerTokenAuth bearerTokenAuth = (BearerTokenAuth) apiAuthorization;
bearerTokenAuth.setAccessToken(accessToken);
return this;
}
}
return this;
}
I experienced same on a Java Project with trying to add swagger-ui