Java Code Examples for org.wso2.carbon.identity.core.util.IdentityUtil#extractDomainFromName()

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityUtil#extractDomainFromName() . 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: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getMultiAttributeSeparator(String authenticatedUser, int tenantId) {
    String claimSeparator = null;
    String userDomain = IdentityUtil.extractDomainFromName(authenticatedUser);

    try {
        RealmConfiguration realmConfiguration = null;
        RealmService realmService = OAuthComponentServiceHolder.getRealmService();

        if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
            UserStoreManager userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId)
                    .getUserStoreManager();
            realmConfiguration = userStoreManager.getSecondaryUserStoreManager(userDomain).getRealmConfiguration();
        }

        if (realmConfiguration != null) {
            claimSeparator = realmConfiguration.getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
            if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                return claimSeparator;
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while getting the realm configuration, User store properties might not be " +
                  "returned", e);
    }
    return null;
}
 
Example 2
Source File: UpdateClaimConfiguration.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
private RoleMapping buildRoleMapping(
        org.wso2.carbon.identity.api.server.application.management.v1.RoleMapping roleMapping) {

    String localRoleName = roleMapping.getLocalRole();
    /*
    For the local roles with userstore domain prepended to the role name, the domain name should not be
    removed from the role name since userstore domain of a role is identified via the given role name. If the
    domain name is not available in the role, the role's domain will be considered as PRIMARY.
    */
    if (localRoleName.contains(CarbonConstants.DOMAIN_SEPARATOR)) {
        String userStoreId = IdentityUtil.extractDomainFromName(localRoleName);
        return new RoleMapping(new LocalRole(userStoreId, localRoleName), roleMapping.getApplicationRole());
    }
    return new RoleMapping(new LocalRole(localRoleName), roleMapping.getApplicationRole());
}
 
Example 3
Source File: DefaultProvisioningHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * remove user store domain from names except the domain 'Internal'
 *
 * @param names
 * @return
 */
private List<String> removeDomainFromNamesExcludeInternal(List<String> names, int tenantId) {
    List<String> nameList = new ArrayList<String>();
    for (String name : names) {
        String userStoreDomain = IdentityUtil.extractDomainFromName(name);
        if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userStoreDomain)) {
            nameList.add(name);
        } else {
            nameList.add(UserCoreUtil.removeDomainFromName(name));
        }
    }
    return nameList;
}
 
Example 4
Source File: DefaultSequenceHandlerUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Remove domain name from roles except the hybrid roles (Internal,Application & Workflow)
 *
 * @param names list of roles assigned to a user
 * @return list of roles assigned to a user with domain name removed from roles
 */
private static List<String> removeDomainFromNamesExcludeHybrid(List<String> names) {

    List<String> nameList = new ArrayList<String>();
    for (String name : names) {
        String userStoreDomain = IdentityUtil.extractDomainFromName(name);
        if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userStoreDomain) || APPLICATION_DOMAIN
                .equalsIgnoreCase(userStoreDomain) || WORKFLOW_DOMAIN.equalsIgnoreCase(userStoreDomain)) {
            nameList.add(name);
        } else {
            nameList.add(UserCoreUtil.removeDomainFromName(name));
        }
    }
    return nameList;
}
 
Example 5
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Remove domain name from roles except the hybrid roles (Internal,Application & Workflow).
 *
 * @param domainAwareRolesList list of roles assigned to a user.
 * @return String of multi attribute separated list of roles assigned to a user with domain name removed from roles.
 */
public static String removeDomainFromNamesExcludeHybrid(List<String> domainAwareRolesList) {

    List<String> roleList = new ArrayList<String>();
    for (String role : domainAwareRolesList) {
        String userStoreDomain = IdentityUtil.extractDomainFromName(role);
        if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userStoreDomain) || APPLICATION_DOMAIN
                .equalsIgnoreCase(userStoreDomain) || WORKFLOW_DOMAIN.equalsIgnoreCase(userStoreDomain)) {
            roleList.add(role);
        } else {
            roleList.add(UserCoreUtil.removeDomainFromName(role));
        }
    }
    return String.join(FrameworkUtils.getMultiAttributeSeparator(), roleList);
}
 
Example 6
Source File: UserStoreConfigServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To check the provided domain set are exists to delete.
 *
 * @param domains domain name array.
 * @return true or false.
 */
