org.wso2.carbon.user.core.AuthorizationManager Java Examples

The following examples show how to use org.wso2.carbon.user.core.AuthorizationManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public static void setAnonAuthorization(String path, UserRealm userRealm)
        throws RegistryException {

    if (userRealm == null) {
        return;
    }

    try {
        AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
        String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;

        accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
        accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);

    } catch (UserStoreException e) {
        String msg = "Could not set authorizations for the " + path + ".";
        log.error(msg, e);
        throw new RegistryException(msg);
    }
}
 
Example #2
Source File: UserRealmProxy.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void buildUIPermissionNode(Collection parent, UIPermissionNode parentNode,
                                   Registry registry, Registry tenantRegistry, AuthorizationManager authMan,
                                   String roleName, String userName)
        throws RegistryException, UserStoreException {

    boolean isSelected = false;
    if (roleName != null) {
        isSelected = authMan.isRoleAuthorized(roleName, parentNode.getResourcePath(),
                UserMgtConstants.EXECUTE_ACTION);
    } else if (userName != null) {
        isSelected = authMan.isUserAuthorized(userName, parentNode.getResourcePath(),
                UserMgtConstants.EXECUTE_ACTION);
    }
    if (isSelected) {
        buildUIPermissionNodeAllSelected(parent, parentNode, registry, tenantRegistry);
        parentNode.setSelected(true);
    } else {
        buildUIPermissionNodeNotAllSelected(parent, parentNode, registry, tenantRegistry,
                authMan, roleName, userName);
    }
}
 
Example #3
Source File: CaptchaUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static void setAnonAuthorization(String path, UserRealm userRealm)
        throws RegistryException {

    if (userRealm == null) {
        return;
    }

    try {
        AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
        String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;

        accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
        accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);

    } catch (UserStoreException e) {
        String msg = "Could not set authorizations for the " + path + ".";
        log.error(msg, e);
        throw new RegistryException(msg);
    }
}
 
Example #4
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private static boolean isUserAuthorizedToConfigureProfile(UserRealm realm, String currentUserName,
                                                          String targetUser, String permission)
        throws UserStoreException {
    boolean isAuthrized = false;
    if (currentUserName == null) {
        //do nothing
    } else if (currentUserName.equals(targetUser)) {
        isAuthrized = true;
    } else {
        AuthorizationManager authorizer = realm.getAuthorizationManager();
        isAuthrized = authorizer.isUserAuthorized(currentUserName,
                CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION + permission,
                "ui.execute");
    }
    return isAuthrized;
}
 
Example #5
Source File: CommonUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static void setAnonAuthorization(String path, UserRealm userRealm)
        throws RegistryException {

    if (userRealm == null) {
        return;
    }

    try {
        AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
        String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;

        accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
        accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);

    } catch (UserStoreException e) {
        String msg = "Could not set authorizations for the " + path + ".";
        log.error(msg, e);
        throw new RegistryException(msg);
    }
}
 
Example #6
Source File: UserRealmProxy.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void buildUIPermissionNode(Collection parent, UIPermissionNode parentNode,
                                   Registry registry, Registry tenantRegistry, AuthorizationManager authMan,
                                   String roleName, String userName)
        throws RegistryException, UserStoreException {

    boolean isSelected = false;
    if (roleName != null) {
        isSelected = authMan.isRoleAuthorized(roleName, parentNode.getResourcePath(),
                UserMgtConstants.EXECUTE_ACTION);
    } else if (userName != null) {
        isSelected = authMan.isUserAuthorized(userName, parentNode.getResourcePath(),
                UserMgtConstants.EXECUTE_ACTION);
    }
    if (isSelected) {
        buildUIPermissionNodeAllSelected(parent, parentNode, registry, tenantRegistry);
        parentNode.setSelected(true);
    } else {
        buildUIPermissionNodeNotAllSelected(parent, parentNode, registry, tenantRegistry,
                authMan, roleName, userName);
    }
}
 
Example #7
Source File: APIManagerComponentImagePermissionTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    authManager = Mockito.mock(AuthorizationManager.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Registry registry = Mockito.mock(Registry.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);

    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(realmService.getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID)).thenReturn(userRealm);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(carbonContext.getRegistry(RegistryType.USER_GOVERNANCE)).thenReturn(registry);
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(APIUtil.getMountedPath(Mockito.any(RegistryContext.class), Mockito.anyString()))
            .thenReturn("");
    PowerMockito.doThrow(new IndexOutOfBoundsException()).when(APIMgtDBUtil.class, "initialize");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
}
 
