Skip to content
Snippets Groups Projects
Commit cf330aea authored by Alan Braz's avatar Alan Braz
Browse files

gettting test user token from KeyCloak

parent d991033a
No related branches found
No related tags found
1 merge request!6Trusted ibm
package org.opengroup.osdu.indexer.ibm.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class KeyCloakUser {
static {
disableSslVerification();
}
private static void disableSslVerification() {
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
// curl --request POST \
// --url https://keycloak-osdu-r2.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud/auth/realms/OSDU/protocol/openid-connect/token \
// --header 'content-type: application/x-www-form-urlencoded' \
// --data grant_type=password \
// --data client_id=osdu-login \
// --data username=osdu-user \
// --data password=password1
public static String getToken() throws IOException {
//String aad_endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenant_id);
URL url = new URL("https://keycloak-osdu-r2.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud/auth/realms/OSDU/protocol/openid-connect/token");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "password");
parameters.put("client_id", "osdu-login");
parameters.put("username", "osdu-user");
parameters.put("password", "password1");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(getParamsString(parameters));
out.flush();
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
Gson gson = new Gson();
JsonObject jobj = gson.fromJson(content.toString(), JsonObject.class);
String token = jobj.get("access_token").getAsString();
return token;
}
private static String getParamsString(Map<String, String> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0
? resultString.substring(0, resultString.length() - 1)
: resultString;
}
}
......@@ -14,6 +14,14 @@
package org.opengroup.osdu.indexer.ibm.util;
import javax.inject.Inject;
import org.apache.http.HttpStatus;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.opengroup.osdu.core.common.provider.interfaces.IJwtCache;
import org.opengroup.osdu.core.common.provider.interfaces.ITenantFactory;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
......@@ -21,15 +29,11 @@ import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
/*
@Inject
private ITenantFactory tenantInfoServiceProvider;
@Inject
private IHeadersInfo headersInfoAzure;
@Inject
@Qualifier("dpsHeaderFactorySearch")
private DpsHeaders dpsHeaders;
@Inject
......@@ -37,64 +41,22 @@ public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
@Inject
private JaxRsDpsLog log;
@Inject
private AADConfiguration configuration;
*/
@Override
public String getIdToken(String tenantName){
return tenantName + "-dont-have-one";
}
/*
public String getIdToken(String tenantName) {
this.log.info("Tenant name received for auth token is: " + tenantName);
/*this.log.info("Tenant name received for auth token is: " + tenantName);
TenantInfo tenant = this.tenantInfoServiceProvider.getTenantInfo(tenantName);
if (tenant == null) {
this.log.error("Invalid tenant name receiving from azure");
throw new AppException(HttpStatus.SC_BAD_REQUEST, "Invalid tenant Name", "Invalid tenant Name from azure");
}
}*/
String ACCESS_TOKEN = "";
try {
IdToken cachedToken = (IdToken) this.cacheService.get(tenant.getServiceAccount());
this.headersInfoAzure.getHeaders().put(DpsHeaders.USER_EMAIL, tenant.getServiceAccount());
this.dpsHeaders.put(DpsHeaders.USER_EMAIL, tenant.getServiceAccount());
if (!IdToken.refreshToken(cachedToken)) {
return cachedToken.getTokenValue();
}
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = null;
try {
context = new AuthenticationContext(configuration.getAuthority(), false, service);
ClientCredential credential = new ClientCredential(configuration.getClientId(), configuration.getSecretKey());
Future<AuthenticationResult> future = context.acquireToken(configuration.getOboApi(), credential, null);
this.dpsHeaders.put(DpsHeaders.USER_EMAIL, "osdu-user@osdu.opengroup.org");
ACCESS_TOKEN = future.get().getAccessToken();
if (future == null) {
log.error(String.format("Azure Authentication: %s", future.get().getAccessToken()));
throw new AppException(HttpStatus.SC_FORBIDDEN, "Access denied", "The user is not authorized to perform this action");
}
IdToken idToken = IdToken.builder().tokenValue(ACCESS_TOKEN).expirationTimeMillis(JWT.decode(ACCESS_TOKEN).getExpiresAt().getTime()).build();
this.cacheService.put(tenant.getServiceAccount(), idToken);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
service.shutdown();
}
} catch (JWTDecodeException e) {
throw new AppException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Persistence error", "Invalid token, error decoding", e);
ACCESS_TOKEN = KeyCloakUser.getToken();
} catch (AppException e) {
throw e;
} catch (Exception e) {
......@@ -103,5 +65,5 @@ public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
return ACCESS_TOKEN;
}
*/
}
server.servlet.contextPath=/api/indexer/v2/
LOG_PREFIX=indexer
spring.main.allow-bean-definition-overriding=true
logging.level.org.springframework.web=DEBUG
server.port=8060
JAVA_HEAP_OPTS=-Xms4096M -Xmx4096M
......@@ -12,7 +14,9 @@ AUTHORIZE_API=https://entitlements-osdu-r2.osduadev-a1c3eaf78a86806e299f5f3f2075
AUTHORIZE_API_KEY=tobeupdated
LEGALTAG_API=https://os-legal-ibm-osdu-r2.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud/api/legal/v1
DEPLOYMENT_ENVIRONMENT=LOCAL
INSECURE_HOSTNAMES=keycloak-osdu-r2.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud:85e9c617-e295-460e-a2ff-048b18a76b22.blijs0dd0dcr4f55oehg.databases.appdomain.cloud:elasticsearch-instance-osdu-es.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud
DEPLOYMENT_ENVIRONMENT=CLOUD
SCHEMA_CACHE_EXPIRATION=60
INDEX_CACHE_EXPIRATION=60
......@@ -57,8 +61,13 @@ indexer.queue.key=abcd
ELASTIC_DATASTORE_KIND=SearchSettings
ELASTIC_DATASTORE_ID=indexer-service
ELASTIC_HOST=elasticsearch-instance-osdu-es.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud
ELASTIC_USER_PASSWORD=elastic:5bljztd8jtpv76cxqqhvf46
#ELASTIC_HOST=elasticsearch-instance-osdu-es.osduadev-a1c3eaf78a86806e299f5f3f207556f0-0000.us-south.containers.appdomain.cloud
#ELASTIC_PORT=443
#ELASTIC_USER_PASSWORD=elastic:5bljztd8jtpv76cxqqhvf46
ELASTIC_HOST=85e9c617-e295-460e-a2ff-048b18a76b22.blijs0dd0dcr4f55oehg.databases.appdomain.cloud
ELASTIC_PORT=30842
ELASTIC_USER_PASSWORD=ibm_cloud_a3207231_f8ea_4ca5_9e7e_b63badc2e544:61e86fddfd5b9385510e961bec444d95799258d41b635422e59b073610d7f62d
#GAE_SERVICE=indexer
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment