Java Code Examples for org.wso2.carbon.context.PrivilegedCarbonContext#setTenantId()

The following examples show how to use org.wso2.carbon.context.PrivilegedCarbonContext#setTenantId() . 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: BaseCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a cache entry.
 *
 * @param key CacheKey
 * @return Cached entry.
 */
public V getValueFromCache(K key) {

    if (!isEnabled()) {
        return null;
    }

    if (key == null) {
        return null;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null && cache.get(key) != null) {
            return (V) cache.get(key);
        }
        return null;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 2
Source File: EntitlementEngineCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public EntitlementEngine get(int key) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        EntitlementEngine entitlementEngine = getEntitlementCache().get(key);
        if (entitlementEngine != null) {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is HIT " +
                        "for tenantId : " + key);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is MISSED " +
                        "for tenantId : " + key);
            }
        }
        return entitlementEngine;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 3
Source File: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private static void clearMetadata(String applicationId) throws RestAPIException {

        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        String resourcePath = METADATA_REG_PATH + applicationId;
        Registry registry = (UserRegistry) PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getRegistry(RegistryType.SYSTEM_GOVERNANCE);
        try {
            registry.beginTransaction();
            if (registry.resourceExists(resourcePath)) {
                registry.delete(resourcePath);
                log.info(String.format("Application metadata removed: [application-id] %s", applicationId));
            }
            registry.commitTransaction();
        } catch (RegistryException e) {
            try {
                registry.rollbackTransaction();
            } catch (RegistryException e1) {
                log.error("Could not rollback transaction", e1);
            }
            throw new RestAPIException(
                    String.format("Application metadata removed: [application-id] %s", applicationId), e);
        }
    }
 
Example 4
Source File: BaseCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(K key, V entry) {
    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        // Element already in the cache. Remove it first
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.put(key, entry);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 5
Source File: EntitlementEngineCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public boolean contains(int key) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        boolean contain = getEntitlementCache().containsKey(key);
        if (contain) {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is HIT " +
                        "for tenantId : " + key);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is MISSED " +
                        "for tenantId : " + key);
            }
        }
        return contain;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 6
Source File: BaseCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a cache entry.
 *
 * @param key CacheKey
 * @return Cached entry.
 */
public V getValueFromCache(K key) {
    if (!isEnabled()) {
        return null;
    }

    if(key == null) {
        return null;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null && cache.get(key) != null) {
            return (V) cache.get(key);
        }
        return null;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 7
Source File: ServiceUtils.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
private static PrivilegedCarbonContext setTenantInfomationToPrivilegedCC(String tenantDomain, int tenantId,
        String username) {

    // setting the correct tenant info for downstream code..
    PrivilegedCarbonContext privilegedCC = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    privilegedCC.setTenantDomain(tenantDomain);
    privilegedCC.setTenantId(tenantId);
    privilegedCC.setUsername(username);

    return privilegedCC;
}
 
Example 8
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

    try {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        registry.beginTransaction();
        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(serializableObject));
        registry.put(resourcePath, nodeResource);
        registry.commitTransaction();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
       try {
           registry.rollbackTransaction();
       }catch (Exception e1){
           if (log.isErrorEnabled()) {
               log.error("Could not rollback transaction", e1);
           }
       }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 9
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

    try {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        registry.beginTransaction();
        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(serializableObject));
        registry.put(resourcePath, nodeResource);
        registry.commitTransaction();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (Exception e1){
            if (log.isErrorEnabled()) {
                log.error("Could not rollback transaction", e1);
            }
        }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 10
Source File: UserMgtInitializer.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void start(BundleContext bc, RegistryService registryService) throws Exception {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

    addPermissions(registryService);
}
 
Example 11
Source File: WebappAuthenticationValve.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {

    if (this.isContextSkipped(request) ||  this.skipAuthentication(request)) {
        this.getNext().invoke(request, response, compositeValve);
        return;
    }

    WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request);
    if (authenticator == null) {
        String msg = "Failed to load an appropriate authenticator to authenticate the request";
        AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
        return;
    }
    AuthenticationInfo authenticationInfo = authenticator.authenticate(request, response);
    if (isManagedAPI(request) && (authenticationInfo.getStatus() == WebappAuthenticator.Status.CONTINUE ||
            authenticationInfo.getStatus() == WebappAuthenticator.Status.SUCCESS)) {
        WebappAuthenticator.Status status = WebappTenantAuthorizer.authorize(request, authenticationInfo);
        authenticationInfo.setStatus(status);
    }
    if (authenticationInfo.getTenantId() != -1) {
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            privilegedCarbonContext.setTenantId(authenticationInfo.getTenantId());
            privilegedCarbonContext.setTenantDomain(authenticationInfo.getTenantDomain());
            privilegedCarbonContext.setUsername(authenticationInfo.getUsername());
            this.processRequest(request, response, compositeValve, authenticationInfo);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    } else {
        this.processRequest(request, response, compositeValve, authenticationInfo);
    }
}
 
