use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.
the class APIUtil method replaceSystemProperty.
/**
* Resolves system properties and replaces in given in text
*
* @param text
* @return System properties resolved text
*/
public static String replaceSystemProperty(String text) {
int indexOfStartingChars = -1;
int indexOfClosingBrace;
// and are assumed to be System properties
while (indexOfStartingChars < text.indexOf("${") && (indexOfStartingChars = text.indexOf("${")) != -1 && (indexOfClosingBrace = text.indexOf('}')) != -1) {
// Is a
// property
// used?
String sysProp = text.substring(indexOfStartingChars + 2, indexOfClosingBrace);
String propValue = System.getProperty(sysProp);
if (propValue == null) {
if ("carbon.context".equals(sysProp)) {
propValue = ServiceReferenceHolder.getContextService().getServerConfigContext().getContextRoot();
} else if ("admin.username".equals(sysProp) || "admin.password".equals(sysProp)) {
try {
RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
if ("admin.username".equals(sysProp)) {
propValue = realmConfig.getAdminUserName();
} else {
propValue = realmConfig.getAdminPassword();
}
} catch (UserStoreException e) {
// Can't throw an exception because the server is
// starting and can't be halted.
log.error("Unable to build the Realm Configuration", e);
return null;
}
}
}
// Derive original text value with resolved system property value
if (propValue != null) {
text = text.substring(0, indexOfStartingChars) + propValue + text.substring(indexOfClosingBrace + 1);
}
if ("carbon.home".equals(sysProp) && propValue != null && ".".equals(propValue)) {
text = new File(".").getAbsolutePath() + File.separator + text;
}
}
return text;
}
use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.
the class BasicAuthenticationInterceptor method handleMessage.
/**
* This method handles the incoming message by checking if an anonymous api is being called or invalid
* authorization headers are present in the request. If not, authenticate the request.
*
* @param inMessage cxf Message
*/
@Override
@MethodStats
public void handleMessage(Message inMessage) {
// by-passes the interceptor if user calls an anonymous api
if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
return;
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
inMessage.put(RestApiConstants.TENANT_DOMAIN, tenantDomain);
// Extract and check if "Authorization: Basic" is present in the request. If not, by-passes the interceptor.
// If yes, set the request_authentication_scheme property in the message as basic_auth and execute the basic
// authentication flow.
AuthorizationPolicy policy = inMessage.get(AuthorizationPolicy.class);
if (policy != null) {
inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.BASIC_AUTHENTICATION);
// Extract user credentials from the auth header and validate.
String username = StringUtils.trim(policy.getUserName());
String password = StringUtils.trim(policy.getPassword());
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
String errorMessage = StringUtils.isEmpty(username) ? "username cannot be null/empty." : "password cannot be null/empty.";
log.error("Basic Authentication failed: " + errorMessage);
throw new AuthenticationException("Unauthenticated request");
} else if (!authenticate(inMessage, username, password)) {
throw new AuthenticationException("Unauthenticated request");
}
log.debug("User logged into web app using Basic Authentication");
}
}
use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.
the class SettingsMappingUtil method fromSettingstoDTO.
public SettingsDTO fromSettingstoDTO(Boolean isUserAvailable, Boolean moneatizationEnabled, boolean recommendationEnabled, boolean anonymousEnabled, String organization) throws APIManagementException {
SettingsDTO settingsDTO = new SettingsDTO();
settingsDTO.setScopes(GetScopeList());
settingsDTO.setApplicationSharingEnabled(APIUtil.isMultiGroupAppSharingEnabled());
settingsDTO.setRecommendationEnabled(recommendationEnabled);
settingsDTO.setMapExistingAuthApps(APIUtil.isMapExistingAuthAppsEnabled());
settingsDTO.setMonetizationEnabled(moneatizationEnabled);
SettingsIdentityProviderDTO identityProviderDTO = new SettingsIdentityProviderDTO();
identityProviderDTO.setExternal(APIUtil.getIdentityProviderConfig() != null);
settingsDTO.setIdentityProvider(identityProviderDTO);
settingsDTO.setIsAnonymousModeEnabled(anonymousEnabled);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
boolean enableChangePassword = Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENABLE_CHANGE_PASSWORD));
settingsDTO.setIsPasswordChangeEnabled(enableChangePassword);
String username = RestApiCommonUtil.getLoggedInUsername();
String tenantDomain = MultitenantUtils.getTenantDomain(username);
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
String userStorePasswordPattern = null;
String passwordPolicyPattern = null;
int passwordPolicyMinLength = -1;
int passwordPolicyMaxLength = -1;
try {
// Get password pattern from the UserStoreManager configuration
RealmConfiguration realmConfiguration = null;
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
UserStoreManager userStoreManager = null;
userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
realmConfiguration = userStoreManager.getRealmConfiguration();
}
if (realmConfiguration != null) {
String passwordJavaRegEx = realmConfiguration.getUserStoreProperty(APIConstants.PASSWORD_JAVA_REGEX_PROPERTY);
if (passwordJavaRegEx != null && !passwordJavaRegEx.trim().isEmpty()) {
userStorePasswordPattern = passwordJavaRegEx;
}
}
// Get password pattern from the Password policy
Property passwordPolicyEnabledProperty = FrameworkUtils.getResidentIdpConfiguration(APIConstants.IS_PASSWORD_POLICY_ENABLED_PROPERTY, tenantDomain);
boolean isPasswordPolicyEnabled = Boolean.parseBoolean(passwordPolicyEnabledProperty.getValue());
if (isPasswordPolicyEnabled) {
passwordPolicyPattern = FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_PATTERN_PROPERTY, tenantDomain).getValue();
passwordPolicyMinLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MIN_LENGTH_PROPERTY, tenantDomain).getValue());
passwordPolicyMaxLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MAX_LENGTH_PROPERTY, tenantDomain).getValue());
}
} catch (UserStoreException e) {
String errorMessage = "Error occurred in getting userRealm for the tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
} catch (FrameworkException e) {
String errorMessage = "Error occurred in getting Resident Idp Configurations for tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
}
settingsDTO.setUserStorePasswordPattern(userStorePasswordPattern);
settingsDTO.setPasswordPolicyPattern(passwordPolicyPattern);
settingsDTO.setPasswordPolicyMinLength(passwordPolicyMinLength);
settingsDTO.setPasswordPolicyMaxLength(passwordPolicyMaxLength);
if (isUserAvailable) {
settingsDTO.setGrantTypes(APIUtil.getGrantTypes());
Map<String, Environment> environments = APIUtil.getEnvironments(organization);
if (environments.isEmpty()) {
settingsDTO.apiGatewayEndpoint("http://localhost:8280, https://localhost:8243");
} else {
for (Map.Entry<String, Environment> entry : environments.entrySet()) {
Environment environment = environments.get(entry.getKey());
if (environment.isDefault()) {
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
break;
}
}
if (settingsDTO.getApiGatewayEndpoint() == null) {
Map.Entry<String, Environment> entry = environments.entrySet().iterator().next();
Environment environment = environments.get(entry.getKey());
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
}
}
}
return settingsDTO;
}
use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importAsyncAPISpecification.
/**
* Importing and AsyncAPI Specification and create and API
*
* @param fileInputStream InputStream for the provided file
* @param fileDetail File meta-data
* @param url URL of the AsyncAPI Specification
* @param additionalProperties API object (json) including additional properties like name, version, context
* @param messageContext CXF message context
* @return API import using AsyncAPI specification response
*/
@Override
public Response importAsyncAPISpecification(InputStream fileInputStream, Attachment fileDetail, String url, String additionalProperties, MessageContext messageContext) throws APIManagementException {
// validate 'additionalProperties' json
if (StringUtils.isBlank(additionalProperties)) {
RestApiUtil.handleBadRequest("'additionalProperties' is required and should not be null", log);
}
// Convert the 'additionalProperties' json into an APIDTO object
ObjectMapper objectMapper = new ObjectMapper();
APIDTO apiDTOFromProperties;
try {
apiDTOFromProperties = objectMapper.readValue(additionalProperties, APIDTO.class);
if (apiDTOFromProperties.getType() == null) {
RestApiUtil.handleBadRequest("Required property protocol is not specified for the Async API", log);
}
} catch (IOException e) {
throw RestApiUtil.buildBadRequestException("Error while parsing 'additionalProperties'", e);
}
// validate whether ASYNC APIs created without advertise only enabled
if (APIDTO.TypeEnum.ASYNC.equals(apiDTOFromProperties.getType()) && (apiDTOFromProperties.getAdvertiseInfo() == null || !apiDTOFromProperties.getAdvertiseInfo().isAdvertised())) {
RestApiUtil.handleBadRequest("ASYNC type APIs only can be created as third party APIs", log);
}
// validate websocket url and change transport types
if (PublisherCommonUtils.isValidWSAPI(apiDTOFromProperties)) {
ArrayList<String> websocketTransports = new ArrayList<>();
websocketTransports.add(APIConstants.WS_PROTOCOL);
websocketTransports.add(APIConstants.WSS_PROTOCOL);
apiDTOFromProperties.setTransport(websocketTransports);
}
// Import the API and Definition
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIDTO createdAPIDTO = importAsyncAPISpecification(fileInputStream, url, apiDTOFromProperties, fileDetail, null, organization);
URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdAPIDTO.getId());
return Response.created(createdApiUri).entity(createdAPIDTO).build();
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createAuditApi.
/**
* Send API Definition to Security Audit for the first time
* @param collectionId Collection ID in which the Definition should be sent to
* @param apiToken API Token to access Security Audit
* @param apiIdentifier API Identifier object
* @param apiDefinition API Definition of API
* @param baseUrl Base URL to communicate with Security Audit
* @param isDebugEnabled Boolean whether debug is enabled
* @param organization Organization
* @return String UUID of API in Security Audit
* @throws IOException In the event of any problems in the request
* @throws APIManagementException In the event of unexpected response
* @throws ParseException In the event of any parse errors from the response
*/
private String createAuditApi(String collectionId, String apiToken, APIIdentifier apiIdentifier, String apiDefinition, String baseUrl, boolean isDebugEnabled, String organization) throws IOException, APIManagementException, ParseException {
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String auditUuid = null;
URL url = new URL(baseUrl);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
// indicates POST method
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty(APIConstants.HEADER_CONTENT_TYPE, APIConstants.MULTIPART_CONTENT_TYPE + APIConstants.MULTIPART_FORM_BOUNDARY);
httpConn.setRequestProperty(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpConn.setRequestProperty(APIConstants.HEADER_API_TOKEN, apiToken);
httpConn.setRequestProperty(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
// Name property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"name\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiIdentifier.getApiName()).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// Specfile property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"specfile\"; filename=\"swagger.json\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.HEADER_CONTENT_TYPE + ": " + APIConstants.APPLICATION_JSON_MEDIA_TYPE).append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiDefinition).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// CollectionID property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"cid\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(collectionId).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY + "--").append(APIConstants.MULTIPART_LINE_FEED);
writer.close();
// Checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
if (isDebugEnabled) {
log.debug("HTTP status " + status);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
auditUuid = (String) ((JSONObject) responseJson.get(APIConstants.DESC)).get(APIConstants.ID);
ApiMgtDAO.getInstance().addAuditApiMapping(apiIdentifier, auditUuid, organization);
} else {
if (httpConn.getErrorStream() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
String errorMessage = httpConn.getResponseMessage();
if (responseJson.containsKey("message")) {
errorMessage = (String) responseJson.get("message");
}
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + errorMessage);
} else {
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + httpConn.getResponseMessage());
}
}
return auditUuid;
}
Aggregations