Java Code Examples for org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantDomain()

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantDomain() . 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: IdentityUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store in which the user is in.
 *
 * @param username Full qualified username
 * @return
 */
public static boolean isUserStoreInUsernameCaseSensitive(String username) {

    boolean isUsernameCaseSensitive = true;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = IdentityTenantUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
        return isUserStoreInUsernameCaseSensitive(username, tenantId);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example 2
Source File: APISynchronizer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Method to load the configurations of a tenant
 */
private void loadTenant(String username) {
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        ConfigurationContext context = ServiceDataHolder.getInstance().getConfigurationContextService()
                .getServerConfigContext();
        TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, context);
        if (log.isDebugEnabled()) {
            log.debug("Tenant was loaded into Carbon Context. Tenant : " + tenantDomain
                    + ", Username : " + username);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping loading super tenant space since execution is currently in super tenant flow.");
        }
    }
}
 
Example 3
Source File: AbstractScopesIssuer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to get the application scopes including the scopes defined for the APIs subscribed to the
 * application and the API-M REST API scopes set of the current tenant.
 *
 * @param consumerKey       Consumer Key of the application
 * @param authenticatedUser Authenticated User
 * @return Application Scope List
 */
public Map<String, String> getAppScopes(String consumerKey, AuthenticatedUser authenticatedUser) {

    //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application.
    Map<String, String> appScopes = null;
    String tenantDomain;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
    }
    try {
        appScopes = getApiMgtDAOInstance().getScopeRolesOfApplication(consumerKey);
        //Add API Manager rest API scopes set. This list should be loaded at server start up and keep
        //in memory and add it to each and every request coming.
        appScopes.putAll(APIUtil.getRESTAPIScopesForTenant(tenantDomain));
    } catch (APIManagementException e) {
        log.error("Error while getting scopes of application " + e.getMessage(), e);
    }
    return appScopes;
}
 
Example 4
Source File: IdentityProviderData.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String getTenantDomain() throws IdentityProviderException {
    if (this.authMechanism == IdentityConstants.AUTH_TYPE_SELF_ISSUED) { //only for tenant 0
        return null;
    }

    if (userIdentifier == null) {
        // auth type is not self issued and still the user identifier is null. 
        // this is a invalid case
        throw new IllegalStateException("User identifier must NOT be null");
    }

    String domain = null;
    domain = MultitenantUtils.getTenantDomain(userIdentifier);
    return domain;
}
 
Example 5
Source File: ApiProductsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override public Response apiProductsApiProductIdDelete(String apiProductId, String ifMatch,
        MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        APIProductIdentifier apiProductIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, tenantDomain);
        if (log.isDebugEnabled()) {
            log.debug("Delete API Product request: Id " +apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }

        List<SubscribedAPI> apiUsages = apiProvider.getAPIProductUsageByAPIProductId(apiProductIdentifier);
        if (apiUsages != null && apiUsages.size() > 0) {
            RestApiUtil.handleConflict("Cannot remove the API " + apiProductIdentifier + " as active subscriptions exist", log);
        }

        apiProvider.deleteAPIProduct(apiProduct.getId(), apiProductId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 6
Source File: MutualAuthHostObject.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the provided user name against user store
 * @param cx context
 * @param thisObj this object
 * @param args arguments
 * @return boolean
 * @throws Exception
 */
public static boolean jsFunction_validateUserNameHeader(Context cx, Scriptable thisObj,
                                                        Object[] args, Function funObj) throws Exception {

    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String) ) {
        throw new ScriptException("Invalid argument. User Name is not set properly");
    }

    boolean isValidUser = false;
    String userNameHeader = (String) args[0];

    try {

        String tenantDomain = MultitenantUtils.getTenantDomain(userNameHeader);
        String userName = MultitenantUtils.getTenantAwareUsername(userNameHeader);
        TenantManager tenantManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager();
        int tenantId = tenantManager.getTenantId(tenantDomain);

        UserStoreManager userstore = ServiceReferenceHolder.getInstance().getRealmService().
                getTenantUserRealm(tenantId).getUserStoreManager();

        if (userstore.isExistingUser(userName)) {
            isValidUser = true;
        }

    } catch (Exception e) {
        log.error("Error validating the user " + e.getMessage(), e);
        throw new ScriptException("Error validating the user " + userNameHeader);

    }

    return isValidUser;

}
 