Example 12
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private List<Property> getRegistryResourceProperties(String registryResourcePath, String applicationId)
        throws RegistryException, MetadataException {
    Registry tempRegistry = getRegistry();
    if (!tempRegistry.resourceExists(registryResourcePath)) {
        return null;
    }

    // We are using only super tenant registry to persist
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

    Resource regResource = tempRegistry.get(registryResourcePath);
    ArrayList<Property> newProperties = new ArrayList<>();
    Properties props = regResource.getProperties();
    Enumeration<?> x = props.propertyNames();
    while (x.hasMoreElements()) {
        String key = (String) x.nextElement();
        List<String> values = regResource.getPropertyValues(key);
        Property property = new Property();
        property.setKey(key);
        String[] valueArr = new String[values.size()];
        property.setValues(values.toArray(valueArr));

        newProperties.add(property);
    }
    return newProperties;
}
 
Example 13
Source File: PolicyPublishExecutor.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void run() {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(tenantDomain);
        context.setTenantId(tenantId);
        context.setUsername(userName);
        try {
            publish();
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

    }
 
Example 14
Source File: ProxyTimerTask.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public void run() {

        synchronized (axisConfig) {
            PrivilegedCarbonContext.startTenantFlow();
            try {
                PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                privilegedCarbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                privilegedCarbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

                AxisServiceGroup proxyAxisServiceGroup =
                        axisConfig.getServiceGroup(WSDL2FormGenerator.TRYIT_SG_NAME);
                if (proxyAxisServiceGroup != null) {
                    List removeServiceList = new ArrayList();
                    for (Iterator iterator = proxyAxisServiceGroup.getServices();
                         iterator.hasNext();) {
                        AxisService axisServce = (AxisService) iterator.next();
                        Long longTime =
                                (Long) axisServce
                                        .getParameterValue(WSDL2FormGenerator.LAST_TOUCH_TIME);
                        if ((System.currentTimeMillis() - longTime.longValue()) > WSDL2FormGenerator
                                .PERIOD) {
                            removeServiceList.add(axisServce.getName());
                        }

                    }
                    if (removeServiceList.size() > 0) {
                        for (Iterator iterator = removeServiceList.iterator(); iterator.hasNext();)
                        {
                            String axisServiceName = (String) iterator.next();
                            proxyAxisServiceGroup.removeService(axisServiceName);
                        }
                    }
                    boolean isLast = proxyAxisServiceGroup.getServices().hasNext();
                    if (!isLast) {
                        axisConfig.removeServiceGroup(WSDL2FormGenerator.TRYIT_SG_NAME);
                    }
                }
            } catch (AxisFault axisFault) {
                String msg = "Fault occured when manipulating Tryit proxy service group";
                log.error(msg, axisFault);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }

        }
    }
 
Example 15
Source File: OAuthHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public boolean isAuthenticated(Message message, ClassResourceInfo classResourceInfo) {
    // get the map of protocol headers
    Map protocolHeaders = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
    // get the value for Authorization Header
    List authzHeaders = (ArrayList) protocolHeaders
            .get(SCIMConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);

        // extract access token
        String accessToken = authzHeader.trim().substring(7).trim();
        // validate access token
        try {
            OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken);
            OAuth2TokenValidationResponseDTO validationResponse = null;

            if (validationApp != null) {
                validationResponse = validationApp.getAccessTokenValidationResponse();
            }

            if (validationResponse != null && validationResponse.isValid()) {
                String userName = validationResponse.getAuthorizedUser();
                authzHeaders.set(0, userName);

                // setup thread local variable to be consumed by the provisioning framework.
                RealmService realmService = (RealmService) PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getOSGiService(RealmService.class);
                ThreadLocalProvisioningServiceProvider serviceProvider = new ThreadLocalProvisioningServiceProvider();
                serviceProvider.setServiceProviderName(validationApp.getConsumerKey());
                serviceProvider
                        .setServiceProviderType(ProvisioningServiceProviderType.OAUTH);
                serviceProvider.setClaimDialect(SCIMProviderConstants.DEFAULT_SCIM_DIALECT);
                serviceProvider.setTenantDomain(MultitenantUtils.getTenantDomain(userName));
                IdentityApplicationManagementUtil
                        .setThreadLocalProvisioningServiceProvider(serviceProvider);
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                String tenantDomain = MultitenantUtils.getTenantDomain(userName);
                carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(userName));
                carbonContext.setTenantId(realmService.getTenantManager().getTenantId(tenantDomain));
                carbonContext.setTenantDomain(tenantDomain);
                return true;
            }
        } catch (Exception e) {
            String error = "Error in validating OAuth access token.";
            log.error(error, e);
        }
    }
    return false;
}
 
