org.wso2.carbon.user.core.service.RealmService Java Examples

The following examples show how to use org.wso2.carbon.user.core.service.RealmService. 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: CarbonUserRealmHostObject.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example #2
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example #3
Source File: MigrationServiceComponent.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Method to unset realm service.
 *
 * @param realmService service to get tenant data.
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting RealmService from WSO2 EI Config component");
    }
    MigrationServiceDataHolder.setRealmService(null);
}
 
Example #4
Source File: EsMigrationServiceComponent.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * Method to set realm service.
 *
 * @param realmService service to get tenant data.
 */
protected void setRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Setting RealmService for WSO2 Enterprise Store migration");
    }
    ServiceHolder.setRealmService(realmService);
}
 
Example #5
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSelfSignupConfigFromRegistryTenant() throws Exception {
    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("foo.com");
    Mockito.when(privilegedCarbonContext.getRegistry(RegistryType.SYSTEM_GOVERNANCE)).thenReturn(registry);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId("foo.com")).thenReturn(4444);

    PowerMockito.mockStatic(APIUtil.class);
    Mockito.when(registry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(true);
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(resource.getContent()).thenReturn("wsdl".getBytes());
    Mockito.when(registry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(resource);
    OMElement omElement = Mockito.mock(OMElement.class);
    Mockito.when(omElement.getFirstChildWithName(Matchers.any(QName.class))).thenReturn(omElement);
    PowerMockito.mockStatic(AXIOMUtil.class);
    Mockito.when(omElement.getChildrenWithLocalName(APIConstants.SELF_SIGN_UP_REG_ROLE_ELEM)).thenReturn(Mockito.mock(Iterator.class));
    PowerMockito.when(AXIOMUtil.stringToOM("wsdl")).thenReturn(omElement);
    PowerMockito.mockStatic(PasswordResolverFactory.class);
    PasswordResolver passwordResolver = Mockito.mock(PasswordResolver.class);
    PowerMockito.when(PasswordResolverFactory.getInstance()).thenReturn(passwordResolver);
    UserRegistrationConfigDTO userRegistrationConfigDTO = SelfSignUpUtil.getSignupConfiguration("bar.com");
    Assert.assertNotNull(userRegistrationConfigDTO);
    PowerMockito.verifyStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext.endTenantFlow();
}
 
Example #6
Source File: HostObjectComponent.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Reference(
         name = "user.realm.service", 
         service = org.wso2.carbon.user.core.service.RealmService.class, 
         cardinality = ReferenceCardinality.MANDATORY, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
    if (realmService != null && log.isDebugEnabled()) {
        log.debug("Realm service initialized");
    }
    ServiceReferenceHolder.getInstance().setRealmService(realmService);
}
 
Example #7
Source File: SecurityMgtServiceComponent.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting the RealmService");
    }
    this.realmService = null;
    SecurityServiceHolder.setRealmService(null);
}
 
Example #8
Source File: FrameworkServiceComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {

        if (log.isDebugEnabled()) {
            log.debug("RealmService is unset in the Application Authentication Framework bundle");
        }
        FrameworkServiceDataHolder.getInstance().setRealmService(null);
    }
 
Example #9
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 #10
Source File: OutboundProvisioningManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param userName
 * @param tenantDomain
 * @return
 * @throws CarbonException
 * @throws UserStoreException
 */
private List<String> getUserRoles(String userName, String tenantDomain) throws CarbonException,
        UserStoreException {

    RegistryService registryService = IdentityProvisionServiceComponent.getRegistryService();
    RealmService realmService = IdentityProvisionServiceComponent.getRealmService();

    UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
            realmService, tenantDomain);

    UserStoreManager userstore = null;
    userstore = realm.getUserStoreManager();
    String[] newRoles = userstore.getRoleListOfUser(userName);
    return Arrays.asList(newRoles);
}
 
Example #11
Source File: PolicyManagementServiceComponent.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Sets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void setRealmService(RealmService realmService) {

    if (log.isDebugEnabled()) {
        log.debug("Setting Realm Service");
    }
    PolicyManagementDataHolder.getInstance().setRealmService(realmService);
}
 
Example #12
Source File: ClaimsMgtUtil.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets first name from the user store manager
 *
 * @param tenant   tenant
 * @param tenantId tenant id
 * @return first name
 * @throws UserStoreException , if error in getting the claim GIVEN_NAME
 */
