Java源码示例:org.wso2.carbon.user.api.UserRealm

示例1
/**
 * Sets a local claim directly at the userstore for the given user by given claim uri
 *
 * @param claimUri   Local claim URI
 * @param claimValue Claim value
 */
private void setLocalUserClaim(String claimUri, Object claimValue) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimUriMap = new HashMap<>();
        claimUriMap.put(claimUri, String.valueOf(claimValue));
        userRealm.getUserStoreManager().setUserClaimValues(usernameWithDomain, claimUriMap, null);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when setting claim : %s of user: %s to value: %s", claimUri,
                authenticatedUser, String.valueOf(claimValue)), e);
    }
}
 
示例2
/**
 * Get the local user claim value specified by the Claim URI.
 *
 * @param claimUri Local claim URI
 * @return Claim value of the given claim URI for the local user if available. Null Otherwise.
 */
private String getLocalUserClaim(String claimUri) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimValues = userRealm.getUserStoreManager().getUserClaimValues(usernameWithDomain, new
            String[]{claimUri}, null);
        return claimValues.get(claimUri);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when getting claim : %s of user: %s", claimUri, authenticatedUser), e);
    }
    return null;
}
 
示例3
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;
    }
 
示例4
private void assignApplicationRole(String applicationName, String username)
        throws IdentityApplicationManagementException {

    String roleName = getAppRoleName(applicationName);
    String[] newRoles = {roleName};

    try {
        // assign new application role to the user.
        UserRealm realm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
        if (realm != null) {
            if (((AbstractUserStoreManager) realm.getUserStoreManager()).isUserInRole(username, roleName)) {
                if (log.isDebugEnabled()) {
                    log.debug("The user: " + username + " is already having the role: " + roleName);
                }
            } else {
                realm.getUserStoreManager().updateRoleListOfUser(username, null, newRoles);
                if (log.isDebugEnabled()) {
                    log.debug("Assigning application role : " + roleName + " to the user : " + username);
                }
            }
        }
    } catch (UserStoreException e) {
        throw new IdentityApplicationManagementException("Error while assigning application role: " + roleName +
                " to the user: " + username, e);
    }
}
 
示例5
/**
 * Check the case sensitivity of the user store.
 *
 * @param userStoreDomain user store domain
 * @param tenantId        tenant id of the user store
 * @return
 */
public static boolean isUserStoreCaseSensitive(String userStoreDomain, int tenantId) {

    boolean isUsernameCaseSensitive = true;
    if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
        //this is to handle federated scenarios
        return true;
    }
    try {
        UserRealm tenantUserRealm = IdentityTenantUtil.getRealmService().getTenantUserRealm(tenantId);
        if (tenantUserRealm != null) {
            org.wso2.carbon.user.core.UserStoreManager userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) tenantUserRealm
                    .getUserStoreManager();
            org.wso2.carbon.user.core.UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager(userStoreDomain);
            return isUserStoreCaseSensitive(userAvailableUserStoreManager);
        }
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
示例6
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
示例7
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
示例8
/**
 * Check whether the client is authorized with the given permission and action.
 * @param permission           Carbon permission that requires for the use
 * @param action               Carbon permission action that requires for the given permission.
 * @return boolean - true if user is authorized else return false.
 */
private boolean isUserAuthorized(String permission, String action) {
    PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String username = context.getUsername();
    try {
        UserRealm userRealm = APIUtil.getRealmService().getTenantUserRealm(PrivilegedCarbonContext
                            .getThreadLocalCarbonContext().getTenantId());
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        boolean status =  userRealm.getAuthorizationManager()
                .isUserAuthorized(tenantAwareUsername, permission, action);
        if (!status) {
            String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(tenantAwareUsername);
            for (String role : roles) {
                if (role.equals(DEFAULT_ADMIN_ROLE)) {
                    return true;
                }
            }
        }
        return status;
    } catch (UserStoreException e) {
        String errorMsg = String.format("Unable to authorize the user : %s", username);
        log.error(errorMsg, e);
        return false;
    }
}
 
示例9
@Test(expected = AuthenticationException.class)
public void authorizeUser_throwsException() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenThrow(UserStoreException.class);

    AuthenticatorUtil.authorizeUser(httpHeaders);
}
 
示例10
@Test
public void testIsRoleNameNotExist() throws Exception {
    String userName = "John";
    String roleName = "developer";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.isExistingRole(roleName)).thenReturn(false);

    Assert.assertFalse(APIUtil.isRoleNameExist(userName, roleName));
}
 
示例11
@Test
public void testGetRoleNamesNonSuperTenant() throws Exception {
    String userName = "John";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    String[] roleNames = {"role1", "role2"};

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(userName)).
            thenReturn("test.com");
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getRoleNames()).thenReturn(roleNames);

    Assert.assertEquals(roleNames, APIUtil.getRoleNames(userName));
}
 
示例12
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;
}
 