private boolean validateDomainsForDelete(String[] domains) {

    String userDomain = IdentityUtil.extractDomainFromName(PrivilegedCarbonContext.getThreadLocalCarbonContext()
            .getUsername());
    for (String domain : domains) {
        if (domain.equalsIgnoreCase(userDomain)) {
            //Trying to delete own domain
            return false;
        }
    }
    return true;
}
 
Example 7
Source File: DefaultProvisioningHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * remove user store domain from names except the domain 'Internal'
 *
 * @param names
 * @return
 */
private List<String> removeDomainFromNamesExcludeInternal(List<String> names, int tenantId) {
    List<String> nameList = new ArrayList<String>();
    for (String name : names) {
        String userStoreDomain = IdentityUtil.extractDomainFromName(name);
        if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userStoreDomain)) {
            nameList.add(name);
        } else {
            nameList.add(UserCoreUtil.removeDomainFromName(name));
        }
    }
    return nameList;
}
 
Example 8
Source File: OAuthAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Registers an consumer secret against the logged in user. A given user can only have a single
 * consumer secret at a time. Calling this method again and again will update the existing
 * consumer secret key.
 *
 * @return An array containing the consumer key and the consumer secret correspondingly.
 * @throws Exception Error when persisting the data in the persistence store.
 */
public String[] registerOAuthConsumer() throws IdentityOAuthAdminException {

    String loggedInUser = CarbonContext.getThreadLocalCarbonContext().getUsername();

    if (log.isDebugEnabled()) {
        log.debug("Adding a consumer secret for the logged in user " + loggedInUser);
    }

    String tenantUser = MultitenantUtils.getTenantAwareUsername(loggedInUser);
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String userDomain = IdentityUtil.extractDomainFromName(loggedInUser);
    OAuthAppDAO dao = new OAuthAppDAO();
    return dao.addOAuthConsumer(UserCoreUtil.removeDomainFromName(tenantUser), tenantId, userDomain);
}
 
Example 9
Source File: UserStoreConfigAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean validateDomainsForDelete(String[] domains) {
    String userDomain = IdentityUtil.extractDomainFromName(PrivilegedCarbonContext.getThreadLocalCarbonContext()
            .getUsername());
    for (String domain : domains) {
        if (domain.equalsIgnoreCase(userDomain)) {
            //Trying to delete own domain
            return false;
        }
    }
    return true;

}
 
Example 10
Source File: SCIMUserManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the full group with all the details including users.
 *
 * @param groupName
 * @return
 * @throws CharonException
 * @throws org.wso2.carbon.user.core.UserStoreException
 * @throws IdentitySCIMException
 */
private Group getGroupWithName(String groupName)
        throws CharonException, org.wso2.carbon.user.core.UserStoreException,
        IdentitySCIMException {

    String userStoreDomainName = IdentityUtil.extractDomainFromName(groupName);
    if(!isInternalOrApplicationGroup(userStoreDomainName) && StringUtils.isNotBlank(userStoreDomainName) &&
            !isSCIMEnabled(userStoreDomainName)){
        throw new CharonException("Cannot retrieve group through scim to user store " + ". SCIM is not " +
                "enabled for user store " + userStoreDomainName);
    }

    Group group = new Group();
    group.setDisplayName(groupName);
    String[] userNames = carbonUM.getUserListOfRole(groupName);

    //get the ids of the users and set them in the group with id + display name
    if (userNames != null && userNames.length != 0) {
        for (String userName : userNames) {
            String userId = carbonUM.getUserClaimValue(userName, SCIMConstants.ID_URI, null);
            group.setMember(userId, userName);
        }
    }
    //get other group attributes and set.
    SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
    group = groupHandler.getGroupWithAttributes(group, groupName);
    return group;
}
 
Example 11
Source File: LocalRole.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public LocalRole(String combinedRoleName) {

        this.userStoreId = IdentityUtil.extractDomainFromName(combinedRoleName);
        this.localRoleName = UserCoreUtil.removeDomainFromName(combinedRoleName);
    }
 
Example 12
Source File: ApplicationDAOImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Stores basic application information and meta-data such as the application name, creator and
 * tenant.
 *
 * @param serviceProvider
 * @throws IdentityApplicationManagementException
 */
