Merge pull request #826 from xhh/java-auth

[Java] Add authentication support (API key, HTTP basic)
This commit is contained in:
Tony Tam 2015-06-05 08:45:08 -07:00
commit b4f153c202
23 changed files with 657 additions and 37 deletions

View File

@ -106,15 +106,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
}
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.java"));
supportingFiles.add(new SupportingFile("JsonUtil.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator);
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
}

View File

@ -17,6 +17,7 @@ import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
@ -33,12 +34,19 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
public class ApiClient {
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean debugging = false;
private String basePath = "{{basePath}}";
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
public ApiClient() {
@ -51,6 +59,14 @@ public class ApiClient {
// Set default User-Agent.
setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/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.
authentications = Collections.unmodifiableMap(authentications);
}
public String getBasePath() {
@ -62,6 +78,75 @@ public class ApiClient {
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*/
@ -222,13 +307,15 @@ public class ApiClient {
* @param headerParams The header parameters
* @param formParams The form parameters
* @param contentType The request Content-Type
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
Client client = getClient();
StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) {
String value = queryParams.get(key);
if (value != null){
@ -329,6 +416,19 @@ public class ApiClient {
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
}
/**
* Encode the given form parameters as request body.
*/

View File

@ -9,7 +9,7 @@ public class Configuration {
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
}
/**
* Set the default API client, which would be used when creating API

View File

@ -102,7 +102,8 @@ public class {{classname}} {
}
try {
String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
}

View File

@ -0,0 +1,55 @@
package {{invokerPackage}}.auth;
import java.util.Map;
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location == "query") {
queryParams.put(paramName, value);
} else if (location == "header") {
headerParams.put(paramName, value);
}
}
}

View File

@ -0,0 +1,8 @@
package {{invokerPackage}}.auth;
import java.util.Map;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams);
}

View File

@ -0,0 +1,37 @@
package {{invokerPackage}}.auth;
import java.util.Map;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
try {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,10 @@
package {{invokerPackage}}.auth;
import java.util.Map;
public class OAuth implements Authentication {
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
// TODO: support oauth
}
}

View File

@ -17,6 +17,7 @@ import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
@ -33,12 +34,19 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import io.swagger.client.auth.Authentication;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
public class ApiClient {
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean debugging = false;
private String basePath = "http://petstore.swagger.io/v2";
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
public ApiClient() {
@ -51,6 +59,13 @@ public class ApiClient {
// Set default User-Agent.
setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
public String getBasePath() {
@ -62,6 +77,75 @@ public class ApiClient {
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*/
@ -222,13 +306,15 @@ public class ApiClient {
* @param headerParams The header parameters
* @param formParams The form parameters
* @param contentType The request Content-Type
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
Client client = getClient();
StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) {
String value = queryParams.get(key);
if (value != null){
@ -329,6 +415,19 @@ public class ApiClient {
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
}
/**
* Encode the given form parameters as request body.
*/

View File

@ -9,7 +9,7 @@ public class Configuration {
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
}
/**
* Set the default API client, which would be used when creating API

View File

@ -78,7 +78,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -128,7 +129,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -180,7 +182,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (List<Pet>) apiClient.deserialize(response, "array", Pet.class);
}
@ -232,7 +235,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (List<Pet>) apiClient.deserialize(response, "array", Pet.class);
}
@ -288,7 +292,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "api_key", "petstore_auth" };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (Pet) apiClient.deserialize(response, "", Pet.class);
}
@ -360,7 +365,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -419,7 +425,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -491,7 +498,8 @@ public class PetApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "petstore_auth" };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}

View File

@ -77,7 +77,8 @@ public class StoreApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { "api_key" };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (Map<String, Integer>) apiClient.deserialize(response, "map", Map.class);
}
@ -127,7 +128,8 @@ public class StoreApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
@ -183,7 +185,8 @@ public class StoreApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
@ -239,7 +242,8 @@ public class StoreApi {
}
try {
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}

View File

@ -78,7 +78,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -128,7 +129,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -178,7 +180,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -233,7 +236,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (String) apiClient.deserialize(response, "", String.class);
}
@ -282,7 +286,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -338,7 +343,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return (User) apiClient.deserialize(response, "", User.class);
}
@ -395,7 +401,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}
@ -451,7 +458,8 @@ public class UserApi {
}
try {
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return ;
}

View File

@ -0,0 +1,55 @@
package io.swagger.client.auth;
import java.util.Map;
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location == "query") {
queryParams.put(paramName, value);
} else if (location == "header") {
headerParams.put(paramName, value);
}
}
}

View File

@ -0,0 +1,8 @@
package io.swagger.client.auth;
import java.util.Map;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams);
}

View File

@ -0,0 +1,37 @@
package io.swagger.client.auth;
import java.util.Map;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
try {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,10 @@
package io.swagger.client.auth;
import java.util.Map;
public class OAuth implements Authentication {
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
// TODO: support oauth
}
}

View File

@ -0,0 +1,75 @@
package io.swagger.client;
import io.swagger.client.auth.*;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> auths = apiClient.getAuthentications();
Authentication auth = auths.get("api_key");
assertNotNull(auth);
assertTrue(auth instanceof ApiKeyAuth);
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
assertEquals("header", apiKeyAuth.getLocation());
assertEquals("api_key", apiKeyAuth.getParamName());
auth = auths.get("petstore_auth");
assertTrue(auth instanceof OAuth);
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
assertNull(auths.get("unknown"));
try {
auths.put("my_auth", new HttpBasicAuth());
fail("the authentications returned should not be modifiable");
} catch (UnsupportedOperationException e) {
}
}
@Test
public void testSetUsername() {
try {
apiClient.setUsername("my-username");
fail("there should be no HTTP basic authentications");
} catch (RuntimeException e) {
}
}
@Test
public void testSetPassword() {
try {
apiClient.setPassword("my-password");
fail("there should be no HTTP basic authentications");
} catch (RuntimeException e) {
}
}
@Test
public void testSetApiKeyAndPrefix() {
ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key");
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
apiClient.setApiKey("my-api-key");
apiClient.setApiKeyPrefix("Token");
assertEquals("my-api-key", auth.getApiKey());
assertEquals("Token", auth.getApiKeyPrefix());
// reset values
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
}
}

View File

@ -0,0 +1,40 @@
package io.swagger.client.auth;
import java.util.Map;
import java.util.HashMap;
import static org.junit.Assert.*;
import org.junit.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
assertEquals(1, queryParams.size());
assertEquals("my-api-key", queryParams.get("api_key"));
// no changes to header parameters
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
}

View File

@ -0,0 +1,48 @@
package io.swagger.client.auth;
import java.util.Map;
import java.util.HashMap;
import static org.junit.Assert.*;
import org.junit.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
assertEquals(expected, headerParams.get("Authorization"));
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));
}
}

View File

@ -5,6 +5,7 @@ import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import io.swagger.client.auth.*;
import java.util.*;
import java.io.*;
@ -18,6 +19,9 @@ public class PetApiTest {
@Before
public void setup() {
api = new PetApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
@Test

View File

@ -1,8 +1,10 @@
package io.swagger.petstore.test;
import io.swagger.client.ApiException;
import io.swagger.client.Configuration;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import io.swagger.client.auth.*;
import java.util.*;
import java.io.*;
@ -16,6 +18,9 @@ public class StoreApiTest {
@Before
public void setup() {
api = new StoreApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
@Test
@ -65,4 +70,4 @@ public class StoreApiTest {
return order;
}
}
}

View File

@ -1,8 +1,10 @@
package io.swagger.petstore.test;
import io.swagger.client.ApiException;
import io.swagger.client.Configuration;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import io.swagger.client.auth.*;
import java.util.*;
import java.io.*;
@ -16,6 +18,9 @@ public class UserApiTest {
@Before
public void setup() {
api = new UserApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
@Test
@ -81,4 +86,4 @@ public class UserApiTest {
return user;
}
}
}