示例13
public void subscribe(Subscription subscription) throws EventBrokerException {
   String resoucePath = JavaUtil.getResourcePath(subscription.getTopicName(), this.topicStoragePath);
    try {
        UserRealm userRealm =
                EventBrokerHolder.getInstance().getRealmService().getTenantUserRealm
                                           (CarbonContext.getThreadLocalCarbonContext().getTenantId());
        String userName = subscription.getOwner();
        // trim the domain part if it is there.
        if (userName.lastIndexOf("@") != -1){
            userName = userName.substring(0, userName.lastIndexOf("@"));
        }
        if (userName.equals(CarbonConstants.REGISTRY_SYSTEM_USERNAME) ||
                userRealm.getAuthorizationManager().isUserAuthorized(
                    userName,
                    resoucePath,
                    EventBrokerConstants.EB_PERMISSION_SUBSCRIBE)){
                   this.matchingManager.addSubscription(subscription);
        } else {
            throw new EventBrokerException("User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                           + " is not allowed to subscribes to " + subscription.getTopicName());
        }
    } catch (UserStoreException e) {
        throw new EventBrokerException("Can not access the user store manager");
    }

}
 
示例14
/**
 * Get Tenant UserStoreManager
 *
 * @return UserStoreManager
 * @throws UserManagerException
 */
private static UserStoreManager getTenantUserStoreManager() throws UserManagerException {

    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    UserRealm userRealm;
    UserStoreManager userStoreManager;

    try {
        userRealm = carbonContext.getUserRealm();
        userStoreManager = userRealm.getUserStoreManager();

    } catch (UserStoreException e) {
        String msg = "Error in retrieving UserStore Manager";
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }

    return userStoreManager;
}
 
示例15
private boolean authorize(String userName, String tenantDomain, int tenantId, Method targetMethod) throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) && !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized = isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
示例16
private boolean authorize(String userName, String tenantDomain, int tenantId,
                          Method targetMethod) throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) &&
            !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service
    // class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized =
            isAuthorized(authorizationManager, userName, permissionString,
                    ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
示例17
private boolean authorize(String userName, String tenantDomain, int tenantId, Method targetMethod)
        throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) && !isCurrentUserSuperTenant(tenantDomain,
            tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized = isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
示例18
public void addUser(String username, String password) {

        UserRealm tenantUserRealm = null;
        try {
            tenantUserRealm = IdentityTenantUtil.getRealmService().getTenantUserRealm(-1234);
            tenantUserRealm.getUserStoreManager().addUser(username, password, new String[]{"admin"}, null, null);
        } catch (UserStoreException e) {
            log.info("User already exists. Hence not adding: " + username);
            log.debug("Error while adding user :" + username, e);
        }

    }
 
示例19
@Override
@Deprecated
public String getAttributeName(String claimURI) throws UserStoreException {

    UserRealm realm = IdentityClaimManagementServiceDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(tenantId);
    String primaryDomainName = realm.getRealmConfiguration().getUserStoreProperty
            (UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    return getAttributeName(primaryDomainName, claimURI);
}
 
示例20
public static boolean isAdmin() throws UserStoreException {
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
    UserRealm realmService = DeviceMgtAPIUtils.getRealmService().getTenantUserRealm(tenantId);
    String adminRoleName = realmService.getRealmConfiguration().getAdminRoleName();
    String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
    String[] roles = realmService.getUserStoreManager().getRoleListOfUser(userName);
    for (String role: roles){
        if (role != null && role.equals(adminRoleName)){
            return true;
        }
    }
    return false;
}
 
示例21
private boolean isAdminUser(String username, int tenantId) throws UserStoreException {
    UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
    if (userRealm != null && userRealm.getAuthorizationManager() != null) {
        return userRealm.getAuthorizationManager()
                .isUserAuthorized(removeTenantDomain(username),
                                  PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION),
                        CarbonConstants.UI_PERMISSION_ACTION);
    }
    return false;
}
 
示例22
/**
 * Create configuration context.
 *
 * @param configurationContext {@link ConfigurationContext} object
 */
public void createdConfigurationContext(ConfigurationContext configurationContext) {
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        //Add the devicemgt-user and devicemgt-admin roles if not exists.
        UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
        UserStoreManager userStoreManager =
                DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
                        .getUserStoreManager();
        String tenantAdminName = userRealm.getRealmConfiguration().getAdminUserName();
        userStoreManager.addRole(User.DEFAULT_DEVICE_USER, null, User.PERMISSIONS_FOR_DEVICE_USER);
        userStoreManager.addRole(User.DEFAULT_DEVICE_ADMIN, new String[]{tenantAdminName},
                                 User.PERMISSIONS_FOR_DEVICE_ADMIN);
        if (log.isDebugEnabled()) {
            log.debug("Device management roles: " + User.DEFAULT_DEVICE_USER + ", " + User.DEFAULT_DEVICE_ADMIN +
                              " created for the tenant:" + tenantDomain + "."
            );
            log.debug("Tenant administrator: " + tenantAdminName + "@" + tenantDomain +
                              " is assigned to the role:" + User.DEFAULT_DEVICE_ADMIN + "."
            );
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while creating roles for the tenant: " + tenantDomain + ".");
    }
}
 
示例23
public static boolean isAdmin() throws UserStoreException {
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
    UserRealm realmService = DeviceMgtAPIUtils.getRealmService().getTenantUserRealm(tenantId);
    String adminRoleName = realmService.getRealmConfiguration().getAdminRoleName();
    String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
    String[] roles = realmService.getUserStoreManager().getRoleListOfUser(userName);
    for (String role: roles){
        if (role != null && role.equals(adminRoleName)){
            return true;
        }
    }
    return false;
}
 
示例24
private String[] getRoleOfDevice(Device device) throws PolicyManagementException {
    try {
        UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
        if (userRealm != null) {
            return userRealm.getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner());
        } else {
            return null;
        }
    } catch (UserStoreException e) {
        throw new PolicyManagementException("Error occurred when retrieving roles related to user name.", e);
    }
}
 