Example 16
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public boolean removePropertyFromApplication(String applicationId, String propertyKey)
        throws RegistryException, MetadataException {
    Registry registry = getRegistry();
    String resourcePath = mainResource + applicationId;
    Resource nodeResource;

    try {
        acquireWriteLock(applicationId);
        // We are using only super tenant registry to persist
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        if (registry.resourceExists(resourcePath)) {
            nodeResource = registry.get(resourcePath);
            if (nodeResource.getProperty(propertyKey) == null) {
                log.info(String.format("Registry property not found: [application-id] %s [key] %s ", applicationId,
                        propertyKey));
                return false;
            } else {
                nodeResource.removeProperty(propertyKey);
                registry.put(resourcePath, nodeResource);
            }
        } else {
            log.error("Registry resource not not found at " + resourcePath);
            return false;
        }

        log.info(String.format("Registry property removed: [application-id] %s, [key] %s", applicationId,
                propertyKey));
        return true;
    } catch (Exception e) {
        throw new MetadataException(
                String.format("Could not remove registry resource: [resource-path] %s, [key] %s", resourcePath,
                        propertyKey), e);
    } finally {
        try {
            releaseWriteLock(applicationId);
        } catch (MetadataException ignored) {
        }
    }
}
 
Example 17
Source File: AbstractProvisioningConnectorFactory.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param identityProviderName
 * @param provisoningProperties
 * @param tenantDomain
 * @return
 * @throws IdentityProvisioningException
 */
public AbstractOutboundProvisioningConnector getConnector(String identityProviderName,
                                                          Property[] provisoningProperties, String tenantDomain)
        throws IdentityProvisioningException {

    String tenantDomainName = null;
    int tenantId = -1234;

    if (CarbonContext.getThreadLocalCarbonContext() != null) {
        tenantDomainName = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    }

    try {
        // maintain the provisioning connector cache in the super tenant.
        // at the time of provisioning there may not be an authenticated user in the system -
        // specially in the case of in-bound provisioning.
        PrivilegedCarbonContext.startTenantFlow();

        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        ProvisioningConnectorCacheKey cacheKey = new ProvisioningConnectorCacheKey(identityProviderName, tenantDomain);
        ProvisioningConnectorCacheEntry entry = ProvisioningConnectorCache.getInstance().getValueFromCache(cacheKey);

        if (entry != null) {
            if (log.isDebugEnabled()) {
                log.debug("Provisioning cache HIT for " + identityProviderName + " of "
                        + tenantDomain);
            }
            return entry.getProvisioningConnector();
        }

        AbstractOutboundProvisioningConnector connector;

        Property idpName = new Property();
        idpName.setName("identityProviderName");
        idpName.setValue(identityProviderName);

        List<Property> provisioningPropertiesList = new ArrayList<>(Arrays.asList(provisoningProperties));

        provisioningPropertiesList.add(idpName);

        Property[] provisioningProperties = new Property[provisioningPropertiesList.size()];
        provisioningProperties = provisioningPropertiesList.toArray(provisioningProperties);

        connector = buildConnector(provisioningProperties);
        entry = new ProvisioningConnectorCacheEntry();
        entry.setProvisioningConnector(connector);
        ProvisioningConnectorCache.getInstance().addToCache(cacheKey, entry);

        return connector;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();

        if (tenantDomain != null) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                    tenantDomainName);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        }
    }

}
 
Example 18
Source File: AbstractProvisioningConnectorFactory.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param identityProviderName
 * @param tenantDomain
 * @throws IdentityProvisioningException
 */
public void destroyConnector(String identityProviderName, String tenantDomain)
        throws IdentityProvisioningException {

    String tenantDomainName = null;
    int tenantId = -1234;

    if (CarbonContext.getThreadLocalCarbonContext() != null) {
        tenantDomainName = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    }

    try {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        ProvisioningConnectorCacheKey cacheKey = new ProvisioningConnectorCacheKey(identityProviderName, tenantDomain);
        ProvisioningConnectorCacheEntry entry = ProvisioningConnectorCache.getInstance().getValueFromCache(cacheKey);

        if (entry != null) {
            ProvisioningConnectorCache.getInstance().clearCacheEntry(cacheKey);

            if (log.isDebugEnabled()) {
                log.debug("Provisioning cached entry removed for idp " + identityProviderName
                        + " from the connector " + getConnectorType());
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Provisioning cached entry not found for idp " + identityProviderName
                        + " from the connector " + getConnectorType());
            }
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();

        if (tenantDomain != null) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                    tenantDomainName);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        }
    }
}
 
Example 19
Source File: StratosAuthenticationHandler.java    From product-private-paas with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if ((username == null) || username.equals("")) {
        log.error("username is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic")
                .type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("Username cannot be null")).build();
    } else if (certObject == null && ((password == null) || password.equals(""))) {
        log.error("password is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic")
                .type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                        type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null || userRealm.getUserStoreManager()
                .authenticate(username, password)) {  // if authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            //populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("authenticated using the " + CookieBasedAuthenticationHandler.class.getName()
                        + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
            }
            return null;
        } else {
            log.warn("unable to authenticate the request");
            // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                    type(MediaType.APPLICATION_JSON)
                    .entity(Utils.buildMessage("Authentication failed. Please " + "check your username/password"))
                    .build();
        }
    } catch (Exception exception) {
        log.error("Authentication failed", exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(Utils.buildMessage("Unexpected error. Please contact the system admin")).build();
    }

}
 
Example 20
Source File: StratosAuthenticationHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Authenticating request: [message-id] %s", message.getId()));
    }

    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if (StringUtils.isEmpty(username)) {
        log.error("username is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "Username cannot be null")).build();
    } else if (certObject == null && (StringUtils.isEmpty(password))) {
        log.error("password is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                        type(MediaType.APPLICATION_JSON).entity(
                        new ResponseMessageBean(ResponseMessageBean.ERROR, "Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null || userRealm.getUserStoreManager().authenticate(username, password)) {  // if authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            //populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("Authenticated using the " + CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
            }
            return null;
        } else {
            log.warn(String.format("Unable to authenticate the request: [message-id] %s", message.getId()));
            // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                    type(MediaType.APPLICATION_JSON).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                    "Authentication failed. Please check your username/password")).build();
        }
    } catch (Exception exception) {
        log.error(String.format("Authentication failed: [message-id] %s", message.getId()), exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "Unexpected error. Please contact the system admin")).build();
    }
}