Example 7
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the user's tenant and the API's tenant is equal. If it is not this will throw an
 * APIMgtAuthorizationFailedException
 *
 * @param apiIdentifier API Identifier
 * @throws APIMgtAuthorizationFailedException
 */
public static void validateUserTenantWithAPIIdentifier(APIIdentifier apiIdentifier)
        throws APIMgtAuthorizationFailedException {
    String username = RestApiUtil.getLoggedInUsername();
    String providerName = APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName());
    String providerTenantDomain = MultitenantUtils.getTenantDomain(providerName);
    String loggedInUserTenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    if (!providerTenantDomain.equals(loggedInUserTenantDomain)) {
        String errorMsg = "User " + username + " is not allowed to access " + apiIdentifier.toString()
                + " as it belongs to a different tenant : " + providerTenantDomain;
        throw new APIMgtAuthorizationFailedException(errorMsg);
    }
}
 
Example 8
Source File: RestApiAdminUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether given policy is allowed to access to user
 * 
 * @param user username with tenant domain
 * @param policy policy to check
 * @return true if user is allowed to access the policy
 */
public static boolean isPolicyAccessibleToUser(String user, Policy policy) {
    //This block checks whether policy's tenant domain and user's tenant domain are same
    String userTenantDomain = MultitenantUtils.getTenantDomain(user);
    if (!StringUtils.isBlank(policy.getTenantDomain())) {
        return policy.getTenantDomain().equals(userTenantDomain);
    } else {
        String tenantDomainFromId = APIUtil.getTenantDomainFromTenantId(policy.getTenantId());
        return !StringUtils.isBlank(tenantDomainFromId) && tenantDomainFromId.equals(userTenantDomain);
    }
}
 
Example 9
Source File: RecommenderDetailsExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public RecommenderDetailsExtractor(Application application, String userName, String requestedTenant) {

        this.publishingDetailType = APIConstants.UPDATED_APPLICATION;
        this.application = application;
        this.applicationId = application.getId();
        this.userName = userName;
        this.tenantDomain = MultitenantUtils.getTenantDomain(userName);
        this.requestTenantDomain = requestedTenant;
    }
 
Example 10
Source File: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create a tenant upon initial server startup
 */
public static void initializeTenant(String username) throws Exception {
    TenantInfoBean tenantInfoBean = new TenantInfoBean();
    TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService();
    char[] password = MicroGatewayCommonUtil.getRandomString(20).toCharArray();
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        if (CommonUtil.isDomainNameAvailable(tenantDomain)) {
            tenantInfoBean.setActive(true);
            tenantInfoBean.setAdmin(tenantAwareUsername);
            tenantInfoBean.setAdminPassword(password.toString());
            tenantInfoBean.setFirstname(TenantInitializationConstants.DEFAULT_FIRST_NAME);
            tenantInfoBean.setLastname(TenantInitializationConstants.DEFAULT_LAST_NAME);
            tenantInfoBean.setTenantDomain(tenantDomain);
            tenantInfoBean.setEmail(TenantInitializationConstants.DEFAULT_EMAIL);
            try {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);

                tenantMgtAdminService.addTenant(tenantInfoBean);
                tenantMgtAdminService.activateTenant(tenantDomain);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
            MicroGatewayCommonUtil.cleanPasswordCharArray(password);
            log.info("Successfully initialized tenant with tenant domain: " + tenantDomain);
        } else {
            log.info("Tenant with tenant domain " + tenantDomain + " already exists.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping initializing super tenant space since execution is currently in super tenant flow.");
        }
    }
}
 
Example 11
Source File: AbstractJWTGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public byte[] signJWT(String assertion, String endUserName) throws APIManagementException {

        String tenantDomain = null;

        try {
            //get tenant domain
            tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
            Key privateKey = CertificateMgtUtils.getInstance().getPrivateKey(tenantDomain);
            return APIUtil.signJwt(assertion, (PrivateKey) privateKey, signatureAlgorithm);
        } catch (RegistryException e) {
            String error = "Error in loading tenant registry for " + tenantDomain;
            //do not log
            throw new APIManagementException(error, e);
        }
    }
 
