Skip to content

replaced oltu with scribejava for Java - okhttp client #10965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
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 @@ -635,9 +635,11 @@ public void processOpts() {
// has OAuth defined
if (ProcessUtils.hasOAuthMethods(openAPI)) {
// for okhttp-gson (default), check to see if OAuth is defined and included OAuth-related files accordingly
if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java"));
if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()) || OKHTTP_GSON_NEXTGEN.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java"));
supportingFiles.add(new SupportingFile("auth/OAuthAuthorizationCodeGrant.mustache", authFolder, "OAuthAuthorizationCodeGrant.java"));
supportingFiles.add(new SupportingFile("auth/OAuthClientCredentialsGrant.mustache", authFolder, "OAuthClientCredentialsGrant.java"));
supportingFiles.add(new SupportingFile("auth/OAuthPasswordGrant.mustache", authFolder, "OAuthPasswordGrant.java"));
}

// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
{{/threetenbp}}
{{#hasOAuthMethods}}
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.common.message.types.GrantType;
{{/hasOAuthMethods}}

import javax.net.ssl.*;
import java.io.File;
Expand Down Expand Up @@ -63,15 +59,7 @@ import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
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;
import {{invokerPackage}}.auth.RetryingOAuth;
import {{invokerPackage}}.auth.OAuthFlow;
{{/hasOAuthMethods}}
import {{invokerPackage}}.auth.*;

/**
* <p>ApiClient class.</p>
Expand Down Expand Up @@ -173,36 +161,37 @@ public class ApiClient {
}

/**
* Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters
*
* @param basePath base path
* @param clientId client ID
* @param clientSecret client secret
* @param parameters a {@link java.util.Map} of parameters
* * Constructor for ApiClient configured with base path, client ID, secret, and additional parameters
*/
public ApiClient(String basePath, String clientId, String clientSecret, Map<String, String> parameters) {
this(basePath, clientId, clientSecret, null, null, parameters);
}

/*
* Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters
*/
public ApiClient(String basePath, String clientId, String clientSecret, String scope, String callbackUrl, Map<String, String> parameters) {
init();
if (basePath != null) {
this.basePath = basePath;
}

{{#hasOAuthMethods}}
String tokenUrl = "{{tokenUrl}}";
if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) {
URI uri = URI.create(getBasePath());
tokenUrl = uri.getScheme() + ":" +
(uri.getAuthority() != null ? "//" + uri.getAuthority() : "") +
tokenUrl;
if (!URI.create(tokenUrl).isAbsolute()) {
throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL");
}
initHttpClient();

switch(OAuthFlow.{{flow}}) {
case accessCode:
authentications.put("{{name}}", new OAuthAuthorizationCodeGrant(clientId, clientSecret, scope, getAuthorizationUrl(), getTokenUrl(), callbackUrl, getRefreshUrl(), parameters, this.httpClient));
break;
case password:
authentications.put("{{name}}", new OAuthPasswordGrant(clientId, clientSecret, scope, getTokenUrl(), getRefreshUrl(), this.httpClient));
break;
case application:
authentications.put("{{name}}", new OAuthClientCredentialsGrant(clientId, clientSecret, scope, getTokenUrl(), this.httpClient));
break;
default:
throw new IllegalArgumentException("OAuth flow not implemented");
}
RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.{{flow}}, clientSecret, parameters);
authentications.put(
"{{name}}",
retryingOAuth
);
initHttpClient(Collections.<Interceptor>singletonList(retryingOAuth));
{{/hasOAuthMethods}}
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
Expand All @@ -213,6 +202,47 @@ public class ApiClient {
authentications = Collections.unmodifiableMap(authentications);
}

{{#hasOAuthMethods}}
private String getTokenUrl() {
try {
return getAbsoluteUrl("{{tokenUrl}}");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL");
}
}

private String getAuthorizationUrl() {
try {
return getAbsoluteUrl("{{authorizationUrl}}");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("OAuth2 authorization URL must be an absolute URL");
}
}

private String getRefreshUrl() {
try {
return getAbsoluteUrl("{{refreshUrl}}");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("OAuth2 authorization URL must be an absolute URL");
}
}

private String getAbsoluteUrl(String url) throws IllegalArgumentException {
if (!"".equals(url) && !URI.create(url).isAbsolute()) {
URI uri = URI.create(getBasePath());
String absoluteUrl = uri.getScheme() + ":" +
(uri.getAuthority() != null ? "//" + uri.getAuthority() : "") +
url;
if (!URI.create(absoluteUrl).isAbsolute()) {
throw new IllegalArgumentException("Unable to obtain an absolute URL");
}
return absoluteUrl;
} else {
return url;
}
}
{{/hasOAuthMethods}}

{{/-first}}
{{/oauthMethods}}
{{/hasOAuthMethods}}
Expand Down Expand Up @@ -724,23 +754,6 @@ public class ApiClient {
return this;
}

{{#hasOAuthMethods}}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
*
* @return Token request builder
*/
public TokenRequestBuilder getTokenEndPoint() {
for (Authentication apiAuth : authentications.values()) {
if (apiAuth instanceof RetryingOAuth) {
RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth;
return retryingOAuth.getTokenRequestBuilder();
}
}
return null;
}
{{/hasOAuthMethods}}

/**
* Format the given parameter object into string.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{{#hasOAuthMethods}}
package {{invokerPackage}}.auth;

import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor;
import com.github.scribejava.core.extractors.TokenExtractor;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth2.bearersignature.BearerSignature;
import com.github.scribejava.core.oauth2.bearersignature.BearerSignatureURIQueryParameter;
import com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication;
import com.github.scribejava.core.oauth2.clientauthentication.RequestBodyAuthenticationScheme;

{{>generatedAnnotation}}
public class DefaultApi20Impl extends DefaultApi20 {
private final String accessTokenEndpoint;
private final String authorizationBaseUrl;
private final String refreshTokenEndpoint;
protected DefaultApi20Impl(String accessTokenEndpoint) {
this(accessTokenEndpoint, null, null);
}

protected DefaultApi20Impl(String accessTokenEndpoint, String refreshTokenEndpoint) {
this(accessTokenEndpoint, null, refreshTokenEndpoint);
}

protected DefaultApi20Impl(String accessTokenEndpoint, String authorizationBaseUrl, String refreshTokenEndpoint) {
this.accessTokenEndpoint = accessTokenEndpoint;
this.authorizationBaseUrl = authorizationBaseUrl;
this.refreshTokenEndpoint = refreshTokenEndpoint;
}

@Override
public String getRefreshTokenEndpoint() {
if (this.refreshTokenEndpoint == null || this.refreshTokenEndpoint.trim().isEmpty()) {
return this.getAccessTokenEndpoint();
}
return this.refreshTokenEndpoint;
}

@Override
public String getAccessTokenEndpoint() {
return accessTokenEndpoint;
}

@Override
protected String getAuthorizationBaseUrl() {
return this.authorizationBaseUrl;
}

@Override
public BearerSignature getBearerSignature() {
return BearerSignatureURIQueryParameter.instance();
}

@Override
public ClientAuthentication getClientAuthentication() {
return RequestBodyAuthenticationScheme.instance();
}

@Override
public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() {
return OAuth2AccessTokenJsonExtractor.instance();
}
}
{{/hasOAuthMethods}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
{{#hasOAuthMethods}}
package {{invokerPackage}}.auth;

import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuth2Authorization;
import com.github.scribejava.core.oauth.AccessTokenRequestParams;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.github.scribejava.httpclient.okhttp.OkHttpHttpClient;
import okhttp3.OkHttpClient;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

{{>generatedAnnotation}}
public class OAuthAuthorizationCodeGrant extends OAuth {
private DefaultApi20Impl apiInstance;
private OAuth20Service service;
private Map<String, String> params;
public OAuthAuthorizationCodeGrant(String clientId, String clientSecret, String authorizationBaseUrl, String accessTokenEndpoint, String callbackUrl, Map<String, String> params) {
this(clientId, clientSecret, null, authorizationBaseUrl, accessTokenEndpoint, callbackUrl, null, params, null);
}

public OAuthAuthorizationCodeGrant(String clientId, String clientSecret, String scope, String authorizationBaseUrl, String accessTokenEndpoint, String callbackUrl, Map<String, String> params) {
this(clientId, clientSecret, scope, authorizationBaseUrl, accessTokenEndpoint, callbackUrl, null, params, null);
}

public OAuthAuthorizationCodeGrant(String clientId, String clientSecret, String scope, String authorizationBaseUrl, String accessTokenEndpoint, String callbackUrl, String refreshUrl, Map<String, String> params) {
this(clientId, clientSecret, scope, authorizationBaseUrl, accessTokenEndpoint, callbackUrl, refreshUrl, params, null);
}

public OAuthAuthorizationCodeGrant(String clientId, String clientSecret, String scope, String authorizationBaseUrl, String accessTokenEndpoint, String callbackUrl, String refreshUrl, Map<String, String> params, OkHttpClient httpClient) {
this.apiInstance = new DefaultApi20Impl(accessTokenEndpoint, authorizationBaseUrl, refreshUrl);
ServiceBuilder serviceBuilder = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.callback(callbackUrl);
if (scope != null && !scope.trim().isEmpty()) {
serviceBuilder.defaultScope(scope);
}

if (httpClient != null) {
serviceBuilder.httpClient(new OkHttpHttpClient(httpClient));
} else {
serviceBuilder.httpClient(new OkHttpHttpClient(new OkHttpClient()));
}


this.service = serviceBuilder.build(this.apiInstance);

this.params = params;
}

public String getAuthorizationUrl(String state) {
if (state != null && !state.trim().isEmpty()) {
return this.service.getAuthorizationUrl(state);
} else {
return this.service.getAuthorizationUrl();
}
}

public OAuth2Authorization extractAuthorization(String redirectLocation) {
return service.extractAuthorization(redirectLocation);
}

public OAuth2AccessToken obtainAccessToken(OAuth2Authorization authorization, String scope) throws IOException, ExecutionException, InterruptedException {
return this.obtainAccessToken(authorization.getCode(), scope);
}

public OAuth2AccessToken obtainAccessToken(String code, String scope) throws IOException, ExecutionException, InterruptedException {
AccessTokenRequestParams reqParams = new AccessTokenRequestParams(code);
reqParams.addExtraParameters(params);
if (scope != null && !scope.trim().isEmpty()) {
reqParams.scope(scope);
}

OAuth2AccessToken tokenResponse = service.getAccessToken(reqParams);

this.setAccessToken(tokenResponse.getAccessToken());
return tokenResponse;
}


public void setToken(OAuth2AccessToken token) {
this.setAccessToken(token.getAccessToken());
}

public void setToken(String accessToken) {
this.setAccessToken(accessToken);
}

public OAuth2AccessToken refreshToken(OAuth2AccessToken token, String scope) throws IOException, ExecutionException, InterruptedException {
return this.refreshToken(token.getRefreshToken(), scope);
}

public OAuth2AccessToken refreshToken(String refreshToken, String scope) throws IOException, ExecutionException, InterruptedException {
if (scope != null && !scope.trim().isEmpty()) {
return this.service.refreshAccessToken(refreshToken, scope);
} else {
return this.service.refreshAccessToken(refreshToken);
}
}

}
{{/hasOAuthMethods}}
Loading