Example #8
Source File: PermissionAuthorizationListener.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(String resourceId,
                            AuthorizationManager authorizationManager) throws
        UserStoreException {
    int tenantId = authorizationManager.getTenantId();
    if (tenantId == CarbonConstants.SUPER_TENANT_ID) {
        // no restrictions for the super tenant
        return true;
    }
    // so don't allow the rest of the tenants to set any permission to protected nodes
    String protectedPermissionPath = RegistryUtils.getAbsolutePath(null,
            RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    CarbonConstants.UI_PROTECTED_PERMISSION_COLLECTION);

    return !(resourceId.startsWith(protectedPermissionPath));
}
 
Example #9
Source File: UserRealmProxyTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@BeforeTest
public void setUp() throws Exception {
    startTenantFlow("carbon.super");
    realm = mock(UserRealm.class);
    userStoreManagerWithAb = mock(AbstractUserStoreManager.class);
    userStoreManager = mock(UserStoreManager.class);
    authorizationManager = mock(AuthorizationManager.class);
    claimManager = mock(ClaimManager.class);
    userRealmProxy = new UserRealmProxy(realm);
    Mockito.when(realm.getRealmConfiguration()).thenReturn(this.getSampleRelaimConfiguration());
}
 
Example #10
Source File: UserRealmProxy.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void buildUIPermissionNodeNotAllSelected(Collection parent, UIPermissionNode parentNode,
                                                 Registry registry, Registry tenantRegistry,
                                                 AuthorizationManager authMan, String roleName, String userName)
        throws RegistryException, UserStoreException {

    String[] children = parent.getChildren();
    UIPermissionNode[] childNodes = new UIPermissionNode[children.length];

    for (int i = 0; i < children.length; i++) {
        String child = children[i];
        Resource resource = null;

        if (tenantRegistry != null && child.startsWith("/permission/applications")) {
            resource = tenantRegistry.get(child);
        } else if (registry.resourceExists(child)) {
            resource = registry.get(child);
        } else {
            throw new RegistryException("Permission resource not found in the registry.");
        }

        boolean isSelected = false;
        if (roleName != null) {
            isSelected = authMan.isRoleAuthorized(roleName, child,
                    UserMgtConstants.EXECUTE_ACTION);
        } else if (userName != null) {
            isSelected = authMan.isUserAuthorized(userName, child,
                    UserMgtConstants.EXECUTE_ACTION);
        }
        childNodes[i] = getUIPermissionNode(resource, isSelected);
        if (resource instanceof Collection) {
            buildUIPermissionNodeNotAllSelected((Collection) resource, childNodes[i],
                    registry, tenantRegistry, authMan, roleName, userName);
        }
    }
    parentNode.setNodeList(childNodes);
}
 
Example #11
Source File: UserProfileUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static boolean isUserAuthorizedToConfigureProfile(UserRealm realm, String currentUserName, String targetUser)
        throws UserStoreException {
    boolean isAuthrized = false;
    if (currentUserName == null) {
        //do nothing
    } else if (currentUserName.equals(targetUser)) {
        isAuthrized = true;
    } else {
        AuthorizationManager authorizer = realm.getAuthorizationManager();
        isAuthrized = authorizer.isUserAuthorized(currentUserName,
                CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION + "/manage/identity/usermgt/profiles",
                "ui.execute");
    }
    return isAuthrized;
}
 