Example 12
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 13
Source File: RestApiAdminUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether given policy is allowed to access to user
 *
 * @param user   username with tenant domain
 * @param policy policy to check
 * @return true if user is allowed to access the policy
 */
public static boolean isPolicyAccessibleToUser(String user, Policy policy) {
    //This block checks whether policy's tenant domain and user's tenant domain are same
    String userTenantDomain = MultitenantUtils.getTenantDomain(user);
    if (!StringUtils.isBlank(policy.getTenantDomain())) {
        return policy.getTenantDomain().equals(userTenantDomain);
    } else {
        String tenantDomainFromId = APIUtil.getTenantDomainFromTenantId(policy.getTenantId());
        return !StringUtils.isBlank(tenantDomainFromId) && tenantDomainFromId.equals(userTenantDomain);
    }
}
 
Example 14
Source File: APITemplateBuilderImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private ConfigContext createConfigContext(API api, Environment environment)
        throws UserStoreException, RegistryException {
    ConfigContext configcontext = new APIConfigContext(api);
    configcontext = new TransportConfigContext(configcontext, api);
    configcontext = new ResourceConfigContext(configcontext, api);
    // this should be initialised before endpoint config context.
    configcontext = new EndpointBckConfigContext(configcontext, api);
    configcontext = new EndpointConfigContext(configcontext, api);
    configcontext = new SecurityConfigContext(configcontext, api);
    configcontext = new JwtConfigContext(configcontext);
    configcontext = new ResponseCacheConfigContext(configcontext, api);
    configcontext = new BAMMediatorConfigContext(configcontext);
    configcontext = new HandlerConfigContex(configcontext, handlers);
    configcontext = new EnvironmentConfigContext(configcontext, environment);
    configcontext = new TemplateUtilContext(configcontext);

    if (APIConstants.API_TYPE_SOAPTOREST.equals(api.getType()) || !StringUtils.isEmpty(api.getWsdlUrl())) {
        RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
        String resourceInPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
                api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName()
                + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR
                + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_IN_RESOURCE;
        String resourceOutPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
                api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName()
                + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR
                + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_OUT_RESOURCE;
        UserRegistry registry = registryService.getGovernanceSystemRegistry(tenantId);
        configcontext = SequenceUtils.getSequenceTemplateConfigContext(registry, resourceInPath,
                SOAPToRESTConstants.Template.IN_SEQUENCES, configcontext);
        configcontext = SequenceUtils.getSequenceTemplateConfigContext(registry, resourceOutPath,
                SOAPToRESTConstants.Template.OUT_SEQUENCES, configcontext);
    }

    return configcontext;
}
 
Example 15
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
protected String getTenantDomain(Identifier identifier) {
    return MultitenantUtils.getTenantDomain(
            APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
}
 
Example 16
Source File: AccessTokenGrantHandler.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    if (!super.validateGrant(tokReqMsgCtx)) {
        return false;
    } else {
        OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
        String username = null;
        String userTenantDomain = null;
        String clientId = oAuth2AccessTokenReqDTO.getClientId();
        String spTenantDomain = null;
        OAuthValidationResponse response;
        ServiceProvider serviceProvider;
        boolean authStatus = false;

        String accessToken = null;
        RequestParameter[] parameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();

        for (RequestParameter parameter : parameters) {
            if (TOKEN_GRANT_PARAM.equals(parameter.getKey())) {
                if (parameter.getValue() != null && parameter.getValue().length > 0) {
                    accessToken = parameter.getValue()[0];
                }
            }
        }

        if (accessToken != null && !accessToken.isEmpty()) {
            try {
                response = tokenValidator.validateToken(accessToken);
            } catch (RemoteException e) {
                log.error("Failed to validate the OAuth token provided.", e);
                return false;
            }
            if (response != null && response.isValid()) {
                authStatus = true;
                username = response.getUserName() + "@" + response.getTenantDomain();
                userTenantDomain = MultitenantUtils.getTenantDomain(username);
                spTenantDomain = response.getTenantDomain();
            } else if (response != null && !response.isValid()) {
                throw new IdentityOAuth2Exception("Authentication failed for the provided access token");
            }
        }

        try {
            serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService()
                    .getServiceProviderByClientId(clientId, "oauth2", spTenantDomain);
        } catch (IdentityApplicationManagementException var15) {
            throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data for client id "
                    + clientId, var15);
        }

        if (!serviceProvider.isSaasApp() && !userTenantDomain.equals(spTenantDomain)) {
            if (log.isDebugEnabled()) {
                log.debug("Non-SaaS service provider tenant domain is not same as user tenant domain; "
                        + spTenantDomain + " != " + userTenantDomain);
            }

            return false;
        } else {
            String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
            username = tenantAwareUserName + "@" + userTenantDomain;
            if (authStatus) {
                if (!username.contains("/") && StringUtils.isNotBlank(UserCoreUtil.getDomainFromThreadLocal())) {
                    username = UserCoreUtil.getDomainFromThreadLocal() + "/" + username;
                }

                AuthenticatedUser user = OAuth2Util.getUserFromUserName(username);
                user.setAuthenticatedSubjectIdentifier(user.toString());
                tokReqMsgCtx.setAuthorizedUser(user);
                tokReqMsgCtx.setScope(oAuth2AccessTokenReqDTO.getScope());
                return authStatus;
            } else {
                throw new IdentityOAuth2Exception("Authentication failed for " + username);
            }
        }
    }
}
 
