use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.
the class ApiMgtDAO method getConsumerKeysForApplication.
/**
* Retrieves the consumer keys and keymanager in a given application
*
* @param appId application id
* @return Map<ConsumerKey, Pair<keyManagerName, keyManagerTenantDomain>
* @throws APIManagementException
*/
public Map<String, Pair<String, String>> getConsumerKeysForApplication(int appId) throws APIManagementException {
Map<String, Pair<String, String>> consumerKeysOfApplication = new HashMap<>();
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.GET_CONSUMER_KEY_OF_APPLICATION_SQL)) {
preparedStatement.setInt(1, appId);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
String consumerKey = resultSet.getString("CONSUMER_KEY");
String keyManagerName = resultSet.getString("NAME");
String keyManagerOrganization = resultSet.getString("ORGANIZATION");
consumerKeysOfApplication.put(consumerKey, Pair.of(keyManagerName, keyManagerOrganization));
}
}
} catch (SQLException e) {
String msg = "Error occurred while getting consumer keys for application " + appId;
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return consumerKeysOfApplication;
}
use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.
the class APIAuthenticationHandler method isAuthenticate.
/**
* Authenticates the given request using the authenticators which have been initialized.
*
* @param messageContext The message to be authenticated
* @return true if the authentication is successful (never returns false)
* @throws APISecurityException If an authentication failure or some other error occurs
*/
protected boolean isAuthenticate(MessageContext messageContext) throws APISecurityException, APIManagementException {
boolean authenticated = false;
AuthenticationResponse authenticationResponse;
List<AuthenticationResponse> authResponses = new ArrayList<>();
for (Authenticator authenticator : authenticators) {
authenticationResponse = authenticator.authenticate(messageContext);
if (authenticationResponse.isMandatoryAuthentication()) {
// Update authentication status only if the authentication is a mandatory one
authenticated = authenticationResponse.isAuthenticated();
}
if (!authenticationResponse.isAuthenticated()) {
authResponses.add(authenticationResponse);
}
if (!authenticationResponse.isContinueToNextAuthenticator()) {
break;
}
}
if (!authenticated) {
Pair<Integer, String> error = getError(authResponses);
throw new APISecurityException(error.getKey(), error.getValue());
}
return true;
}
use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.
the class SystemScopesIssuer method validateScope.
@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
if (accessTokenDO == null) {
return false;
}
String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
// Return true if there is no resource to validate the token against.
if (resource == null) {
return true;
}
// Get the list of scopes associated with the access token
String[] scopes = accessTokenDO.getScope();
// If no scopes are associated with the token
if (scopes == null || scopes.length == 0) {
return true;
}
String resourceScope = null;
int resourceTenantId = -1;
boolean cacheHit = false;
// Check the cache, if caching is enabled.
OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
// Cache hit
if (result != null && result instanceof ResourceScopeCacheEntry) {
resourceScope = ((ResourceScopeCacheEntry) result).getScope();
resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
cacheHit = true;
}
// Cache was not hit. So retrieve from database.
if (!cacheHit) {
Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
if (scopeMap != null) {
resourceScope = scopeMap.getLeft();
resourceTenantId = scopeMap.getRight();
}
cacheKey = new OAuthCacheKey(resource);
ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
cacheEntry.setTenantId(resourceTenantId);
// Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
// which scopes haven't been defined).
OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
}
// Return TRUE if - There does not exist a scope definition for the resource
if (resourceScope == null) {
if (log.isDebugEnabled()) {
log.debug("Resource '" + resource + "' is not protected with a scope");
}
return true;
}
List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
// If the access token does not bear the scope required for accessing the Resource.
if (!scopeList.contains(resourceScope)) {
if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
}
return false;
}
// This system property is set at server start using -D option, Thus will be a permanent property.
if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
return true;
}
AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
String clientId = accessTokenDO.getConsumerKey();
List<String> requestedScopes = Arrays.asList(scopes);
List<String> authorizedScopes = null;
String[] userRoles = null;
Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
if (appScopes != null) {
// If no scopes can be found in the context of the application
if (isAppScopesEmpty(appScopes, clientId)) {
authorizedScopes = getAllowedScopes(requestedScopes);
oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
return true;
}
userRoles = getUserRoles(authenticatedUser);
authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
}
if (ArrayUtils.isEmpty(userRoles)) {
if (log.isDebugEnabled()) {
log.debug("No roles associated for the user " + authenticatedUser.getUserName());
}
return false;
}
return true;
}
use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method fromAppDTOToApplicationInfo.
/**
* Creating a OAuthApplicationInfo type object to return
*
* @param clientId client id
* @param clientName client name
* @param callbackUrl callback url
* @param clientSecret clientSecret
* @param saasApp IsSaasApp
* @param appOwner AppOwner
* @param sampleMap Map
* @return OAuthApplicationInfo object containing parsed values.
*/
private OAuthApplicationInfo fromAppDTOToApplicationInfo(String clientId, String clientName, String callbackUrl, String clientSecret, boolean saasApp, String appOwner, Map<String, String> sampleMap) {
OAuthApplicationInfo updatingApp = new OAuthApplicationInfo();
updatingApp.setClientId(clientId);
updatingApp.setClientName(clientName);
updatingApp.setCallBackURL(callbackUrl);
updatingApp.setClientSecret(clientSecret);
updatingApp.setIsSaasApplication(saasApp);
updatingApp.setAppOwner(appOwner);
Iterator it = sampleMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
updatingApp.addParameter((String) pair.getKey(), pair.getValue());
it.remove();
}
return updatingApp;
}
use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.
the class PolicyUtil method deployPolicy.
/**
* Deploy the given throttle policy in the Traffic Manager.
*
* @param policy policy object
* @param policyEvent policy event object which was triggered
*/
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
Map<String, String> policiesToDeploy = new HashMap<>();
List<String> policiesToUndeploy = new ArrayList<>();
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
String policyFile;
String policyString;
if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
// Add Subscription policy
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
policiesToDeploy.put(policyFile, policyString);
} else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
// Add Application policy
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
policiesToDeploy.put(policyFile, policyString);
} else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
// Add API policy
policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
policiesToDeploy.put(defaultPolicyName, defaultPolicy);
if (policyEvent instanceof APIPolicyEvent) {
List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
// Undeploy removed condition groups
if (deletedConditionGroupIds != null) {
for (int conditionGroupId : deletedConditionGroupIds) {
policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
}
}
}
} else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
// Add Global policy
GlobalPolicy globalPolicy = (GlobalPolicy) policy;
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
policiesToDeploy.put(policyFile, policyString);
}
// Undeploy removed policies
undeployPolicies(policiesToUndeploy);
for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
String policyPlanName = pair.getKey();
String flowString = pair.getValue();
String executionPlan = null;
try {
executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
} catch (ExecutionPlanConfigurationException e) {
// Deploy new policies
eventProcessorService.deployExecutionPlan(flowString);
}
if (executionPlan != null) {
// Update existing policies
eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
}
}
} catch (APITemplateException e) {
log.error("Error in creating execution plan", e);
} catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
log.error("Error in deploying execution plan", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
Aggregations