use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.
the class SystemScopesIssuer method getScopes.
/**
* This method is used to retrieve the authorized scopes with respect to a token.
*
* @param tokReqMsgCtx token message context
* @return authorized scopes list
*/
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
List<String> authorizedScopes = null;
List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
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)) {
return getAllowedScopes(requestedScopes);
}
String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
String[] userRoles = null;
// If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
// JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
// use user roles from assertion or jwt otherwise use roles from userstore.
String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
authenticatedUser.setUserStoreDomain("FEDERATED");
tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
userRoles = getRolesFromAssertion(assertion);
} else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
configureForJWTGrant(tokReqMsgCtx);
Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
}
} else {
userRoles = getUserRoles(authenticatedUser);
}
authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
}
return authorizedScopes;
}
use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property 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.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.
the class APIUtilTest method testGetOAuthConfigurationFromAPIMConfig.
@Test
public void testGetOAuthConfigurationFromAPIMConfig() throws Exception {
String property = "AuthorizationHeader";
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.OAUTH_CONFIGS + property)).thenReturn("APIM_AUTH");
String authHeader = getOAuthConfigurationFromAPIMConfig(property);
Assert.assertEquals("APIM_AUTH", authHeader);
}
use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.
the class CustomAPIIndexerTest method testIndexDocumentForNewAPI.
/**
* This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
*
* @throws RegistryException Registry Exception.
* @throws APIManagementException API Management Exception.
*/
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
Resource resource = new ResourceImpl();
PowerMockito.mockStatic(APIUtil.class);
GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(APIUtil.getArtifactManager((UserRegistry) (Mockito.anyObject()), Mockito.anyString())).thenReturn(artifactManager);
GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry)).thenReturn(Mockito.mock(API.class));
resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
indexer.getIndexedDocument(file2Index);
Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not " + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.
the class CommonThrottleMappingUtil method fromDTOListToConditionList.
/**
* Converts a list of Throttle Condition DTOs into a list of Condition model objects
*
* @param throttleConditionDTOs list of Throttle Condition DTOs
* @return Derived list of Condition model objects from Throttle Condition DTOs
* @throws UnsupportedThrottleConditionTypeException
*/
public static List<Condition> fromDTOListToConditionList(List<ThrottleConditionDTO> throttleConditionDTOs) throws UnsupportedThrottleConditionTypeException {
List<Condition> conditions = new ArrayList<>();
String errorMessage;
if (throttleConditionDTOs != null) {
for (ThrottleConditionDTO dto : throttleConditionDTOs) {
ThrottleConditionDTO.TypeEnum conditionType = dto.getType();
if (conditionType != null) {
switch(conditionType) {
case HEADERCONDITION:
{
if (dto.getHeaderCondition() != null) {
conditions.add(fromDTOToHeaderCondition(dto.getHeaderCondition(), dto.isInvertCondition()));
} else {
errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.HEADERCONDITION) + dto.toString();
throw new UnsupportedThrottleConditionTypeException(errorMessage);
}
break;
}
case IPCONDITION:
{
if (dto.getIpCondition() != null) {
conditions.add(fromDTOToIPCondition(dto.getIpCondition(), dto.isInvertCondition()));
} else {
errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.IPCONDITION) + dto.toString();
throw new UnsupportedThrottleConditionTypeException(errorMessage);
}
break;
}
case QUERYPARAMETERCONDITION:
{
if (dto.getQueryParameterCondition() != null) {
conditions.add(fromDTOToQueryParameterCondition(dto.getQueryParameterCondition(), dto.isInvertCondition()));
} else {
errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION) + dto.toString();
throw new UnsupportedThrottleConditionTypeException(errorMessage);
}
break;
}
case JWTCLAIMSCONDITION:
{
if (dto.getJwtClaimsCondition() != null) {
conditions.add(fromDTOToJWTClaimsCondition(dto.getJwtClaimsCondition(), dto.isInvertCondition()));
} else {
errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION) + dto.toString();
throw new UnsupportedThrottleConditionTypeException(errorMessage);
}
break;
}
default:
return null;
}
} else {
errorMessage = "Condition item 'type' property has not been specified\n" + dto.toString();
throw new UnsupportedThrottleConditionTypeException(errorMessage);
}
}
}
return conditions;
}
Aggregations