Example 17
Source File: APIProductImportUtil.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method imports dependent APIs of the API Product.
 *
 * @param path                     Location of the extracted folder of the API Product
 * @param currentUser              The current logged in user
 * @param isDefaultProviderAllowed Decision to keep or replace the provider
 * @param apiProvider              API provider
 * @param overwriteAPIs            Whether to overwrite the APIs or not
 * @param apiProduct               API Product
 * @throws IOException If there is an error while reading an API file
 * @throws APIImportExportException If there is an error in importing an API
 * @throws APIManagementException If failed to get the API Provider of an API, or failed when checking the existence of an API
 */
private static void importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed,
                                        APIProvider apiProvider, Boolean overwriteAPIs, APIProduct apiProduct)
        throws APIImportExportException, IOException, APIManagementException {

    List<APIProductResource> apiProductResources = apiProduct.getProductResources();

    String apisDirectoryPath = path + File.separator + APIImportExportConstants.APIS_DIRECTORY;
    File apisDirectory = new File(apisDirectoryPath);
    File[] apisDirectoryListing = apisDirectory.listFiles();
    if (apisDirectoryListing != null) {
        for (File api : apisDirectoryListing) {
            String apiDirectoryPath = path + File.separator + APIImportExportConstants.APIS_DIRECTORY + File.separator + api.getName();
            // Get API Definition as JSON
            String jsonContent = APIAndAPIProductCommonUtil.getAPIDefinitionAsJson(apiDirectoryPath);
            if (jsonContent == null) {
                throw new IOException("Cannot find API definition. api.json or api.yaml should present");
            }
            JsonElement configElement = new JsonParser().parse(jsonContent);
            JsonObject configObject = configElement.getAsJsonObject();

            // Locate the "providerName", "apiName" and "apiVersion" within the "id"
            JsonObject apiId = configObject.getAsJsonObject(APIImportExportConstants.ID_ELEMENT);

            String provider = apiId.get(APIImportExportConstants.PROVIDER_ELEMENT).getAsString();
            String apiName = apiId.get(APIImportExportConstants.API_NAME_ELEMENT).getAsString();
            String apiVersion = apiId.get(APIImportExportConstants.VERSION_ELEMENT).getAsString();

            if (isDefaultProviderAllowed) {
                APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName,
                        apiVersion);

                // Checking whether the API exists
                if (apiProvider.isAPIAvailable(apiIdentifier)) {
                    // If the API is already imported, update it if the overWriteAPIs flag is specified,
                    // otherwise do not import/update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        APIImportUtil.importAPI(apiDirectoryPath, currentUser, true, apiProvider, true);
                    }
                } else {
                    // If the API is not already imported, import it
                    APIImportUtil.importAPI(apiDirectoryPath, currentUser, true, apiProvider, false);
                }
            } else {
                // Retrieve the current tenant domain of the logged in user
                String currentTenantDomain = MultitenantUtils
                        .getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser));

                // Get the provider of the API if the API is in current user's tenant domain.
                String apiProviderInCurrentTenantDomain = APIUtil
                        .getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain);

                if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) {
                    // If there is no API in the current tenant domain (which means the provider name is blank)
                    // then the API should be imported freshly
                    APIImportUtil.importAPI(apiDirectoryPath, currentUser, false, apiProvider, false);
                    // Update the provider name of the resources of this API in the current product resources with the current user's name
                    updateProviderNameInProductResources(apiName, apiVersion, apiProductResources, currentUser);
                } else {
                    // If there is an API already in the current tenant domain, update it if the overWriteAPIs flag is specified,
                    // otherwise do not import/update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        APIImportUtil.importAPI(apiDirectoryPath, currentUser, false, apiProvider, true);
                    }
                    // Update the provider name of the resources of this API in the current product resources
                    // with the user's name who is the provider of this API
                    updateProviderNameInProductResources(apiName, apiVersion, apiProductResources, apiProviderInCurrentTenantDomain);
                }
            }
        }
    } else {
        String msg = "No dependent APIs supplied. Continuing ...";
        log.info(msg);
    }
}
 