@Override
public int createApplication(ServiceProvider serviceProvider, String tenantDomain)
        throws IdentityApplicationManagementException {

    // get logged-in users tenant identifier.
    int tenantID = MultitenantConstants.INVALID_TENANT_ID;

    if (tenantDomain != null) {
        tenantID = IdentityTenantUtil.getTenantId(tenantDomain);
    }

    String qualifiedUsername = CarbonContext.getThreadLocalCarbonContext().getUsername();
    if (ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName())) {
        qualifiedUsername = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
    }
    String username = UserCoreUtil.removeDomainFromName(qualifiedUsername);
    String userStoreDomain = IdentityUtil.extractDomainFromName(qualifiedUsername);
    String applicationName = serviceProvider.getApplicationName();
    String description = serviceProvider.getDescription();

    if (log.isDebugEnabled()) {
        log.debug("Creating Application " + applicationName + " for user " + qualifiedUsername);
    }

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement storeAppPrepStmt = null;
    ResultSet results = null;

    try {
        String dbProductName = connection.getMetaData().getDatabaseProductName();
        storeAppPrepStmt = connection.prepareStatement(
                ApplicationMgtDBQueries.STORE_BASIC_APPINFO, new String[]{
                        DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "ID")});

        // TENANT_ID, APP_NAME, USER_STORE, USERNAME, DESCRIPTION, AUTH_TYPE
        storeAppPrepStmt.setInt(1, tenantID);
        storeAppPrepStmt.setString(2, applicationName);
        storeAppPrepStmt.setString(3, userStoreDomain);
        storeAppPrepStmt.setString(4, username);
        storeAppPrepStmt.setString(5, description);
        // by default authentication type would be default.
        // default authenticator is defined system-wide - in the configuration file.
        storeAppPrepStmt.setString(6, ApplicationConstants.AUTH_TYPE_DEFAULT);
        storeAppPrepStmt.execute();

        results = storeAppPrepStmt.getGeneratedKeys();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }

        int applicationId = 0;
        if (results.next()) {
            applicationId = results.getInt(1);
        }
        // some JDBC Drivers returns this in the result, some don't
        if (applicationId == 0) {
            if (log.isDebugEnabled()) {
                log.debug("JDBC Driver did not return the application id, executing Select operation");
            }
            applicationId = getApplicationIDByName(applicationName, tenantID, connection);
        }

        if (serviceProvider.getSpProperties() != null) {
            addServiceProviderProperties(connection, applicationId,
                    Arrays.asList(serviceProvider.getSpProperties()), tenantID);
        }

        if (log.isDebugEnabled()) {
            log.debug("Application Stored successfully with application id " + applicationId);
        }

        return applicationId;

    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException sql) {
            throw new IdentityApplicationManagementException(
                    "Error while Creating Application", sql);
        }
        throw new IdentityApplicationManagementException("Error while Creating Application", e);
    } finally {
        IdentityApplicationManagementUtil.closeResultSet(results);
        IdentityApplicationManagementUtil.closeStatement(storeAppPrepStmt);
        IdentityApplicationManagementUtil.closeConnection(connection);
    }
}
 
Example 13
Source File: LocalRole.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public LocalRole(String combinedRoleName) {
    this.userStoreId = IdentityUtil.extractDomainFromName(combinedRoleName);
    this.localRoleName = UserCoreUtil.removeDomainFromName(combinedRoleName);
}
 
Example 14
Source File: SAMLAssertionClaimsCallback.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Get claims from user store
 *
 * @param requestMsgCtx Token request message context
 * @return Users claim map
 * @throws Exception
 */