public static String getFirstNamefromUserStoreManager(RealmService realmService,
                                                      int tenantId) throws UserStoreException {
    try {
        return getClaimfromUserStoreManager(realmService, tenantId,
                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
    } catch (Exception e) {
        String msg = "First Name not found for the tenant";
        log.debug(msg, e);
        return ""; // returns empty string
    }
}
 
Example #13
Source File: EventBrokerBuilderDS.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
@Reference(
        name = "realm.service",
        service = org.wso2.carbon.user.core.service.RealmService.class,
        cardinality = ReferenceCardinality.MANDATORY,
        policy = ReferencePolicy.DYNAMIC,
        unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {

    EventBrokerHolder.getInstance().registerRealmService(realmService);
}
 
Example #14
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
    RealmService realmService =
            (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
    if (realmService == null) {
        throw new IllegalStateException("Realm service has not been initialized.");
    }
    try {
        return realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new DeviceManagementException("Error occured while trying to " +
                "obtain tenant id of currently logged in user");
    }
}
 
Example #15
Source File: DeleteRoleWFRequestHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for delete role received without the mandatory " +
                "parameter 'username'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteRole(roleName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting role is aborted for role '" + roleName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example #16
Source File: TemplateMgtUIServiceComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Reference(
        name = "realm.service",
        service = org.wso2.carbon.user.core.service.RealmService.class,
        cardinality = ReferenceCardinality.MANDATORY,
        policy = ReferencePolicy.DYNAMIC,
        unbind = "unsetRealmService"
)
protected void setRealmService(RealmService realmService) {

    TemplateManagementUIServiceDataHolder.getInstance().setRealmService(realmService);
    if (realmService != null && log.isDebugEnabled()) {
        log.debug("RealmService is registered in ConsentManager service.");
    }
}
 
Example #17
Source File: RoleBasedScopesIssuer.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to get roles list of the user.
 *
 * @param authenticatedUser Authenticated user
 * @return roles list
 */
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {

    String[] userRoles = null;
    String tenantDomain;
    String username;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
        username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
        username = authenticatedUser.getUserName();
    }
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    RealmService realmService = getRealmService();
    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }
        UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
        userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);

    } catch (UserStoreException e) {
        //Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    return userRoles;
}
 
Example #18
Source File: ClaimsMgtUtil.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Gets first name from the user store manager
 * 
 * @param tenant
 *            tenant
 * @param tenantId
 *            tenant id
 * @return first name
 * @throws UserStoreException
 *             , if error in getting the claim GIVEN_NAME
 */
public static String getFirstNamefromUserStoreManager(RealmService realmService,
                                                      int tenantId) throws UserStoreException {
    try {
        return getClaimfromUserStoreManager(realmService, tenantId,
                                            UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
    } catch (Exception e) {
        String msg = "First Name not found for the tenant";
        log.debug(msg, e);
        return ""; // returns empty string
    }
}
 
Example #19
Source File: IdentityProvisionServiceComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param realmService
 */
@Reference(
         name = "realm.service", 
         service = org.wso2.carbon.user.core.service.RealmService.class, 
         cardinality = ReferenceCardinality.MANDATORY, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Setting the Realm Service");
    }
    ProvisioningServiceDataHolder.getInstance().setRealmService(realmService);
}
 
Example #20
Source File: PolicyManagementServiceComponent.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Unsets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting Realm Service");
    }
    PolicyManagementDataHolder.getInstance().setRealmService(null);
}
 
Example #21
Source File: OutboundProvisioningManager.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param userName
 * @param tenantDomain
 * @return
 * @throws CarbonException
 * @throws UserStoreException
 */
private Map<String, String> getUserClaims(String userName, String tenantDomain) throws CarbonException,
                                                                                       UserStoreException {

    Map<String, String> inboundAttributes = new HashMap<>();

    RegistryService registryService = IdentityProvisionServiceComponent.getRegistryService();
    RealmService realmService = IdentityProvisionServiceComponent.getRealmService();

    UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                                                                  realmService, tenantDomain);

    UserStoreManager userstore = null;
    userstore = realm.getUserStoreManager();
    Claim[] claimArray = null;
    try {
        claimArray = userstore.getUserClaimValues(userName, null);
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + userName + " not found in user store");
            }
        } else {
            throw e;
        }
    }
    if (claimArray != null) {
        for (Claim claim : claimArray) {
            inboundAttributes.put(claim.getClaimUri(), claim.getValue());
        }
    }

    return inboundAttributes;
}
 
Example #22
Source File: MergedPolicyEvaluationServiceComponent.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Unsets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting Realm Service");
    }
    PolicyDecisionPointDataHolder.getInstance().setRealmService(null);
}
 
Example #23
Source File: ThriftAuthenticationServiceComponent.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {
    setRealmServiceInstance(null);
}
 
Example #24
Source File: UserStoreConfigComponent.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {
    UserStoreConfigComponent.realmService = null;
    if (log.isDebugEnabled()) {
        log.debug("Unset the Realm Service");
    }
}
 
Example #25
Source File: UMRemoteServicesDataHolder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public RealmService getRealmService() {
    return realmService;
}
 
Example #26
Source File: UserStoreConfigComponent.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void setRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Setting the Realm Service");
    }
    UserStoreConfigComponent.realmService = realmService;
}
 
Example #27
Source File: UserRegistrationDSComponent.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public static RealmService getRealmService() {
    return realmService;
}
 
Example #28
Source File: DeleteClaimWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Set User Claim received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    String claimURI = (String) requestParams.get(CLAIM_URI);
    String profile = (String) requestParams.get(PROFILE_NAME);

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUserClaimValue(userName, claimURI, profile);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting User Claim is aborted for user '" + userName + "', ClaimURI:" + claimURI +
                    ", Reason: Workflow response was " + status);
        }
    }
}
 
Example #29
Source File: UserRegistrationDSComponent.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.info("Unsetting the Realm Service");
    }
    UserRegistrationDSComponent.realmService = null;
}
 
Example #30
Source File: SecurityDeploymentInterceptor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void setRealmService(RealmService realmService) {
    SecurityServiceHolder.setRealmService(realmService);
}