Example 18
Source File: UserIdentityMgtBean.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public String getTenantDomain() {
    if (tenantDomain == null) {
        tenantDomain = MultitenantUtils.getTenantDomain(userId);
    }
    return tenantDomain;
}
 
Example 19
Source File: OIDCAuthenticator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Login method
 *
 * @param code  code value
 * @param nonce nonce value
 * @return user name of authenticated user
 */
public String login(String code, String nonce) {

    String userName;

    try {

        HttpSession httpSession = getHttpSession();
        RealmService realmService = OIDCAuthBEDataHolder.getInstance().getRealmService();
        RegistryService registryService = OIDCAuthBEDataHolder.getInstance().getRegistryService();

        ServerConfiguration serverConfiguration = getServerConfiguration();
        AuthClient authClient = getClientConfiguration();
        String jsonResponse = getTokenFromTokenEP(serverConfiguration, authClient, code);
        AuthenticationToken oidcAuthenticationToken = getAuthenticationToken(jsonResponse);
        userName = getUserName(oidcAuthenticationToken, serverConfiguration);

        if (userName == null || userName.equals("")) {
            log.error("Authentication Request is rejected. "
                    + "User Name is Null");
            return null;
        }

        String tenantDomain = MultitenantUtils.getTenantDomain(userName);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);


        // Start Authentication
        handleAuthenticationStarted(tenantId);
        if (isResponseSignatureValidationEnabled()) {

            boolean isSignatureValid = validateSignature(serverConfiguration, authClient,
                    oidcAuthenticationToken, nonce);

            if (!isSignatureValid) {
                log.error("Authentication Request is rejected. "
                        + " Signature validation failed.");
                CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, userName, tenantId,
                        "OIDC Authentication",
                        "Invalid Signature");
                handleAuthenticationCompleted(tenantId, false);
                return null;
            }
        }

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

        // Starting Authorization
        PermissionUpdateUtil.updatePermissionTree(tenantId);
        boolean isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName,
                "/permission/admin/login", CarbonConstants.UI_PERMISSION_ACTION);
        if (isAuthorized) {
            CarbonAuthenticationUtil.onSuccessAdminLogin(httpSession, userName,
                    tenantId, tenantDomain, "OIDC Authentication");
            handleAuthenticationCompleted(tenantId, true);
        } else {
            log.error("Authentication Request is rejected. Authorization Failure.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, userName, tenantId,
                    "OIDC Authentication", "Invalid credential");
            handleAuthenticationCompleted(tenantId, false);
            return null;
        }
    } catch (Exception e) {
        String msg = "System error while Authenticating/Authorizing User : " + e.getMessage();
        log.error(msg, e);
        return null;
    }

    return userName;
}
 
Example 20
Source File: RestApiAdminUtils.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
 * Checks whether given block condition is allowed to access to user
 *
 * @param user           username with tenant domain
 * @param blockCondition Block condition to check
 * @return true if user is allowed to access the block condition
 */
public static boolean isBlockConditionAccessibleToUser(String user, BlockConditionsDTO blockCondition) {
    String userTenantDomain = MultitenantUtils.getTenantDomain(user);
    return !StringUtils.isBlank(blockCondition.getTenantDomain()) && blockCondition.getTenantDomain()
            .equals(userTenantDomain);
}