Example #12
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws UserStoreException, RegistryException {
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    userRealm = Mockito.mock(UserRealm.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    userStoreManager = Mockito.mock(UserStoreManager.class);
    keyManager = Mockito.mock(KeyManager.class);
    cacheInvalidator = Mockito.mock(CacheInvalidator.class);
    registryService = Mockito.mock(RegistryService.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registry = Mockito.mock(Registry.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    authorizationManager = Mockito.mock(AuthorizationManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ApplicationUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.mockStatic(CacheInvalidator.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(CacheInvalidator.getInstance()).thenReturn(cacheInvalidator);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(KeyManagerHolder.getKeyManagerInstance(Mockito.anyString(),Mockito.anyString())).thenReturn(keyManager);
    PowerMockito.when(APIUtil.replaceSystemProperty(anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
}
 
Example #13
Source File: AuthorizationManagerService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private AuthorizationManager getAuthorizationManager() throws UserStoreException {
    try {
        UserRealm realm = super.getUserRealm();
        if (realm == null) {
            throw new UserStoreException(NULL_REALM_MESSAGE);
        }
        return realm.getAuthorizationManager();
    } catch (Exception e) {
        throw new UserStoreException(e);
    }
}
 
Example #14
Source File: UserRealmProxy.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void setRoleUIPermission(String roleName, String[] rawResources)
        throws UserAdminException {
    try {
        if (((AbstractUserStoreManager) realm.getUserStoreManager()).isOthersSharedRole(roleName)) {
            throw new UserAdminException("Logged in user is not authorized to assign " +
                    "permissions to a role belong to another tenant");
        }
        if (realm.getRealmConfiguration().getAdminRoleName().equalsIgnoreCase(roleName)) {
            String msg = "UI permissions of Admin is not allowed to change";
            log.error(msg);
            throw new UserAdminException(msg);
        }

        String loggedInUserName = addPrimaryDomainIfNotExists(getLoggedInUser());
        String adminUser = addPrimaryDomainIfNotExists(realm.getRealmConfiguration().getAdminUserName());
        if (rawResources != null &&
                !adminUser.equalsIgnoreCase(loggedInUserName)) {
            Arrays.sort(rawResources);
            if (Arrays.binarySearch(rawResources, PERMISSION_ADMIN) > -1 ||
                    Arrays.binarySearch(rawResources, "/permission/protected") > -1 ||
                    Arrays.binarySearch(rawResources, PERMISSION) > -1) {
                log.warn("An attempt to Assign admin permission for role by user : " +
                        loggedInUserName);
                throw new UserStoreException("Can not assign Admin for permission role");
            }
        }

        String[] optimizedList = UserCoreUtil.optimizePermissions(rawResources);
        AuthorizationManager authMan = realm.getAuthorizationManager();
        authMan.clearRoleActionOnAllResources(roleName, UserMgtConstants.EXECUTE_ACTION);
        for (String path : optimizedList) {
            authMan.authorizeRole(roleName, path, UserMgtConstants.EXECUTE_ACTION);
        }
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        throw new UserAdminException(e.getMessage(), e);
    }
}
 
Example #15
Source File: UserRealmProxy.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void buildUIPermissionNodeNotAllSelected(Collection parent, UIPermissionNode parentNode,
                                                 Registry registry, Registry tenantRegistry,
                                                 AuthorizationManager authMan, String roleName, String userName)
        throws RegistryException, UserStoreException {

    String[] children = parent.getChildren();
    UIPermissionNode[] childNodes = new UIPermissionNode[children.length];

    for (int i = 0; i < children.length; i++) {
        String child = children[i];
        Resource resource = null;

        if (tenantRegistry != null && child.startsWith("/permission/applications")) {
            resource = tenantRegistry.get(child);
        } else if (registry.resourceExists(child)) {
            resource = registry.get(child);
        } else {
            throw new RegistryException("Permission resource not found in the registry.");
        }

        boolean isSelected = false;
        if (roleName != null) {
            isSelected = authMan.isRoleAuthorized(roleName, child,
                    UserMgtConstants.EXECUTE_ACTION);
        } else if (userName != null) {
            isSelected = authMan.isUserAuthorized(userName, child,
                    UserMgtConstants.EXECUTE_ACTION);
        }
        childNodes[i] = getUIPermissionNode(resource, isSelected);
        if (resource instanceof Collection) {
            buildUIPermissionNodeNotAllSelected((Collection) resource, childNodes[i],
                    registry, tenantRegistry, authMan, roleName, userName);
        }
    }
    parentNode.setNodeList(childNodes);
}
 
Example #16
Source File: UserProfileUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static boolean isUserAuthorizedToConfigureProfile(UserRealm realm, String currentUserName, String targetUser)
        throws UserStoreException {
    boolean isAuthrized = false;
    if (currentUserName == null) {
        //do nothing
    } else if (currentUserName.equals(targetUser)) {
        isAuthrized = true;
    } else {
        AuthorizationManager authorizer = realm.getAuthorizationManager();
        isAuthrized = authorizer.isUserAuthorized(currentUserName,
                CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION + "/configure/security/usermgt/profiles",
                "ui.execute");
    }
    return isAuthrized;
}
 
Example #17
Source File: PermissionAuthorizationListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(String resourceId,
                            AuthorizationManager authorizationManager) throws
        UserStoreException {
    int tenantId = authorizationManager.getTenantId();
    if (tenantId == CarbonConstants.SUPER_TENANT_ID) {
        // no restrictions for the super tenant
        return true;
    }
    // so don't allow the rest of the tenants to set any permission to protected nodes
    String protectedPermissionPath = RegistryUtils.getAbsolutePath(null,
            RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    CarbonConstants.UI_PROTECTED_PERMISSION_COLLECTION);

    return !(resourceId.startsWith(protectedPermissionPath));
}
 
Example #18
Source File: AuthorizationManagerMockCreator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
AuthorizationManager getMock() {
    return authorizationManager;
}
 
Example #19
Source File: AuthorizationManagerMockCreator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public AuthorizationManagerMockCreator() {
    authorizationManager = Mockito.mock(AuthorizationManager.class);
}
 
Example #20
Source File: WSRealm.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationManager getAuthorizationManager() throws UserStoreException {
    return authzMan;
}
 
Example #21
Source File: PermissionAuthorizationListener.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isUserAuthorized(String userName, String resourceId, String action,
                                AuthorizationManager authorizationManager) throws
        UserStoreException {
    return isAuthorized(resourceId, authorizationManager);
}
 
Example #22
Source File: PermissionAuthorizationListener.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isRoleAuthorized(String roleName, String resourceId, String action,
                                AuthorizationManager authorizationManager) throws
        UserStoreException {
    return isAuthorized(resourceId, authorizationManager);
}
 
Example #23
Source File: MockRealm.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationManager getAuthorizationManager() throws UserStoreException {
    return authorizationManager;
}
 
Example #24
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public SecurityConfigData getSecurityConfigData(String serviceName, String scenarioId,
                                                String policyPath) throws SecurityConfigException {

    SecurityConfigData data = null;
    AxisService service = axisConfig.getServiceForActivation(serviceName);
    String serviceGroupId = service.getAxisServiceGroup().getServiceGroupName();
    try {
        if (scenarioId == null) {
            return data;
        }
        /**
         * Scenario ID can either be a default one (out of 15) or "policyFromRegistry", which
         * means the current scenario refers to a custom policy from registry. If that is the
         * case, we can't read the current scenario from the WSU ID. Therefore, we don't
         * check the scenario ID. In default cases, we check it.
         */
        if (scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
            Parameter param = service.getParameter(SecurityConstants.SECURITY_POLICY_PATH);
            if (param == null || !policyPath.equals(param.getValue())) {
                return data;
            }
        } else {
            SecurityScenario scenario = readCurrentScenario(serviceName);
            if (scenario == null || !scenario.getScenarioId().equals(scenarioId)) {
                return data;
            }
        }

        Policy policy = getCurrentPolicy(service);
        OMElement carbonSecConfig = getCarbonSecConfigs(policy);
        RampartConfig rampartConfigs = getRampartConfigs(policy);
        Map<String, String> trustProperties = getTrustProperties(carbonSecConfig);
        KerberosConfigData kerberosData = this.readKerberosConfigurations(carbonSecConfig);

        data = new SecurityConfigData();
        data.setKerberosConfigurations(kerberosData);
        //may be we don't need this in the new persistence model
        // String serviceXPath = PersistenceUtils.getResourcePath(service);
        AuthorizationManager acReader = realm.getAuthorizationManager();
        String[] roles = acReader.getAllowedRolesForResource(
                serviceGroupId + "/" + serviceName,
                UserCoreConstants.INVOKE_SERVICE_PERMISSION);

        data.setUserGroups(roles);

        String privateStore = getProperty(rampartConfigs, trustProperties, ServerCrypto.PROP_ID_PRIVATE_STORE);
        if (StringUtils.isNotBlank(privateStore)) {
            data.setPrivateStore(privateStore);
        }

        String trustedStores = getProperty(rampartConfigs, trustProperties, ServerCrypto.PROP_ID_TRUST_STORES);
        if (StringUtils.isNotBlank(trustedStores)) {
            data.setTrustedKeyStores(trustedStores.split(","));
        }
        return data;

    } catch (UserStoreException e) {
        log.error("Error in getting security config data. Failed to get Authorization Manager", e);
    }
    return data;
}
 
Example #25
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public void applySecurity(String serviceName, String scenarioId, String policyPath,
                          String[] trustedStores, String privateStore,
                          String[] userGroups) throws SecurityConfigException {

    AxisService service = axisConfig.getServiceForActivation(serviceName);
    OMElement carbonSecConfigs = null;
    if (service == null) {
        throw new SecurityConfigException("Service not available.");
    }

    if (userGroups != null) {
        Arrays.sort(userGroups);
        if (Arrays.binarySearch(userGroups, CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME) > -1) {
            log.error("Security breach. A user is attempting to enable anonymous for UT access");
            throw new SecurityConfigException("Invalid data provided"); // obscure error message
        }
    }
    // First disable security and remove all applied policies before applying a new policy
    this.disableSecurityOnService(serviceName);

    OMElement policyElement = loadPolicyAsXML(scenarioId, policyPath);
    SecurityScenario scenario = SecurityScenarioDatabase.get(scenarioId);
    boolean isTrustEnabled = scenario.getModules().contains(SecurityConstants.TRUST_MODULE);

    if ((isTrustEnabled || (userGroups != null && userGroups.length > 0))) {
        carbonSecConfigs = addUserParameters(policyElement, trustedStores, privateStore, userGroups, null,
                isTrustEnabled, policyPath);
    }
    // If policy is taken from registry (custom policy) it needs to have rampartConfigs defined it.
    if (StringUtils.isNotBlank(policyPath)) {
        policyElement.addChild(buildRampartConfigXML(privateStore, trustedStores, null));
    }

    Policy policy = PolicyEngine.getPolicy(policyElement);
    try {
        persistPolicy(service, policyElement, policy.getId());
        applyPolicy(service, policy, carbonSecConfigs);
        String serviceGroupId = service.getAxisServiceGroup().getServiceGroupName();
        if (userGroups != null) {
            for (String value : userGroups) {
                AuthorizationManager acAdmin = realm.getAuthorizationManager();

                acAdmin.authorizeRole(value, serviceGroupId + "/" + service.getName(),
                        UserCoreConstants.INVOKE_SERVICE_PERMISSION);
            }
        }
        if (policyPath != null &&
                scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
            Parameter pathParam = new Parameter(SecurityConstants.SECURITY_POLICY_PATH,
                    policyPath);
            service.addParameter(pathParam);
        }

    } catch (Exception e) {
        throw new SecurityConfigException("Error while persisting policy in registry", e);
    }
}
 
Example #26
Source File: PermissionAuthorizationListener.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isUserAuthorized(String userName, String resourceId, String action,
                                AuthorizationManager authorizationManager) throws
        UserStoreException {
    return isAuthorized(resourceId, authorizationManager);
}
 
Example #27
Source File: PermissionAuthorizationListener.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isRoleAuthorized(String roleName, String resourceId, String action,
                                AuthorizationManager authorizationManager) throws
        UserStoreException {
    return isAuthorized(resourceId, authorizationManager);
}
 
Example #28
Source File: UserRealmProxy.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public void setRoleUIPermission(String roleName, String[] rawResources)
        throws UserAdminException {

    Permission[] permissions = null;
    UserStoreManager userStoreManager = null;
    try {
        if (((AbstractUserStoreManager) realm.getUserStoreManager()).isOthersSharedRole(roleName)) {
            throw new UserAdminException("Logged in user is not authorized to assign " +
                    "permissions to a role belong to another tenant");
        }
        if (realm.getRealmConfiguration().getAdminRoleName().equalsIgnoreCase(roleName)) {
            String msg = "UI permissions of Admin is not allowed to change";
            log.error(msg);
            throw new UserAdminException(msg);
        }

        String loggedInUserName = addPrimaryDomainIfNotExists(getLoggedInUser());
        String adminUser = addPrimaryDomainIfNotExists(realm.getRealmConfiguration().getAdminUserName());
        if (rawResources != null &&
                !adminUser.equalsIgnoreCase(loggedInUserName)) {
            Arrays.sort(rawResources);
            if (Arrays.binarySearch(rawResources, PERMISSION_ADMIN) > -1 ||
                    Arrays.binarySearch(rawResources, "/permission/protected") > -1 ||
                    Arrays.binarySearch(rawResources, PERMISSION) > -1) {
                log.warn("An attempt to Assign admin permission for role by user : " +
                        loggedInUserName);
                throw new UserStoreException("Can not assign Admin for permission role");
            }
        }

        String[] optimizedList = UserCoreUtil.optimizePermissions(rawResources);
        AuthorizationManager authMan = realm.getAuthorizationManager();
        authMan.clearRoleActionOnAllResources(roleName, UserMgtConstants.EXECUTE_ACTION);

        permissions = new Permission[optimizedList.length];
        for (int i = 0; i < optimizedList.length; i++) {
            authMan.authorizeRole(roleName, optimizedList[i], UserMgtConstants.EXECUTE_ACTION);
            permissions[i] = new Permission(optimizedList[i], UserMgtConstants.EXECUTE_ACTION);
        }

        userStoreManager = realm.getUserStoreManager();
        ManagementPermissionUtil.handlePostUpdatePermissionsOfRole(roleName, permissions, userStoreManager);
    } catch (UserStoreException e) {
        ManagementPermissionUtil
                .handleOnUpdatePermissionsOfRoleFailure(e.getMessage(), roleName, permissions, userStoreManager);
        log.error(e.getMessage(), e);
        throw new UserAdminException(e.getMessage(), e);
    }
}