Java Code Examples for org.wso2.carbon.base.MultitenantConstants#SUPER_TENANT_ID

The following examples show how to use org.wso2.carbon.base.MultitenantConstants#SUPER_TENANT_ID . 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: DefaultClaimsRetriever.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getDefaultClaims(String endUserName) throws IdentityOAuth2Exception {

    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    try {
        tenantId = OAuth2Util.getTenantIdFromUserName(endUserName);
        // if no claims were requested, return all
        if(log.isDebugEnabled()){
            log.debug("No claims set requested. Returning all claims in the dialect");
        }
        ClaimManager claimManager =
                OAuthComponentServiceHolder.getRealmService().getTenantUserRealm(tenantId).getClaimManager();
        ClaimMapping[] claims = claimManager.getAllClaimMappings(dialectURI);
        return claimToString(claims);
    } catch (UserStoreException e) {
        throw new IdentityOAuth2Exception("Error while reading default claims for user : " + endUserName, e);
    }
}
 
Example 2
Source File: SAMLSSOConfigService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @return
 * @throws IdentityException
 */
public String[] getCertAliasOfPrimaryKeyStore() throws IdentityException {
    KeyStoreData[] keyStores = getKeyStores();
    KeyStoreData primaryKeyStore = null;
    for (int i = 0; i < keyStores.length; i++) {
        boolean superTenant = MultitenantConstants.SUPER_TENANT_ID == CarbonContext
                .getThreadLocalCarbonContext().getTenantId() ? true : false;
        if (superTenant && KeyStoreUtil.isPrimaryStore(keyStores[i].getKeyStoreName())) {
            primaryKeyStore = keyStores[i];
            break;
        } else if (!superTenant
                && SAMLSSOUtil.generateKSNameFromDomainName(getTenantDomain()).equals(
                keyStores[i].getKeyStoreName())) {
            primaryKeyStore = keyStores[i];
            break;
        }
    }
    if (primaryKeyStore != null) {
        return getStoreEntries(primaryKeyStore.getKeyStoreName());
    }
    throw IdentityException.error("Primary Keystore cannot be found.");
}
 
Example 3
Source File: DeviceManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * returns the tenant Id of the specific tenant Domain
 *
 * @param tenantDomain
 * @return
 * @throws DeviceManagementException
 */
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
    try {
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            return MultitenantConstants.SUPER_TENANT_ID;
        }
        TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
        int tenantId = tenantManager.getTenantId(tenantDomain);
        if (tenantId == -1) {
            throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain);
        }
        return tenantId;
    } catch (UserStoreException e) {
        throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain);
    }
}
 
Example 4
Source File: APIManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * returns the tenant Id of the specific tenant Domain
 */
public static int getTenantId(String tenantDomain) throws APIManagerException {
    try {
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            return MultitenantConstants.SUPER_TENANT_ID;
        }
        TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager();
        int tenantId = tenantManager.getTenantId(tenantDomain);
        if (tenantId == -1) {
            throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
        }
        return tenantId;
    } catch (UserStoreException e) {
        throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
    }
}
 
Example 5
Source File: AuthenticationServiceImpl.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: CertificateManagerImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean deleteCertificateFromGateway(String alias) {
    // Check whether the api is invoked via the APIGatewayAdmin service.
    int loggedInTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (loggedInTenantId != MultitenantConstants.SUPER_TENANT_ID) {
        alias = alias + "_" + loggedInTenantId;
    }
    return deleteCertificateFromListenerAndSenderProfiles(alias, false);
}
 
Example 7
Source File: CertificateManagerImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addCertificateToGateway(String certificate, String alias) {
    // Check whether the api is invoked via the APIGatewayAdmin service.
    int loggedInTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (loggedInTenantId != MultitenantConstants.SUPER_TENANT_ID) {
        alias = alias + "_" + loggedInTenantId;
    }
    return addCertificateToListenerOrSenderProfile(certificate, alias, false);
}
 
Example 8
Source File: RemoteTaskUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private static String getTenantSectionInURL(int tenantId) {
    if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
        return "";
    } else {
        return "/t/" + getTenantDomainFromId(tenantId);
    }
}
 