private static Map<String, Object> getClaimsFromUserStore(OAuthTokenReqMessageContext requestMsgCtx)
        throws UserStoreException, IdentityApplicationManagementException, IdentityException {

    String username = requestMsgCtx.getAuthorizedUser().toString();
    String tenantDomain = requestMsgCtx.getAuthorizedUser().getTenantDomain();

    UserRealm realm;
    List<String> claimURIList = new ArrayList<String>();
    Map<String, Object> mappedAppClaims = new HashMap<String, Object>();

    ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
    String spName = applicationMgtService
            .getServiceProviderNameByClientId(requestMsgCtx.getOauth2AccessTokenReqDTO().getClientId(),
                                              INBOUND_AUTH2_TYPE, tenantDomain);
    ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName,
                                                                                                tenantDomain);
    if (serviceProvider == null) {
        return mappedAppClaims;
    }

    realm = IdentityTenantUtil.getRealm(tenantDomain, username);
    if (realm == null) {
        log.warn("No valid tenant domain provider. Empty claim returned back for tenant " + tenantDomain
                 + " and user " + username);
        return new HashMap<>();
    }

    Map<String, String> spToLocalClaimMappings;
    UserStoreManager userStoreManager = realm.getUserStoreManager();
    ClaimMapping[] requestedLocalClaimMap = serviceProvider.getClaimConfig().getClaimMappings();

    if (requestedLocalClaimMap != null && requestedLocalClaimMap.length > 0) {

        for (ClaimMapping mapping : requestedLocalClaimMap) {
            if (mapping.isRequested()) {
                claimURIList.add(mapping.getLocalClaim().getClaimUri());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Requested number of local claims: " + claimURIList.size());
        }

        spToLocalClaimMappings = ClaimManagerHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(
                SP_DIALECT, null, tenantDomain, false);

        Map<String, String> userClaims = null;
        try {
            userClaims = userStoreManager.getUserClaimValues(
                    MultitenantUtils.getTenantAwareUsername(username),
                    claimURIList.toArray(new String[claimURIList.size()]), 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 (log.isDebugEnabled()) {
            log.debug("Number of user claims retrieved from user store: " + userClaims.size());
        }

        if (MapUtils.isEmpty(userClaims)) {
            return new HashMap<>();
        }

        for (Iterator<Map.Entry<String, String>> iterator = spToLocalClaimMappings.entrySet().iterator(); iterator
                .hasNext(); ) {
            Map.Entry<String, String> entry = iterator.next();
            String value = userClaims.get(entry.getValue());
            if (value != null) {
                mappedAppClaims.put(entry.getKey(), value);
                if (log.isDebugEnabled() &&
                        IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                    log.debug("Mapped claim: key -  " + entry.getKey() + " value -" + value);
                }
            }
        }

        String domain = IdentityUtil.extractDomainFromName(username);
        RealmConfiguration realmConfiguration = userStoreManager.getSecondaryUserStoreManager(domain)
                .getRealmConfiguration();

        String claimSeparator = realmConfiguration.getUserStoreProperty(
                IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            mappedAppClaims.put(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR, claimSeparator);
        }
    }
    return mappedAppClaims;
}
 
Example 15
Source File: SCIMUserManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private User getSCIMUser(String userName, List<String> claimURIList) throws CharonException {
    User scimUser = null;

    String userStoreDomainName = IdentityUtil.extractDomainFromName(userName);
    if(StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){
        throw new CharonException("Cannot add user through scim to user store " + ". SCIM is not " +
                "enabled for user store " + userStoreDomainName);
    }

    try {
        //obtain user claim values
        Map<String, String> attributes = carbonUM.getUserClaimValues(
                userName, claimURIList.toArray(new String[claimURIList.size()]), null);
        //skip simple type addresses claim coz it is complex with sub types in the schema
        if (attributes.containsKey(SCIMConstants.ADDRESSES_URI)) {
            attributes.remove(SCIMConstants.ADDRESSES_URI);
        }

        // Add username with domain name
        attributes.put(SCIMConstants.USER_NAME_URI, userName);

        //get groups of user and add it as groups attribute
        String[] roles = carbonUM.getRoleListOfUser(userName);
        //construct the SCIM Object from the attributes
        scimUser = (User) AttributeMapper.constructSCIMObjectFromAttributes(
                attributes, SCIMConstants.USER_INT);
        //add groups of user:
        for (String role : roles) {
            if (UserCoreUtil.isEveryoneRole(role, carbonUM.getRealmConfiguration())
                    || UserCoreUtil.isPrimaryAdminRole(role, carbonUM.getRealmConfiguration())
                    || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equalsIgnoreCase(role)
                    || role.toLowerCase().startsWith((UserCoreConstants.INTERNAL_DOMAIN +
                    CarbonConstants.DOMAIN_SEPARATOR).toLowerCase())) {
                // carbon specific roles do not possess SCIM info, hence
                // skipping them.
                // skip intenal roles
                continue;
            }
            Group group = getGroupOnlyWithMetaAttributes(role);
            if (group != null) { // can be null for non SCIM groups
                scimUser.setGroup(null, group.getId(), role);
            }
        }
    } catch (UserStoreException | CharonException | NotFoundException | IdentitySCIMException e) {
        throw new CharonException("Error in getting user information for user: " + userName, e);
    }
    return scimUser;
}