Skip to content

Instantly share code, notes, and snippets.

@xgp
Last active December 7, 2016 10:57
Show Gist options
  • Save xgp/a853e80351e832070511a8ec7d0fda78 to your computer and use it in GitHub Desktop.
Save xgp/a853e80351e832070511a8ec7d0fda78 to your computer and use it in GitHub Desktop.
Using swagger codegen Java with APIs that require 2- or 3-legged OAuth1
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
import se.akerfeldt.okhttp.signpost.SigningInterceptor;
....
// Using the default Java
DefaultApi api = new DefaultApi();
ApiClient client = api.getApiClient();
// Put the interceptor in the http client
OkHttpClient http = client.getHttpClient();
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer("yourConsumerKey", "yourConsumerSecret");
consumer.setTokenWithSecret("yourAccessToken", "yourAccessSecret"); //comment out for 2-legged
http.interceptors().add(new SigningInterceptor(consumer));
// Call your API
api.someMethod();
....
// Or if you're using Retrofit
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer("yourConsumerKey", "yourConsumerSecret");
consumer.setTokenWithSecret("yourAccessToken", "yourAccessSecret"); //comment out for 2-legged
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
// Build Retrofit with the custom client
Retrofit retrofit = new Retrofit.Builder()
...
.client(client)
.build();
// Create your API and call it
DefaultApi api = retrofit.create(DefaultApi.class);
Response<SomeObject> obj = api.someMethod().execute();
<!-- Add this to your pom.xml dependencies -->
<dependency>
<groupId>se.akerfeldt</groupId>
<artifactId>okhttp-signpost</artifactId>
<version>1.0.0</version> <!-- 1.0.0 for compatibility with OkHttp2/Retrofit, 1.1.0 for OkHttp3/Retrofit2 -->
</dependency>
This is a way to use Swagger (1.2 and 2.0) Java generated code with APIs that require 2- or 3-legged OAuth1.
This only works with the default Java and Retrofit codegen (not any of the jax or jersey or feign or etc.).
Make sure to leave securityDefinitions and security out of your swagger IDL, as it will conflict with the
interceptor you are putting in the OkHttpClient.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment