Commit d9459e9e authored by Rucha Deshpande's avatar Rucha Deshpande
Browse files

Use client credetials flow to get access token

parent 6ea95b76
......@@ -50,7 +50,7 @@
<dependency>
<groupId>org.opengroup.osdu.core.aws</groupId>
<artifactId>os-core-lib-aws</artifactId>
<version>0.3.11</version>
<version>0.3.12-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-secretsmanager -->
......
......@@ -22,14 +22,20 @@ import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonSyntaxException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.opengroup.osdu.core.aws.entitlements.AccessToken;
import org.opengroup.osdu.core.aws.iam.IAMConfig;
import org.opengroup.osdu.core.common.http.HttpClient;
import org.opengroup.osdu.core.common.http.HttpRequest;
import org.opengroup.osdu.core.common.http.HttpResponse;
import org.opengroup.osdu.core.common.http.IHttpClient;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.opengroup.osdu.core.common.model.entitlements.EntitlementsException;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.opengroup.osdu.notification.provider.aws.utils.AwsCognitoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
......@@ -38,10 +44,7 @@ import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.*;
@Component
public class ServiceAccountJwtAwsClientImpl implements IServiceAccountJwtClient {
......@@ -66,14 +69,18 @@ public class ServiceAccountJwtAwsClientImpl implements IServiceAccountJwtClient
public String environment;
@Value("${aws.tokenUrl}")
@Getter()
public String tokenUrl;
@Autowired
private JaxRsDpsLog log;
String password;
String clientid;
String userpoolid;
String serviceprincipaluser;
AwsCognitoClient cognitoClient;
String client_credentials_secret;
String client_credentials_clientid;
private AWSCredentialsProvider amazonAWSCredentials;
private AWSSimpleSystemsManagement ssmManager;
......@@ -81,22 +88,21 @@ public class ServiceAccountJwtAwsClientImpl implements IServiceAccountJwtClient
@PostConstruct
public void init() {
if (ssmEnabled) {
String secretKey = "service_principal_password";
String secretName = "/osdu/" + environment + "/service_principal_password";
String cognito_user_pool_id = "/osdu/" + environment + "/cognito-user-pool-id";
String cognito_client_id = "/osdu/" + environment + "/cognito-client-id";
String service_principal = "/osdu/" + environment + "/service-principal-user";
String client_credentials_client_id = "/osdu/" + environment + "/client-credentials-client-id";
String client_secret_key = "client_credentials_client_secret";
String client_secret_secretName = "/osdu/" + environment + "/client_credentials_secret";
amazonAWSCredentials = IAMConfig.amazonAWSCredentials();
ssmManager = AWSSimpleSystemsManagementClientBuilder.standard()
.withCredentials(amazonAWSCredentials)
.withRegion(amazonRegion)
.build();
GetParametersRequest paramRequest = new GetParametersRequest()
.withNames(cognito_user_pool_id,cognito_client_id,service_principal)
GetParameterRequest paramRequest = new GetParameterRequest()
.withName(client_credentials_client_id)
.withWithDecryption(true);
GetParametersResult paramResult = new GetParametersResult();
paramResult = ssmManager.getParameters(paramRequest);
GetParameterResult paramResult = new GetParameterResult();
paramResult = ssmManager.getParameter(paramRequest);
List<Parameter> paramsResultList = new ArrayList<>();
List<String> paramsResultListInvalid = new ArrayList<>();
paramsResultList = paramResult.getParameters();
......@@ -104,24 +110,16 @@ public class ServiceAccountJwtAwsClientImpl implements IServiceAccountJwtClient
if(paramsResultListInvalid.size() >0)
{
log.error("SSM did not retrieve all parameters");
log.error("Notification Service: SSM did not retrieve all parameters");
}
for (Parameter s : paramsResultList) {
if (s.getName().equalsIgnoreCase(cognito_user_pool_id)) {
userpoolid = s.getValue();
if (s.getName().equalsIgnoreCase(client_credentials_client_id)) {
client_credentials_clientid = s.getValue();
}
if (s.getName().equalsIgnoreCase(cognito_client_id)) {
clientid = s.getValue();
}
if (s.getName().equalsIgnoreCase(service_principal)) {
serviceprincipaluser = s.getValue();
}
}
client_credentials_secret = getSecret(client_secret_secretName,amazonRegion,client_secret_key);
password = getSecret(secretName,amazonRegion,secretKey);
cognitoClient = new AwsCognitoClient(amazonRegion,clientid,"USER_PASSWORD_AUTH", serviceprincipaluser,password);
cognitoClient.setPassword(serviceprincipaluser,password,userpoolid);
}
}
......@@ -136,9 +134,26 @@ public class ServiceAccountJwtAwsClientImpl implements IServiceAccountJwtClient
public String getServicePrincipalCredentials()
{
String token = cognitoClient.getToken(serviceprincipaluser,password,"bearer");
return token;
String token=null;
Map<String,String> headers = new HashMap<>();
String authorizationHeaderContents=getEncodedAuthorization(client_credentials_clientid,client_credentials_secret);
headers.put("Authorization","Basic "+authorizationHeaderContents);
headers.put("Content-Type", "application/x-www-form-urlencoded");
IHttpClient httpClient = new HttpClient();
String url = tokenUrl+"?grant_type=client_credentials&client_id="+client_credentials_clientid+"&scope=osduOnAws/fromNotificaton";
HttpRequest rq = HttpRequest.post().url(url).headers(headers).build();
HttpResponse result = httpClient.send(rq);
try {
AccessToken accessToken = this.getResult(result, AccessToken.class);
token = accessToken.getAccess_token();
}catch(Exception e)
{
System.out.println("Could not parse AccessToken result to get access_token");
}
return token;
}
public String getSecret(String secretName, String region,String secretKey) {
......@@ -210,4 +225,27 @@ String secretVaue="";
}
public String getEncodedAuthorization(String clientID, String clientSecret)
{
String base64Auth = Base64.getEncoder().encodeToString((clientID+":"+ clientSecret).getBytes());
return base64Auth;
}
private <T> T getResult(HttpResponse result, Class<T> type) throws EntitlementsException {
if (result.isSuccessCode()) {
try {
return result.parseBody(type);
} catch (JsonSyntaxException e) {
throw new EntitlementsException("Error parsing response. Check the inner HttpResponse for more info.",
result);
}
} else {
throw this.generateEntitlementsException(result);
}
}
private EntitlementsException generateEntitlementsException(HttpResponse result) {
return new EntitlementsException(
"Could not generate accessToken in Notification Service with client_credentials flow.", result);
}
}
......@@ -28,7 +28,7 @@ aws.region=${AWS_REGION}
aws.dynamodb.table.prefix=${RESOURCE_PREFIX}-
aws.dynamodb.endpoint=dynamodb.${AWS_REGION}.amazonaws.com
aws.tokenUrl=${OAUTH_TOKEN_URL}
app.expireTime=300
app.maxCacheSize=10
......
......@@ -38,14 +38,13 @@
<java.version>8</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
<os-core-lib-aws.version>0.3.11</os-core-lib-aws.version>
</properties>
<dependencies>
<dependency>
<groupId>org.opengroup.osdu.core.aws</groupId>
<artifactId>os-core-lib-aws</artifactId>
<version>0.3.11</version>
<version>0.3.12-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment