use of org.wso2.carbon.apimgt.impl.template.ConfigContext in project carbon-apimgt by wso2.
the class GatewaySourceGeneratorImpl method getConfigStringFromTemplate.
@Override
public String getConfigStringFromTemplate(List<TemplateBuilderDTO> apiResources) throws APITemplateException {
StringWriter writer = new StringWriter();
String templatePath = "resources" + File.separator + "template" + File.separator + "template.xml";
try {
// build the context for template and apply the necessary decorators
apiConfigContext.validate();
ConfigContext configContext = new ResourceConfigContext(apiConfigContext, apiResources);
VelocityContext context = configContext.getContext();
VelocityEngine velocityengine = new VelocityEngine();
velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
velocityengine.init();
Template template = velocityengine.getTemplate(templatePath);
template.merge(context, writer);
} catch (ResourceNotFoundException e) {
log.error("Template " + templatePath + " not Found", e);
throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (ParseErrorException e) {
log.error("Syntax error in " + templatePath, e);
throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
}
return writer.toString();
}
use of org.wso2.carbon.apimgt.impl.template.ConfigContext in project carbon-apimgt by wso2.
the class GatewaySourceGeneratorImpl method getCompositeAPIConfigStringFromTemplate.
@Override
public String getCompositeAPIConfigStringFromTemplate(List<TemplateBuilderDTO> apiResources, List<CompositeAPIEndpointDTO> compositeApiEndpoints) throws APITemplateException {
StringWriter writer = new StringWriter();
String templatePath = "resources" + File.separator + "template" + File.separator + "composite_template.xml";
try {
// build the context for template and apply the necessary decorators
apiConfigContext.validate();
CompositeAPIConfigContext configContext = new CompositeAPIConfigContext(apiConfigContext, apiResources, compositeApiEndpoints);
VelocityContext context = configContext.getContext();
VelocityEngine velocityengine = new VelocityEngine();
velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
velocityengine.init();
Template template = velocityengine.getTemplate(templatePath);
template.merge(context, writer);
} catch (ResourceNotFoundException e) {
log.error("Template " + templatePath + " not Found", e);
throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (ParseErrorException e) {
log.error("Syntax error in " + templatePath, e);
throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
}
return writer.toString();
}
use of org.wso2.carbon.apimgt.impl.template.ConfigContext in project airavata by apache.
the class Wso2IdentityServerClient method getAdminServiceClient.
public static RemoteUserStoreManagerServiceStub getAdminServiceClient(String adminUserName, String adminPassword, String adminService) {
/**
* trust store path. this must contains server's certificate or Server's CA chain
*/
/* The below code snippet is intentionally commented for the build to pass,
* because the private key and certificate file are not committed to GitHub,
* which are needed to run the client */
// String trustStore = System.getProperty("user.dir") + File.separator +
// "modules" + File.separator + "user-profile-migration" + File.separator +
// "src" + File.separator + "main" + File.separator +
// "resources" + File.separator + "wso2carbon.jks";
// System.out.println("file path : " + trustStore);
/**
* Call to https://localhost:9443/services/ uses HTTPS protocol.
* Therefore we to validate the server certificate or CA chain. The server certificate is looked up in the
* trust store.
* Following code sets what trust-store to look for and its JKs password.
*/
// System.setProperty("javax.net.ssl.trustStore", trustStore );
// System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
// idp.scigap.org:9443 certificate has expired, so the following disables checking the certificate
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLContext.setDefault(sc);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
/**
* Axis2 configuration context
*/
ConfigurationContext configContext;
RemoteUserStoreManagerServiceStub adminStub;
try {
/**
* Create a configuration context. A configuration context contains information for
* axis2 environment. This is needed to create an axis2 service client
*/
configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
/**
* end point url with service name
*/
// String serviceEndPoint = SEVER_URL + "RemoteUserStoreManagerService";
String serviceEndPoint = SEVER_URL + adminService;
/**
* create stub and service client
*/
adminStub = new RemoteUserStoreManagerServiceStub(configContext, serviceEndPoint);
ServiceClient client = adminStub._getServiceClient();
Options option = client.getOptions();
/**
* Setting a authenticated cookie that is received from Carbon server.
* If you have authenticated with Carbon server earlier, you can use that cookie, if
* it has not been expired
*/
option.setProperty(HTTPConstants.COOKIE_STRING, null);
/**
* Setting basic auth headers for authentication for carbon server
*/
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername(adminUserName);
auth.setPassword(adminPassword);
auth.setPreemptiveAuthentication(true);
option.setProperty(HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
return adminStub;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use of org.wso2.carbon.apimgt.impl.template.ConfigContext in project airavata by apache.
the class SecureClient method main.
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// register client or use existing client
System.out.println("");
System.out.println("Please select from the following options:");
System.out.println("1. Register the client as an OAuth application.");
System.out.println("2. Client is already registered. Use the existing credentials.");
String opInput = scanner.next();
int option = Integer.valueOf(opInput.trim());
String consumerId = null;
String consumerSecret = null;
if (option == 1) {
// register OAuth application - this happens once during initialization of the gateway.
/**
**********************Start obtaining input from user****************************
*/
System.out.println("");
System.out.println("Registering an OAuth application representing the client....");
System.out.println("Please enter following information as you prefer, or use defaults.");
System.out.println("OAuth application name: (default:" + Properties.appName + ", press 'd' to use default value.)");
String appNameInput = scanner.next();
String appName = null;
if (appNameInput.trim().equals("d")) {
appName = Properties.appName;
} else {
appName = appNameInput.trim();
}
System.out.println("Consumer Id: (default:" + Properties.consumerID + ", press 'd' to use default value.)");
String consumerIdInput = scanner.next();
if (consumerIdInput.trim().equals("d")) {
consumerId = Properties.consumerID;
} else {
consumerId = consumerIdInput.trim();
}
System.out.println("Consumer Secret: (default:" + Properties.consumerSecret + ", press 'd' to use default value.)");
String consumerSecInput = scanner.next();
if (consumerSecInput.trim().equals("d")) {
consumerSecret = Properties.consumerSecret;
} else {
consumerSecret = consumerSecInput.trim();
}
/**
********************* Perform registration of the client as an OAuth app**************************
*/
try {
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
OAuthAppRegisteringClient authAppRegisteringClient = new OAuthAppRegisteringClient(Properties.oauthAuthzServerURL, Properties.adminUserName, Properties.adminPassword, configContext);
OAuthConsumerAppDTO appDTO = authAppRegisteringClient.registerApplication(appName, consumerId, consumerSecret);
/**
******************* Complete registering the client **********************************************
*/
System.out.println("");
System.out.println("Registered OAuth app successfully. Following is app's details:");
System.out.println("App Name: " + appDTO.getApplicationName());
System.out.println("Consumer ID: " + appDTO.getOauthConsumerKey());
System.out.println("Consumer Secret: " + appDTO.getOauthConsumerSecret());
System.out.println("");
} catch (AiravataSecurityException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else if (option == 2) {
System.out.println("");
System.out.println("Enter Consumer Id: ");
consumerId = scanner.next().trim();
System.out.println("Enter Consumer Secret: ");
consumerSecret = scanner.next().trim();
}
// obtain OAuth access token
/**
**********************Start obtaining input from user****************************
*/
System.out.println("");
System.out.println("Please select the preferred grant type: (or press d to use the default option" + Properties.grantType + ")");
System.out.println("1. Resource Owner Password Credential.");
System.out.println("2. Client Credential.");
String grantTypeInput = scanner.next().trim();
int grantType = 0;
if (grantTypeInput.equals("d")) {
grantType = Properties.grantType;
} else {
grantType = Integer.valueOf(grantTypeInput);
}
String userName = null;
String password = null;
if (grantType == 1) {
System.out.println("Obtaining OAuth access token via 'Resource Owner Password' grant type....");
System.out.println("Please enter following information as you prefer, or use defaults.");
System.out.println("End user's name: (default:" + Properties.userName + ", press 'd' to use default value.)");
String userNameInput = scanner.next();
if (userNameInput.trim().equals("d")) {
userName = Properties.userName;
} else {
userName = userNameInput.trim();
}
System.out.println("End user's password: (default:" + Properties.password + ", press 'd' to use default value.)");
String passwordInput = scanner.next();
if (passwordInput.trim().equals("d")) {
password = Properties.password;
} else {
password = passwordInput.trim();
}
} else if (grantType == 2) {
System.out.println("");
System.out.println("Please enter the user name to be passed: ");
String userNameInput = scanner.next();
userName = userNameInput.trim();
System.out.println("");
System.out.println("Obtaining OAuth access token via 'Client Credential' grant type...' grant type....");
}
/**
*************************** Finish obtaining input from user******************************************
*/
try {
// obtain the OAuth token for the specified end user.
String accessToken = new OAuthTokenRetrievalClient().retrieveAccessToken(consumerId, consumerSecret, userName, password, grantType);
System.out.println("");
System.out.println("OAuth access token is: " + accessToken);
// invoke Airavata API by the SecureClient, on behalf of the user.
System.out.println("");
System.out.println("Invoking Airavata API...");
System.out.println("Enter the access token to be used: (default:" + accessToken + ", press 'd' to use default value.)");
String accessTokenInput = scanner.next();
String acTk = null;
if (accessTokenInput.trim().equals("d")) {
acTk = accessToken;
} else {
acTk = accessTokenInput.trim();
}
// obtain as input, the method to be invoked
System.out.println("");
System.out.println("Enter the number corresponding to the method to be invoked: ");
System.out.println("1. getAPIVersion");
System.out.println("2. getAllAppModules");
System.out.println("3. addGateway");
String methodNumberString = scanner.next();
int methodNumber = Integer.valueOf(methodNumberString.trim());
Airavata.Client client = createAiravataClient(Properties.SERVER_HOST, Properties.SERVER_PORT);
AuthzToken authzToken = new AuthzToken();
authzToken.setAccessToken(acTk);
Map<String, String> claimsMap = new HashMap<>();
claimsMap.put("userName", userName);
claimsMap.put("email", "hasini@gmail.com");
authzToken.setClaimsMap(claimsMap);
if (methodNumber == 1) {
String version = client.getAPIVersion(authzToken);
System.out.println("");
System.out.println("Airavata API version: " + version);
System.out.println("");
} else if (methodNumber == 2) {
System.out.println("");
System.out.println("Enter the gateway id: ");
String gatewayId = scanner.next().trim();
List<ApplicationModule> appModules = client.getAllAppModules(authzToken, gatewayId);
System.out.println("Output of getAllAppModuels: ");
for (ApplicationModule appModule : appModules) {
System.out.println(appModule.getAppModuleName());
}
System.out.println("");
System.out.println("");
} else if (methodNumber == 3) {
System.out.println("");
System.out.println("Enter the gateway id: ");
String gatewayId = scanner.next().trim();
Gateway gateway = new Gateway(gatewayId, GatewayApprovalStatus.REQUESTED);
gateway.setDomain("airavata.org");
gateway.setEmailAddress("airavata@apache.org");
gateway.setGatewayName("airavataGW");
String output = client.addGateway(authzToken, gateway);
System.out.println("");
System.out.println("Output of addGateway: " + output);
System.out.println("");
}
} catch (InvalidRequestException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} catch (AiravataSecurityException e) {
e.printStackTrace();
}
}
use of org.wso2.carbon.apimgt.impl.template.ConfigContext in project airavata by apache.
the class DefaultAiravataSecurityManager method isUserAuthorized.
public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
try {
String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
String accessToken = authzToken.getAccessToken();
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String action = metaData.get(Constants.API_METHOD_NAME);
// if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is
if (ServerSettings.isAuthzCacheEnabled()) {
// obtain an instance of AuthzCacheManager implementation.
AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager();
// check in the cache
AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus(new AuthzCacheIndex(subject, gatewayId, accessToken, action));
if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return true;
} else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return false;
} else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + "Obtaining it from the authorization server.");
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision, cache it and return the result.
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
if (validationResponse.getValid()) {
String authorizedUserName = validationResponse.getAuthorizedUser();
if (authorizedUserName.contains("@")) {
authorizedUserName = authorizedUserName.split("@")[0];
}
if (subject.contains("@")) {
subject = subject.split("@")[0];
}
// cannot impersonate users
if (!authorizedUserName.toLowerCase().equals(subject.toLowerCase()))
return false;
long expiryTimestamp = validationResponse.getExpiryTime();
// check for fine grained authorization for the API invocation, based on XACML.
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
// cache the authorization decision
authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis()));
return authorizationDecision;
} else {
return false;
}
} else {
// undefined status returned from the authz cache manager
throw new AiravataSecurityException("Error in reading from the authorization cache.");
}
} else {
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled).
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
boolean isOAuthTokenValid = validationResponse.getValid();
// if XACML based authorization is enabled, check for role based authorization for the API invocation
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
return (isOAuthTokenValid && authorizationDecision);
}
} catch (AxisFault axisFault) {
logger.error(axisFault.getMessage(), axisFault);
throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client.");
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in reading OAuth server configuration.");
} catch (RegistryServiceException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in accessing AppCatalog.");
} catch (TException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in connecting to Credential Store Service.");
}
}
Aggregations