Package: ClientAuthenticator

ClientAuthenticator

nameinstructionbranchcomplexitylinemethod
ClientAuthenticator()
M: 3 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
getAccessToken(String, String, String, String, String, String, String, String, String, String, String)
M: 195 C: 0
0%
M: 12 C: 0
0%
M: 7 C: 0
0%
M: 36 C: 0
0%
M: 1 C: 0
0%
getResponseString(InputStream)
M: 30 C: 0
0%
M: 2 C: 0
0%
M: 2 C: 0
0%
M: 5 C: 0
0%
M: 1 C: 0
0%
makeDCRRequest(DCRParamRequest)
M: 212 C: 0
0%
M: 4 C: 0
0%
M: 3 C: 0
0%
M: 39 C: 0
0%
M: 1 C: 0
0%
static {...}
M: 19 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 7 C: 0
0%
M: 1 C: 0
0%

Coverage

1: package org.wso2.am.integration.test;
2:
3: import com.google.gson.JsonObject;
4: import com.google.gson.JsonParser;
5: import org.apache.commons.io.IOUtils;
6: import org.apache.commons.lang.StringUtils;
7: import org.apache.http.client.methods.CloseableHttpResponse;
8: import org.apache.http.client.methods.HttpPost;
9: import org.apache.http.entity.StringEntity;
10: import org.apache.http.impl.client.CloseableHttpClient;
11: import org.apache.http.impl.client.HttpClientBuilder;
12: import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
13: import org.wso2.am.integration.test.utils.bean.ApplicationKeyBean;
14: import org.wso2.am.integration.test.utils.bean.DCRParamRequest;
15: import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
16:
17: import java.io.BufferedReader;
18: import java.io.IOException;
19: import java.io.InputStream;
20: import java.io.InputStreamReader;
21: import java.net.URI;
22: import java.net.URL;
23: import java.nio.charset.StandardCharsets;
24: import java.security.SecureRandom;
25: import java.security.cert.CertificateException;
26: import java.security.cert.X509Certificate;
27: import java.util.HashMap;
28: import java.util.Map;
29: import javax.net.ssl.HostnameVerifier;
30: import javax.net.ssl.HttpsURLConnection;
31: import javax.net.ssl.SSLContext;
32: import javax.net.ssl.SSLSession;
33: import javax.net.ssl.TrustManager;
34: import javax.net.ssl.X509TrustManager;
35: import javax.xml.bind.DatatypeConverter;
36:
37: import static org.wso2.am.integration.test.Constants.CHAR_AT;
38:
39: public class ClientAuthenticator {
40:
41: public static final double JAVA_VERSION;
42: private static TrustManager trustAll;
43: private static String consumerKey = null;
44: private static String consumerSecret = null;
45: private static Map<String, ApplicationKeyBean> applicationKeyMap = new HashMap<>();
46: private static final String TLS_PROTOCOL = "TLS";
47: private static int count = 0;
48: static {
49: JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version"));
50:
51: trustAll = new X509TrustManager() {
52: @Override
53: public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
54: }
55:
56: @Override
57: public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
58: }
59:
60: @Override
61: public X509Certificate[] getAcceptedIssuers() {
62: return null;
63: }
64: };
65: }
66:
67: public static String getAccessToken(String scopeList, String appName, String callBackURL, String tokenScope, String appOwner,
68: String grantType, String dcrEndpoint, String username, String password, String tenantDomain, String tokenEndpoint) {
69: URL url;
70: HttpsURLConnection urlConn = null;
71: //calling token endpoint
72: try {
73: url = new URL(tokenEndpoint);
74: urlConn = (HttpsURLConnection) url.openConnection();
75: urlConn.setDoOutput(true);
76: urlConn.setRequestMethod("POST");
77: urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
78:
79: ApplicationKeyBean applicationKeyBean = applicationKeyMap.get(appName);
80: String clientEncoded = DatatypeConverter.printBase64Binary(
81: (applicationKeyBean.getConsumerKey()
82: + ':' + applicationKeyBean.getConsumerSecret()).getBytes(StandardCharsets.UTF_8));
83: urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded);
84:• if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain) || username.contains(CHAR_AT)) {
85: username = username + CHAR_AT + tenantDomain;
86: }
87: String postParams;
88:• if (APIMIntegrationConstants.GRANT_TYPE.PASSWORD.equals(grantType)) {
89: postParams = "grant_type=password&username=" + username + "&password=" + password;
90: } else {
91: postParams = "grant_type=client_credentials";
92: }
93:• if (!scopeList.isEmpty()) {
94: postParams += "&scope=" + scopeList+" device_"+count;
95: }
96: urlConn.setHostnameVerifier(new HostnameVerifier() {
97:
98: @Override
99: public boolean verify(String s, SSLSession sslSession) {
100: return true;
101: }
102: });
103: SSLContext sslContext = SSLContext.getInstance(TLS_PROTOCOL);
104: sslContext.init(null, new TrustManager[]{trustAll}, new SecureRandom());
105: urlConn.setSSLSocketFactory(sslContext.getSocketFactory());
106: urlConn.getOutputStream().write((postParams).getBytes("UTF-8"));
107: int responseCode = urlConn.getResponseCode();
108:• if (responseCode == 200) {
109: String responseStr = getResponseString(urlConn.getInputStream());
110: JsonParser parser = new JsonParser();
111: JsonObject obj = parser.parse(responseStr).getAsJsonObject();
112: count++;
113: return obj.get("access_token").getAsString();
114: } else {
115: throw new RuntimeException("Error occurred while getting token. Status code: " + responseCode);
116: }
117: } catch (Exception e) {
118: String msg = "Error while creating the new token for token regeneration.";
119: throw new RuntimeException(msg, e);
120: } finally {
121:• if (urlConn != null) {
122: urlConn.disconnect();
123: }
124: }
125: }
126:
127: public static ApplicationKeyBean makeDCRRequest(DCRParamRequest dcrParamRequest) {
128:
129: String applicationName = dcrParamRequest.getAppName();
130: try {
131: //Create json payload for DCR endpoint
132: JsonObject json = new JsonObject();
133: json.addProperty("callbackUrl", dcrParamRequest.getCallBackURL());
134: json.addProperty("clientName", applicationName);
135: json.addProperty("tokenScope", dcrParamRequest.getTokenScope());
136: json.addProperty("grantType", dcrParamRequest.getGrantType());
137: json.addProperty("saasApp", true);
138:
139: String clientEncoded;
140:
141:• if (StringUtils.isEmpty(dcrParamRequest.getTenantDomain())) {
142: json.addProperty("owner", dcrParamRequest.getAppOwner());
143: clientEncoded = DatatypeConverter.printBase64Binary(
144: (System.getProperty("systemUsername", dcrParamRequest.getUsername()) + ':' + System
145: .getProperty("systemUserPwd", dcrParamRequest.getPassword()))
146: .getBytes(StandardCharsets.UTF_8));
147: } else {
148: json.addProperty("owner", dcrParamRequest.getUsername() + CHAR_AT + dcrParamRequest.getTenantDomain());
149: clientEncoded = DatatypeConverter.printBase64Binary(
150: (dcrParamRequest.getUsername() + CHAR_AT + dcrParamRequest.getTenantDomain() + ':'
151: + dcrParamRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
152: }
153:
154: // Calling DCR endpoint
155: CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
156: HttpPost httpPost = new HttpPost();
157: httpPost.setURI(URI.create(dcrParamRequest.getDcrEndpoint()));
158:
159: httpPost.addHeader("Content-Type", "application/json");
160: httpPost.addHeader("Authorization", "Basic " + clientEncoded);
161: httpPost.setEntity(new StringEntity(json.toString()));
162: try (CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost)) {
163: int statusCode = httpResponse.getStatusLine().getStatusCode();
164:• if (statusCode == 200) { //If the DCR call is success
165: try (InputStream content = httpResponse.getEntity().getContent()) {
166: String responseStr = IOUtils.toString(content);
167: ApplicationKeyBean applicationKeyBean = new ApplicationKeyBean();
168: JsonParser parser = new JsonParser();
169: JsonObject jObj = parser.parse(responseStr).getAsJsonObject();
170: applicationKeyBean.setConsumerKey(jObj.getAsJsonPrimitive("clientId").getAsString());
171: applicationKeyBean.setConsumerSecret(jObj.getAsJsonPrimitive("clientSecret").getAsString());
172: applicationKeyMap.put(dcrParamRequest.getAppName(), applicationKeyBean);
173: return applicationKeyBean;
174: }
175: } else { //If DCR call fails
176: throw new RuntimeException("DCR call failed. Status code: " + statusCode);
177: }
178: }
179: } catch (IOException e) {
180: String errorMsg = "Can not create OAuth application : " + applicationName;
181: throw new RuntimeException(errorMsg, e);
182: }
183: }
184:
185:
186: private static String getResponseString(InputStream input) throws IOException {
187: try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
188: String file = "";
189: String str;
190:• while ((str = buffer.readLine()) != null) {
191: file += str;
192: }
193: return file;
194: }
195: }
196: }