Example 9
Source File: KeyStoreAdminServiceImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public KeyStoreData[] getKeyStores() throws SecurityConfigException {
    KeyStoreAdmin admin = new KeyStoreAdmin(CarbonContext.getThreadLocalCarbonContext().getTenantId(),
            getGovernanceSystemRegistry());
    boolean isSuperTenant = CarbonContext.getThreadLocalCarbonContext().getTenantId() ==
            MultitenantConstants.SUPER_TENANT_ID;
    return admin.getKeyStores(isSuperTenant);
}
 
Example 10
Source File: Util.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * This method validates the signature of the SAML Response.
 * @param resp SAML Response
 * @return true, if signature is valid.
 */
public static boolean validateSignature(Response resp, String keyStoreName,
                                        String keyStorePassword, String alias, int tenantId,
                                        String tenantDomain) {
    boolean isSigValid = false;
    try {
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        if(log.isDebugEnabled()){
            log.debug("Validating against "+cert.getSubjectDN().getName());
        }
        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(resp.getSignature());
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        if (log.isDebugEnabled()){
        log.debug("Signature verification is failed for "+tenantDomain);
        }
        return isSigValid;
    }
}
 
Example 11
Source File: STSAdminServiceImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getCertAliasOfPrimaryKeyStore() throws SecurityConfigException {

    KeyStoreData[] keyStores = getKeyStores();
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    KeyStoreData primaryKeystore = null;
    for (KeyStoreData keyStore : keyStores) {
        if (keyStore != null) {
            if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
                if (KeyStoreUtil.isPrimaryStore(keyStore.getKeyStoreName())) {
                    primaryKeystore = keyStore;
                    break;
                }
            } else {
                if (keyStore.getPrivateStore()) {
                    primaryKeystore = keyStore;
                    break;
                }
            }
        }
    }

    if (primaryKeystore != null) {
        return getStoreEntries(primaryKeystore.getKeyStoreName());
    }

    throw new SecurityConfigException("Primary Keystore cannot be found.");
}
 
Example 12
Source File: TenantManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private TenantManager() {
    this.tenantIdTenantMap = new HashMap<Integer, Tenant>();
    this.tenantDomainTenantMap = new HashMap<String, Tenant>();
    Tenant superTenant = new Tenant(MultitenantConstants.SUPER_TENANT_ID,
            MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    this.tenantIdTenantMap.put(MultitenantConstants.SUPER_TENANT_ID, superTenant);
    this.tenantDomainTenantMap.put(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, superTenant);
}
 
Example 13
Source File: DeviceManagementAdminServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Override
@GET
public Response getDevicesByName(@QueryParam("name") @Size(max = 45) String name,
                                 @QueryParam("type") @Size(min = 2, max = 45) String type,
                                 @QueryParam("tenant-domain") String tenantDomain,
                                 @HeaderParam("If-Modified-Since") String ifModifiedSince,
                                 @QueryParam("offset") int offset,
                                 @QueryParam("limit") int limit) {
    RequestValidationUtil.validatePaginationParameters(offset, limit);
    int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
        return Response.status(Response.Status.UNAUTHORIZED).entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(
                        "Current logged in user is not authorized to perform this operation").build()).build();
    }
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain));

        PaginationRequest request = new PaginationRequest(offset, limit);
        request.setDeviceType(type);
        request.setDeviceName(name);
        List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().
                getDevicesByNameAndType(request, false);

        // setting up paginated result
        DeviceList deviceList = new DeviceList();
        deviceList.setList(devices);
        deviceList.setCount(devices.size());

        return Response.status(Response.Status.OK).entity(deviceList).build();
    } catch (DeviceManagementException e) {
        String msg = "Error occurred at server side while fetching device list.";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 14
Source File: DeviceAccessAuthorizationAdminServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@POST
@Override
public Response isAuthorized(AuthorizationRequest authorizationRequest) {
    int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String loggedinUserTenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (authorizationRequest.getTenantDomain() != null) {
        if (!loggedinUserTenantDomain.equals(authorizationRequest.getTenantDomain())) {
            if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
                return Response.status(Response.Status.UNAUTHORIZED).entity(
                        new ErrorResponse.ErrorResponseBuilder().setMessage(
                                "Current logged in user is not authorized to perform this operation").build())
                        .build();
            }
        }
    } else {
        authorizationRequest.setTenantDomain(loggedinUserTenantDomain);
    }
    if (authorizationRequest.getTenantDomain() == null || authorizationRequest.getTenantDomain().isEmpty()) {
        authorizationRequest.setTenantDomain(
                PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    }
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                authorizationRequest.getTenantDomain(), true);
        String[] permissionArr = null;
        if (authorizationRequest.getPermissions() != null && authorizationRequest.getPermissions().size() > 0) {
            permissionArr = new String[authorizationRequest.getPermissions().size()];
            permissionArr = authorizationRequest.getPermissions().toArray(permissionArr);
        }
        DeviceAuthorizationResult deviceAuthorizationResult =
                DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
                        authorizationRequest.getDeviceIdentifiers(), authorizationRequest.getUsername()
                        , permissionArr);

        return Response.status(Response.Status.OK).entity(deviceAuthorizationResult).build();
    } catch (DeviceAccessAuthorizationException e) {
        String msg = "Error occurred at server side while fetching authorization information.";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 15
Source File: DeviceManagementAdminServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Override
@GET
public Response getDevicesByName(@QueryParam("name") @Size(max = 45) String name,
                                 @QueryParam("type") @Size(min = 2, max = 45) String type,
                                 @QueryParam("tenant-domain") String tenantDomain,
                                 @HeaderParam("If-Modified-Since") String ifModifiedSince,
                                 @QueryParam("offset") int offset,
                                 @QueryParam("limit") int limit) {
    RequestValidationUtil.validatePaginationParameters(offset, limit);
    int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
        return Response.status(Response.Status.UNAUTHORIZED).entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(
                        "Current logged in user is not authorized to perform this operation").build()).build();
    }
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain));

        PaginationRequest request = new PaginationRequest(offset, limit);
        request.setDeviceType(type);
        request.setDeviceName(name);
        List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().
                getDevicesByNameAndType(request, false);

        // setting up paginated result
        DeviceList deviceList = new DeviceList();
        deviceList.setList(devices);
        deviceList.setCount(devices.size());

        return Response.status(Response.Status.OK).entity(deviceList).build();
    } catch (DeviceManagementException e) {
        String msg = "Error occurred at server side while fetching device list.";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 16
Source File: DeviceAccessAuthorizationAdminServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@POST
@Override
public Response isAuthorized(AuthorizationRequest authorizationRequest) {
    int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String loggedinUserTenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (authorizationRequest.getTenantDomain() != null) {
        if (!loggedinUserTenantDomain.equals(authorizationRequest.getTenantDomain())) {
            if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
                return Response.status(Response.Status.UNAUTHORIZED).entity(
                        new ErrorResponse.ErrorResponseBuilder().setMessage(
                                "Current logged in user is not authorized to perform this operation").build())
                        .build();
            }
        }
    } else {
        authorizationRequest.setTenantDomain(loggedinUserTenantDomain);
    }
    if (authorizationRequest.getTenantDomain() == null || authorizationRequest.getTenantDomain().isEmpty()) {
        authorizationRequest.setTenantDomain(
                PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    }
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                authorizationRequest.getTenantDomain(), true);
        String[] permissionArr = null;
        if (authorizationRequest.getPermissions() != null && authorizationRequest.getPermissions().size() > 0) {
            permissionArr = new String[authorizationRequest.getPermissions().size()];
            permissionArr = authorizationRequest.getPermissions().toArray(permissionArr);
        }
        DeviceAuthorizationResult deviceAuthorizationResult =
                DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
                        authorizationRequest.getDeviceIdentifiers(), authorizationRequest.getUsername()
                        , permissionArr);

        return Response.status(Response.Status.OK).entity(deviceAuthorizationResult).build();
    } catch (DeviceAccessAuthorizationException e) {
        String msg = "Error occurred at server side while fetching authorization information.";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 17
Source File: Util.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
static boolean isSuperTenant() {
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    return tenantId == MultitenantConstants.SUPER_TENANT_ID;
}
 
Example 18
Source File: TestTenantManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public Tenant[] getAllTenants() throws UserStoreException {
    return new Tenant[MultitenantConstants.SUPER_TENANT_ID];
}
 
Example 19
Source File: TestTenantManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public int getTenantId(String s) throws UserStoreException {
    return MultitenantConstants.SUPER_TENANT_ID;
}
 
Example 20
Source File: KeyStoreManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 2 votes vote down vote up
private boolean isSuperTenant(String tenantDomain) {

        return IdentityTenantUtil.getTenantId(tenantDomain) == MultitenantConstants.SUPER_TENANT_ID;
    }