use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class KeyManagerConfigurationDataRetriever method run.
@Override
public void run() {
APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
if (apiManagerConfiguration != null) {
EventHubConfigurationDto eventHubConfigurationDto = apiManagerConfiguration.getEventHubConfigurationDto();
if (eventHubConfigurationDto != null && eventHubConfigurationDto.isEnabled()) {
try {
String url = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP).concat("/keymanagers");
byte[] credentials = Base64.encodeBase64((eventHubConfigurationDto.getUsername() + ":" + eventHubConfigurationDto.getPassword()).getBytes());
HttpGet method = new HttpGet(url);
method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
URL configUrl = new URL(url);
int port = configUrl.getPort();
String protocol = configUrl.getProtocol();
HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
HttpResponse httpResponse = null;
int retryCount = 0;
boolean retry;
do {
try {
httpResponse = httpClient.execute(method);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
KeyManagerConfiguration[] keyManagerConfigurations = new Gson().fromJson(responseString, KeyManagerConfiguration[].class);
for (KeyManagerConfiguration keyManagerConfiguration : keyManagerConfigurations) {
if (keyManagerConfiguration.isEnabled()) {
try {
ServiceReferenceHolder.getInstance().getKeyManagerConfigurationService().addKeyManagerConfiguration(keyManagerConfiguration.getTenantDomain(), keyManagerConfiguration.getName(), keyManagerConfiguration.getType(), keyManagerConfiguration);
} catch (APIManagementException e) {
log.error("Error while configuring Key Manager " + keyManagerConfiguration.getName() + " in tenant " + keyManagerConfiguration.getTenantDomain(), e);
}
}
}
retry = false;
} else {
retry = true;
retryCount++;
}
} catch (IOException ex) {
retryCount++;
int maxRetries = 15;
if (retryCount < maxRetries) {
retry = true;
long retryTimeout = (long) Math.min(Math.pow(2, retryCount), 300);
log.warn("Failed retrieving Key Manager Configurations from remote " + "endpoint: " + ex.getMessage() + ". Retrying after " + retryTimeout + " seconds...");
Thread.sleep(retryTimeout * 1000);
} else {
throw ex;
}
}
} while (retry);
} catch (InterruptedException | IOException e) {
log.error("Error while retrieving key manager configurations", e);
}
}
}
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowApprovedByAdmin.
@Test
public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception {
Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
roleMap.put(signUpRole, false);
UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
userRegistrationConfigDTO.setRoles(roleMap);
PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod();
PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true);
Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true);
// Set workflow status to be approved
workflowDTO.setStatus(WorkflowStatus.APPROVED);
workflowDTO.setTenantDomain(tenantDomain);
// Set tenant admin credentials
userRegistrationConfigDTO.setAdminUserName("admin");
userRegistrationConfigDTO.setAdminPassword("admin");
// Test failure to complete workflow execution, when error has been occurred while updating user with signup roles
Mockito.doThrow(UserStoreException.class).when(userStoreManager).updateRoleListOfUser(Mockito.anyString(), Mockito.any(), new String[] { Mockito.anyString() });
try {
userSignUpWSWorkflowExecutor.complete(workflowDTO);
Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed");
} catch (WorkflowException e) {
Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
}
// Test failure to complete workflow execution, when sign up roles are not existing in user realm
Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
try {
userSignUpWSWorkflowExecutor.complete(workflowDTO);
Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
} catch (WorkflowException e) {
Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
}
// Test failure to complete workflow execution, when error has been occurred while retrieving signup config
PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
try {
userSignUpWSWorkflowExecutor.complete(workflowDTO);
Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
} catch (WorkflowException e) {
Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
}
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method register.
@POST
@Override
public Response register(RegistrationProfile profile) {
/**
* sample message to this method
* {
* "callbackUrl": "www.google.lk",
* "clientName": "mdm",
* "tokenScope": "Production",
* "owner": "admin",
* "grantType": "password refresh_token",
* "saasApp": true
*}
*/
Response response;
String applicationName = null;
ErrorDTO errorDTO;
try {
OAuthAppRequest appRequest = new OAuthAppRequest();
OAuthApplicationInfo oauthApplicationInfo = new OAuthApplicationInfo();
OAuthApplicationInfo returnedAPP;
String loggedInUserTenantDomain;
String owner = profile.getOwner();
String authUserName = RestApiCommonUtil.getLoggedInUsername();
// correct domain
if (owner != null && authUserName != null) {
int index = authUserName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
int ownerIndex = owner.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
if (index > 0 && ownerIndex < 0) {
if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(authUserName.substring(0, index)) && owner.equals(authUserName.substring(index + 1))) {
if (log.isDebugEnabled()) {
log.debug("Update profile user name :" + owner + " with " + authUserName);
}
owner = authUserName;
profile.setOwner(owner);
}
}
}
// Validates if the application owner and logged in username is same.
if (authUserName != null && ((authUserName.equals(owner)) || isUserSuperAdmin(authUserName))) {
if (!isUserAccessAllowed(authUserName)) {
String errorMsg = "You do not have enough privileges to create an OAuth app";
log.error("User " + authUserName + " does not have any of subscribe/create/publish privileges " + "to create an OAuth app");
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403L, errorMsg);
response = Response.status(Response.Status.FORBIDDEN).entity(errorDTO).build();
return response;
}
// Getting client credentials from the profile
String grantTypes = profile.getGrantType();
oauthApplicationInfo.setClientName(profile.getClientName());
if (StringUtils.isNotBlank(profile.getCallbackUrl())) {
oauthApplicationInfo.setCallBackURL(profile.getCallbackUrl());
} else {
String[] grantTypeArr = grantTypes.split(" ");
for (String grantType : grantTypeArr) {
if ((grantType.equalsIgnoreCase(ApplicationConstants.AUTHORIZATION_CODE)) || (grantType.equalsIgnoreCase(ApplicationConstants.IMPLICIT_CONST))) {
grantTypes = grantTypes.replace(grantType, "");
}
}
}
String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
String profileTokenType = profile.getTokenType();
if (StringUtils.isNotEmpty(profileTokenType)) {
tokenType = profileTokenType;
}
oauthApplicationInfo.addParameter(OAUTH_CLIENT_USERNAME, owner);
oauthApplicationInfo.setClientId("");
oauthApplicationInfo.setClientSecret("");
oauthApplicationInfo.setIsSaasApplication(profile.isSaasApp());
oauthApplicationInfo.setTokenType(tokenType);
appRequest.setOAuthApplicationInfo(oauthApplicationInfo);
if (!authUserName.equals(owner)) {
loggedInUserTenantDomain = MultitenantUtils.getTenantDomain(owner);
} else {
loggedInUserTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
}
String userId = (String) oauthApplicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
String userNameForSP = MultitenantUtils.getTenantAwareUsername(userId);
// Replace domain separator by "_" if user is coming from a secondary userstore.
String domain = UserCoreUtil.extractDomainFromName(userNameForSP);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userNameForSP = userNameForSP.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
applicationName = profile.getClientName();
ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance();
// Check if the application is already exists
ServiceProvider appServiceProvider = null;
try {
appServiceProvider = applicationManagementService.getApplicationExcludingFileBasedSPs(applicationName, loggedInUserTenantDomain);
} catch (IdentityApplicationManagementException e) {
log.error("Error occurred while checking the existence of the application " + applicationName, e);
}
// Retrieving the existing application
if (appServiceProvider != null) {
returnedAPP = this.getExistingApp(applicationName, appServiceProvider.isSaasApp());
} else {
// create a new application if the application doesn't exists.
returnedAPP = this.createApplication(applicationName, appRequest, grantTypes);
}
// ReturnedAPP is null
if (returnedAPP == null) {
String errorMsg = "OAuth app '" + profile.getClientName() + "' creation or updating failed." + " Dynamic Client Registration Service not available.";
log.error(errorMsg);
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
} else {
if (log.isDebugEnabled()) {
log.debug("OAuth app " + profile.getClientName() + " creation successful.");
}
response = Response.status(Response.Status.OK).entity(returnedAPP).build();
}
} else {
String errorMsg = "Logged in user '" + authUserName + "' and application owner '" + owner + "' should be same.";
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg);
response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
}
} catch (APIManagementException e) {
String errorMsg = "Error occurred while trying to create the client application " + applicationName;
log.error(errorMsg, e);
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
}
return response;
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class APIMappingUtil method handleAWSCredentials.
/**
* Set AWS Secret Key based on preserveCredentials state
*
* @param awsEndpointConfig Endpoint configuration of the API
* @param preserveCredentials Condition to preserve credentials
* @return Updated endpoint config
*/
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
if (!preserveCredentials) {
awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
return awsEndpointConfig;
} else {
String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
// Decrypting the key since CTL project goes between environments which have different encryption keys.
try {
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
return awsEndpointConfig;
} catch (CryptoException | UnsupportedEncodingException e) {
log.error("Error while decrypting the Amazon key", e);
}
}
}
return awsEndpointConfig;
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class OAuthAuthenticator method authenticate.
@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) throws APIManagementException {
boolean isJwtToken = false;
String accessToken = null;
String remainingAuthHeader = "";
boolean defaultVersionInvoked = false;
Map headers = (Map) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
String tenantDomain = GatewayUtils.getTenantDomain();
keyManagerList = GatewayUtils.getKeyManagers(synCtx);
if (keyValidator == null) {
this.keyValidator = new APIKeyValidator();
}
if (jwtValidator == null) {
this.jwtValidator = new JWTValidator(this.keyValidator, tenantDomain);
}
config = getApiManagerConfiguration();
removeOAuthHeadersFromOutMessage = isRemoveOAuthHeadersFromOutMessage();
securityContextHeader = getSecurityContextHeader();
if (headers != null) {
requestOrigin = (String) headers.get("Origin");
// Extract the access token from auth header
// From 1.0.7 version of this component onwards remove the OAuth authorization header from
// the message is configurable. So we dont need to remove headers at this point.
String authHeader = (String) headers.get(getSecurityHeader());
if (authHeader == null) {
if (log.isDebugEnabled()) {
log.debug("OAuth2 Authentication: Expected authorization header with the name '".concat(getSecurityHeader()).concat("' was not found."));
}
} else {
ArrayList<String> remainingAuthHeaders = new ArrayList<>();
boolean consumerkeyFound = false;
String[] splitHeaders = authHeader.split(oauthHeaderSplitter);
if (splitHeaders != null) {
for (int i = 0; i < splitHeaders.length; i++) {
String[] elements = splitHeaders[i].split(consumerKeySegmentDelimiter);
if (elements != null && elements.length > 1) {
int j = 0;
boolean isConsumerKeyHeaderAvailable = false;
for (String element : elements) {
if (!"".equals(element.trim())) {
if (consumerKeyHeaderSegment.equals(elements[j].trim())) {
isConsumerKeyHeaderAvailable = true;
} else if (isConsumerKeyHeaderAvailable) {
accessToken = removeLeadingAndTrailing(elements[j].trim());
consumerkeyFound = true;
}
}
j++;
}
}
if (!consumerkeyFound) {
remainingAuthHeaders.add(splitHeaders[i]);
} else {
consumerkeyFound = false;
}
}
}
remainingAuthHeader = String.join(oauthHeaderSplitter, remainingAuthHeaders);
}
if (log.isDebugEnabled()) {
log.debug(accessToken != null ? "Received Token ".concat(accessToken) : "No valid Authorization header found");
}
// Check if client invoked the default version API (accessing API without version).
defaultVersionInvoked = headers.containsKey(defaultAPIHeader);
}
if (log.isDebugEnabled()) {
log.debug("Default Version API invoked");
}
if (removeOAuthHeadersFromOutMessage) {
// Remove authorization headers sent for authentication at the gateway and pass others to the backend
if (StringUtils.isNotBlank(remainingAuthHeader)) {
if (log.isDebugEnabled()) {
log.debug("Removing OAuth key from Authorization header");
}
headers.put(getSecurityHeader(), remainingAuthHeader);
} else {
if (log.isDebugEnabled()) {
log.debug("Removing Authorization header from headers");
}
headers.remove(getSecurityHeader());
}
}
if (removeDefaultAPIHeaderFromOutMessage) {
headers.remove(defaultAPIHeader);
}
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
SignedJWTInfo signedJWTInfo = null;
// If the matching resource does not require authentication
Timer timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_RESOURCE_AUTH"));
Timer.Context context = timer.start();
org.apache.axis2.context.MessageContext axis2MessageCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
org.apache.axis2.context.MessageContext.setCurrentMessageContext(axis2MessageCtx);
String authenticationScheme;
try {
// Initial guess of a JWT token using the presence of a DOT.
if (StringUtils.isNotEmpty(accessToken) && accessToken.contains(APIConstants.DOT)) {
try {
if (StringUtils.countMatches(accessToken, APIConstants.DOT) != 2) {
log.debug("Invalid JWT token. The expected token format is <header.payload.signature>");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
}
signedJWTInfo = getSignedJwt(accessToken);
if (GatewayUtils.isInternalKey(signedJWTInfo.getJwtClaimsSet()) || GatewayUtils.isAPIKey(signedJWTInfo.getJwtClaimsSet())) {
log.debug("Invalid Token Provided");
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
String keyManager = ServiceReferenceHolder.getInstance().getJwtValidationService().getKeyManagerNameIfJwtValidatorExist(signedJWTInfo);
if (StringUtils.isNotEmpty(keyManager)) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManager + "found for authenticate token " + GatewayUtils.getMaskedToken(accessToken));
}
if (keyManagerList.contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || keyManagerList.contains(keyManager)) {
if (log.isDebugEnabled()) {
log.debug("Elected KeyManager " + keyManager + "found in API level list " + String.join(",", keyManagerList));
}
isJwtToken = true;
} else {
if (log.isDebugEnabled()) {
log.debug("Elected KeyManager " + keyManager + " not found in API level list " + String.join(",", keyManagerList));
}
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("KeyManager not found for accessToken " + GatewayUtils.getMaskedToken(accessToken));
}
}
} catch (ParseException | IllegalArgumentException e) {
log.debug("Not a JWT token. Failed to decode the token header.", e);
} catch (APIManagementException e) {
log.error("error while check validation of JWt", e);
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
}
authenticationScheme = getAPIKeyValidator().getResourceAuthenticationScheme(synCtx);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
context.stop();
APIKeyValidationInfoDTO info;
if (APIConstants.NO_MATCHING_AUTH_SCHEME.equals(authenticationScheme)) {
info = new APIKeyValidationInfoDTO();
info.setAuthorized(false);
info.setValidationStatus(900906);
} else if (accessToken == null || apiContext == null || apiVersion == null) {
if (log.isDebugEnabled()) {
if (accessToken == null) {
log.debug("OAuth headers not found");
} else if (apiContext == null) {
log.debug("Couldn't find API Context");
} else {
log.debug("Could not find api version");
}
}
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_CREDENTIALS, "Required OAuth credentials not provided");
} else {
// Start JWT token validation
if (isJwtToken) {
try {
AuthenticationContext authenticationContext = jwtValidator.authenticate(signedJWTInfo, synCtx);
APISecurityUtils.setAuthenticationContext(synCtx, authenticationContext, securityContextHeader);
log.debug("User is authorized using JWT token to access the resource.");
synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, authenticationContext.getUsername());
return new AuthenticationResponse(true, isMandatory, false, 0, null);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
}
if (log.isDebugEnabled()) {
log.debug("Matching resource is: ".concat(matchingResource));
}
timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_KEY_VALIDATION_INFO"));
context = timer.start();
try {
info = getAPIKeyValidator().getKeyValidationInfo(apiContext, accessToken, apiVersion, authenticationScheme, matchingResource, httpMethod, defaultVersionInvoked, keyManagerList);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
context.stop();
synCtx.setProperty(APIMgtGatewayConstants.APPLICATION_NAME, info.getApplicationName());
synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, info.getEndUserName());
synCtx.setProperty(APIMgtGatewayConstants.SCOPES, info.getScopes() == null ? null : info.getScopes().toString());
}
if (info.isAuthorized()) {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setTier(info.getTier());
authContext.setApiKey(accessToken);
authContext.setKeyType(info.getType());
if (info.getEndUserName() != null) {
authContext.setUsername(info.getEndUserName());
} else {
authContext.setUsername(APIConstants.END_USER_ANONYMOUS);
}
authContext.setCallerToken(info.getEndUserToken());
authContext.setApplicationId(info.getApplicationId());
authContext.setApplicationUUID(info.getApplicationUUID());
authContext.setApplicationName(info.getApplicationName());
authContext.setApplicationTier(info.getApplicationTier());
authContext.setSubscriber(info.getSubscriber());
authContext.setConsumerKey(info.getConsumerKey());
authContext.setApiTier(info.getApiTier());
authContext.setThrottlingDataList(info.getThrottlingDataList());
authContext.setSubscriberTenantDomain(info.getSubscriberTenantDomain());
authContext.setSpikeArrestLimit(info.getSpikeArrestLimit());
authContext.setSpikeArrestUnit(info.getSpikeArrestUnit());
authContext.setStopOnQuotaReach(info.isStopOnQuotaReach());
authContext.setIsContentAware(info.isContentAware());
APISecurityUtils.setAuthenticationContext(synCtx, authContext, securityContextHeader);
if (info.getProductName() != null && info.getProductProvider() != null) {
authContext.setProductName(info.getProductName());
authContext.setProductProvider(info.getProductProvider());
}
/* Synapse properties required for BAM Mediator*/
// String tenantDomain = MultitenantUtils.getTenantDomain(info.getApiPublisher());
synCtx.setProperty("api.ut.apiPublisher", info.getApiPublisher());
synCtx.setProperty("API_NAME", info.getApiName());
/* GraphQL Query Analysis Information */
if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, info.getGraphQLMaxDepth());
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, info.getGraphQLMaxComplexity());
}
if (log.isDebugEnabled()) {
log.debug("User is authorized to access the Resource");
}
return new AuthenticationResponse(true, isMandatory, false, 0, null);
} else {
if (log.isDebugEnabled()) {
log.debug("User is NOT authorized to access the Resource");
}
return new AuthenticationResponse(false, isMandatory, true, info.getValidationStatus(), "Access failure for API: " + apiContext + ", version: " + apiVersion + " status: (" + info.getValidationStatus() + ") - " + APISecurityConstants.getAuthenticationFailureMessage(info.getValidationStatus()));
}
}
Aggregations