示例25
@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);
        }
    }
}
 
示例26
@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 delete user 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;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUser(userName);
        } 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 is aborted for user '" + userName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
示例27
@Test
public void authorizeUser() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.doReturn(true).when(userStoreManager).authenticate(any(String.class), any(String.class));

    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.doReturn("admin").when(realmConfiguration).getAdminRoleName();

    String[] userRoles = new String[2];
    userRoles[0] = "admin";
    userRoles[1] = "publisher";
    Mockito.doReturn(userRoles).when(userStoreManager).getRoleListOfUser(any(String.class));

    AuthDTO response = AuthenticatorUtil.authorizeUser(httpHeaders);
    Assert.assertEquals(Response.Status.OK, response.getResponseStatus());
}
 
示例28
@Test
public void authorizeUser_unauthroizedUser() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.doReturn(true).when(userStoreManager).authenticate(any(String.class), any(String.class));

    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.doReturn("admin").when(realmConfiguration).getAdminRoleName();

    String[] userRoles = new String[2];
    userRoles[0] = "subscriber";
    userRoles[1] = "publisher";

    Mockito.doReturn(userRoles).when(userStoreManager).getRoleListOfUser(any(String.class));

    AuthDTO response = AuthenticatorUtil.authorizeUser(httpHeaders);
    Assert.assertEquals(Response.Status.UNAUTHORIZED, response.getResponseStatus());
}
 
示例29
@Test
public void testIsRoleNameExist() throws Exception {
    String userName = "John";
    String roleName = "developer";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.isExistingRole(roleName)).thenReturn(true);

    Mockito.when(userStoreManager.isExistingRole("NonExistingDomain/role")).thenThrow(UserStoreException.class);
    Mockito.when(userStoreManager.isExistingRole("NonExistingDomain/")).thenThrow(UserStoreException.class);
    
    Assert.assertTrue(APIUtil.isRoleNameExist(userName, roleName));
    Assert.assertFalse(APIUtil.isRoleNameExist(userName, "NonExistingDomain/role"));
    Assert.assertFalse(APIUtil.isRoleNameExist(userName, "NonExistingDomain/"));
    Assert.assertTrue(APIUtil.isRoleNameExist(userName, ""));//allow adding empty role
}
 
示例30
/**
 * If the use is invalid, throws an <code>AuthenticationException</code>
 * If the password is equals to the shared key, returns <code>true</code>
 * Otherwise, calls the authenticate method of the <code>UserStoreManager<code>
 *
 * @param username The name of the user to be authenticated
 * @param password The password of the user to be authenticated.
 * @return <code>true</code> if the authentication is successful.
 * @throws AuthenticationException for failures in the authentication
 */
public boolean authenticate(String username, String password) throws AuthenticationException {
    String tenantLessUsername = MultitenantUtils.getTenantAwareUsername(username);
    try {
        int tenantID = MultitenantConstants.SUPER_TENANT_ID;
        if (username.contains("@")) {
            tenantID = realmService.getTenantManager().getTenantId(username.substring(username.lastIndexOf("@") + 1));
        }
        UserRealm userRealm = realmService.getTenantUserRealm(tenantID);

        // User not found in the UM
        if (!userRealm.getUserStoreManager().isExistingUser(tenantLessUsername)) {
            throw new AuthenticationException("Invalid User : " + tenantLessUsername, log);
        }

        // Authenticate internal call from another Carbon bundle
        if (password.equals(sharedKeyAccessService.getSharedKey())) {
            return true;
        }

        // Check if the user is authenticated
        return userRealm.getUserStoreManager().authenticate(tenantLessUsername, password);

        // Let the engine know if the user is authenticated or not
    } catch (UserStoreException e) {
        throw new AuthenticationException("User not authenticated for the given username : " + tenantLessUsername, log);
    }
}