use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class RestApiUtil method handleMigrationSpecificPermissionViolations.
/**
* Handle if any cross tenant access permission violations detected. Cross tenant resources (apis/apps) can be
* retrieved only by super tenant admin user, only while a migration process(2.6.0 to 3.0.0). APIM server has to be
* started with the system property 'migrationMode=true' if a migration related exports are to be done.
*
* @param targetTenantDomain Tenant domain of which resources are requested
* @param username Logged in user name
* @throws ForbiddenException
*/
public static void handleMigrationSpecificPermissionViolations(String targetTenantDomain, String username) throws ForbiddenException {
boolean isCrossTenantAccess = !targetTenantDomain.equals(MultitenantUtils.getTenantDomain(username));
if (!isCrossTenantAccess) {
return;
}
String superAdminRole = null;
try {
superAdminRole = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminRoleName();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting super admin role name", e, log);
}
// check whether logged in user is a super tenant user
String superTenantDomain = null;
try {
superTenantDomain = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getSuperTenantDomain();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting the super tenant domain", e, log);
}
boolean isSuperTenantUser = RestApiCommonUtil.getLoggedInUserTenantDomain().equals(superTenantDomain);
if (!isSuperTenantUser) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a super " + "tenant user";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
// check whether the user has super tenant admin role
boolean isSuperAdminRoleNameExist = false;
try {
isSuperAdminRoleNameExist = APIUtil.isUserInRole(username, superAdminRole);
} catch (UserStoreException | APIManagementException e) {
RestApiUtil.handleInternalServerError("Error in checking whether the user has admin role", e, log);
}
if (!isSuperAdminRoleNameExist) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a " + "super tenant admin";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class BasicAuthenticationInterceptor method validateUserRolesWithRESTAPIScopes.
/**
* This method validates the user roles against the roles of the REST API scopes defined for the current resource.
*
* @param resourceScopeList Scope list of the current resource
* @param restAPIScopes RESTAPIScopes mapping for the current tenant
* @param userRoles Role list for the user
* @param username Username
* @param path Path Info
* @param verb HTTP Request Method
* @param inMessage cxf Message to set the matched user scopes for the resource
* @return whether user role validation against REST API scope roles is success or not.
*/
private boolean validateUserRolesWithRESTAPIScopes(List<Scope> resourceScopeList, Map<String, String> restAPIScopes, String[] userRoles, String username, String path, String verb, Message inMessage) {
// Holds the REST API scope list which the user will get successfully validated against with
List<Scope> validatedUserScopes = new ArrayList<>();
// iterate the non empty scope list of the URITemplate of the invoking resource
for (Scope scope : resourceScopeList) {
// get the configured roles list string of the requested resource
String resourceRolesString = restAPIScopes.get(scope.getKey());
if (StringUtils.isNotBlank(resourceRolesString)) {
// split role list string read using comma separator
List<String> resourceRoleList = Arrays.asList(resourceRolesString.split("\\s*,\\s*"));
// check if the roles related to the API resource contains any of the role of the user
for (String role : userRoles) {
if (resourceRoleList.contains(role)) {
// Role validation is success. Add the current scope to the validated user scope list and
// skip role check iteration of current scope and move to next resource scope.
validatedUserScopes.add(scope);
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: role validation successful for user: " + username + " with scope: " + scope.getKey() + " for resource path: " + path + " and verb " + verb);
log.debug("Added scope: " + scope.getKey() + " to validated user scope list");
}
break;
}
}
} else {
// No role for the requested resource scope. Add it to the validated user scope list.
validatedUserScopes.add(scope);
if (log.isDebugEnabled()) {
log.debug("Role validation skipped. No REST API scope to role mapping defined for resource scope: " + scope.getKey() + " Treated as anonymous scope.");
}
}
}
List<String> scopes = new ArrayList<>();
validatedUserScopes.forEach(scope -> scopes.add(scope.getKey()));
// Add the validated user scope list to the cxf message
inMessage.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, scopes.toArray(new String[0]));
if (!validatedUserScopes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Successfully validated REST API Scopes for the user " + username);
}
return true;
}
// none of the resource scopes were matched against the user role set
log.error("Insufficient privileges. Role validation failed for user: " + username + " to access resource path: " + path + " and verb " + verb);
return false;
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class SystemScopesMappingUtil method fromRoleScopeMapToRoleScopeDTOList.
/**
* Converts api scope-role mapping to RoleScopeDTO List.
*
* @param scopeRoleMapping Map of a Role Scope Mapping
* @return RoleScopeDTO list
*/
private static List<ScopeDTO> fromRoleScopeMapToRoleScopeDTOList(Map<String, String> scopeRoleMapping) throws APIManagementException {
List<ScopeDTO> scopeDTOs = new ArrayList<>(scopeRoleMapping.size());
if (portalScopeList.isEmpty()) {
synchronized (lock) {
if (portalScopeList.isEmpty()) {
portalScopeList = RestApiUtil.getScopesInfoFromAPIYamlDefinitions();
}
}
}
for (Map.Entry<String, List<String>> mapping : portalScopeList.entrySet()) {
// openid scope doesn't need a role mapping
if (APIConstants.OPEN_ID_SCOPE_NAME.equals(mapping.getKey())) {
continue;
}
if (scopeRoleMapping.containsKey(mapping.getKey())) {
ScopeDTO roleScopeDTO = new ScopeDTO();
roleScopeDTO.setName(mapping.getKey());
String roles = scopeRoleMapping.get(mapping.getKey());
List<String> roleList = new ArrayList<String>(Arrays.asList((roles.replaceAll("\\s+", "")).split(",")));
roleScopeDTO.setRoles(roleList);
roleScopeDTO.setDescription(mapping.getValue().get(0));
roleScopeDTO.setTag(mapping.getValue().get(1));
scopeDTOs.add(roleScopeDTO);
} else {
log.warn("The scope " + mapping.getKey() + " does not exist in tenant.conf");
}
}
return scopeDTOs;
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class SystemScopesMappingUtil method fromRoleAliasObjectToRoleAliasDTOList.
/**
* Converts api scope-role mapping to RoleScopeDTO List.
*
* @param roleMapping Map of a Role Scope Mapping
* @return RoleScopeDTO list
*/
private static List<RoleAliasDTO> fromRoleAliasObjectToRoleAliasDTOList(Map<String, List<String>> roleMapping) {
List<RoleAliasDTO> roleAliasDTOS = new ArrayList<>(roleMapping.size());
for (Map.Entry<String, List<String>> mapping : roleMapping.entrySet()) {
RoleAliasDTO roleAliasDTO = new RoleAliasDTO();
roleAliasDTO.setRole(mapping.getKey());
roleAliasDTO.setAliases(mapping.getValue());
roleAliasDTOS.add(roleAliasDTO);
}
return roleAliasDTOS;
}
use of org.wso2.charon3.core.objects.Role in project airavata by apache.
the class MigrationManager method getUserProfilesFromWso2IS.
/* Method used to fetch all the user profiles from the registered tenants */
public List<UserProfileDAO> getUserProfilesFromWso2IS() {
ArrayList<UserProfileDAO> userProfileList = new ArrayList<UserProfileDAO>();
for (Wso2ISLoginCredentialsDAO creds : adminCredentials) {
RemoteUserStoreManagerServiceStub isClient = Wso2IdentityServerClient.getAdminServiceClient(creds.getLoginUserName(), creds.getLoginPassword(), "RemoteUserStoreManagerService");
String[] userList;
System.out.println("Fetching User Profiles for " + creds.getGateway() + " tenant ...");
try {
userList = isClient.getUserList("http://wso2.org/claims/givenname", "*", "default");
System.out.println("FirstName\tLastName\tEmail\t\t\tuserName\tCountry\tOrganization\tphone\tRoles");
String[] claims = { "http://wso2.org/claims/givenname", "http://wso2.org/claims/lastname", "http://wso2.org/claims/emailaddress", "http://wso2.org/claims/country", "http://wso2.org/claims/organization", "http://wso2.org/claims/mobile", "http://wso2.org/claims/telephone", "http://wso2.org/claims/streetaddress", "http://wso2.org/claims/role", "http://wso2.org/claims/identity/accountLocked" };
for (String user : userList) {
UserProfileDAO userProfile = new UserProfileDAO();
ClaimValue[] retrievedClaimValues = isClient.getUserClaimValuesForClaims(user, claims, null);
List<String> phones = new ArrayList<String>();
for (ClaimValue claim : retrievedClaimValues) {
if (claim.getClaimURI().equals(claims[0])) {
userProfile.setFirstName(claim.getValue());
} else if (claim.getClaimURI().equals(claims[1])) {
userProfile.setLastName(claim.getValue());
} else if (claim.getClaimURI().equals(claims[2])) {
userProfile.setEmail(claim.getValue());
} else if (claim.getClaimURI().equals(claims[3])) {
userProfile.setCountry(claim.getValue());
} else if (claim.getClaimURI().equals(claims[4])) {
userProfile.setOrganization(claim.getValue());
} else if (claim.getClaimURI().equals(claims[5]) || claim.getClaimURI().equals(claims[6])) {
phones.add(claim.getValue());
} else if (claim.getClaimURI().equals(claims[7])) {
userProfile.setAddress(claim.getValue());
} else if (claim.getClaimURI().equals(claims[8])) {
userProfile.setRoles(convertCommaSeparatedRolesToList(claim.getValue()));
} else if (claim.getClaimURI().equals(claims[9])) {
userProfile.setAccountLocked(claim.getValue().equals("true"));
}
}
// Lowercase all usernames as required by Keycloak and User Profile service
userProfile.setUserName(user.toLowerCase());
userProfile.setGatewayID(creds.getGateway());
userProfile.setPhones(phones);
if (!userProfile.isAccountLocked()) {
System.out.println(userProfile.getFirstName() + "\t" + userProfile.getLastName() + "\t" + userProfile.getUserName() + "\t" + userProfile.getEmail() + "\t" + userProfile.getCountry() + "\t" + userProfile.getOrganization() + "\t" + userProfile.getAddress() + "\t" + userProfile.getRoles());
userProfileList.add(userProfile);
} else {
System.out.println("Skipping locked account for user " + user + "!");
}
}
} catch (RemoteException e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
} catch (RemoteUserStoreManagerServiceUserStoreExceptionException e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
}
System.out.println("User profiles from all the tenant are retrieved ...");
return userProfileList;
}
Aggregations