Java Code Examples for org.wso2.carbon.context.PrivilegedCarbonContext#setTenantDomain()
The following examples show how to use
org.wso2.carbon.context.PrivilegedCarbonContext#setTenantDomain() .
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: EntitlementEngineCache.java From carbon-identity-framework with Apache License 2.0 | 6 votes |
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 2
Source File: ManagementPermissionsAdder.java From carbon-identity with Apache License 2.0 | 6 votes |
@Override public void bundleChanged(BundleEvent event) { Bundle bundle = event.getBundle(); try { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); if (event.getType() == BundleEvent.STARTED) { addUIPermissionFromBundle(bundle); } } catch (Exception e) { log.error("Error occured when processing component xml in bundle " + bundle.getSymbolicName(), e); } }
Example 3
Source File: EntitlementEngineCache.java From carbon-identity with Apache License 2.0 | 6 votes |
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 4
Source File: StratosApiV41Utils.java From attic-stratos with Apache License 2.0 | 6 votes |
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 5
Source File: ServerStartupListener.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Method to load the configurations of a tenant */ private static void loadTenant(String username) throws IOException { String tenantDomain; APIManagerConfiguration config = ServiceDataHolder.getInstance(). getAPIManagerConfigurationService().getAPIManagerConfiguration(); tenantDomain = MultitenantUtils.getTenantDomain(username); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantDomain(tenantDomain); carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(username)); ConfigurationContext context = ServiceDataHolder.getInstance().getConfigurationContextService().getServerConfigContext(); // load tenant configuration TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, context); log.info("Successfully loaded tenant with tenant domain : " + tenantDomain); } finally { PrivilegedCarbonContext.endTenantFlow(); } } else { if (log.isDebugEnabled()) { log.debug("Skipping loading super tenant space since execution is currently in super tenant flow."); } } }
Example 6
Source File: FrameworkUtils.java From carbon-identity-framework with Apache License 2.0 | 6 votes |
/** * Starts the tenant flow for the given tenant domain * * @param tenantDomain tenant domain */ public static void startTenantFlow(String tenantDomain) { String tenantDomainParam = tenantDomain; int tenantId = MultitenantConstants.SUPER_TENANT_ID; if (tenantDomainParam != null && !tenantDomainParam.trim().isEmpty()) { try { tenantId = FrameworkServiceComponent.getRealmService().getTenantManager() .getTenantId(tenantDomain); } catch (UserStoreException e) { log.error("Error while getting tenantId from tenantDomain query param", e); } } else { tenantDomainParam = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(tenantId); carbonContext.setTenantDomain(tenantDomainParam); }
Example 7
Source File: RegistryManager.java From attic-stratos with Apache License 2.0 | 5 votes |
/** * 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 8
Source File: BasicAuthenticationInterceptor.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * This method authenticates the request using Basic authentication and validate the roles of user based on * roles of scope. * * @param inMessage cxf Message * @param username username in basic auth header * @param password password in basic auth header * @return true if user is successfully authenticated and authorized. false otherwise. */ private boolean authenticate(Message inMessage, String username, String password) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null); RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class, null); String tenantDomain = MultitenantUtils.getTenantDomain(username); int tenantId; UserRealm userRealm; try { tenantId = realmService.getTenantManager().getTenantId(tenantDomain); userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain); if (userRealm == null) { log.error("Authentication failed: invalid domain or unactivated tenant login"); return false; } //if authenticated if (userRealm.getUserStoreManager() .authenticate(MultitenantUtils.getTenantAwareUsername(username), password)) { //set the correct tenant info for downstream code. carbonContext.setTenantDomain(tenantDomain); carbonContext.setTenantId(tenantId); carbonContext.setUsername(username); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { APIUtil.loadTenantConfigBlockingMode(tenantDomain); } return validateRoles(inMessage, userRealm, tenantDomain, username); } else { log.error("Authentication failed: Invalid credentials"); } } catch (UserStoreException | CarbonException e) { log.error("Error occurred while authenticating user: " + username, e); } return false; }
Example 9
Source File: WebappAuthenticationValve.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
@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 10
Source File: UserMgtInitializer.java From carbon-identity-framework with Apache License 2.0 | 5 votes |
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: PreAuthenticationInterceptor.java From carbon-apimgt with Apache License 2.0 | 5 votes |
@Override public void handleMessage(Message message) throws Fault { String path = (String) message.get(Message.PATH_INFO); if (path.contains(APIConstants.RestApiConstants.REST_API_OLD_VERSION)) { path = path.replace("/" + APIConstants.RestApiConstants.REST_API_OLD_VERSION, ""); } String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD); Dictionary<URITemplate,List<String>> whiteListedResourcePathsMap; //If Authorization headers are present anonymous URI check will be skipped ArrayList authHeaders = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))) .get(RestApiConstants.AUTH_HEADER_NAME); if (authHeaders != null) return; //Check if the accessing URI is white-listed and then authorization is skipped try { whiteListedResourcePathsMap = RestApiUtil.getWhiteListedURIsToMethodsMap(); Enumeration<URITemplate> uriTemplateSet = whiteListedResourcePathsMap.keys(); while (uriTemplateSet.hasMoreElements()) { URITemplate uriTemplate = uriTemplateSet.nextElement(); if (uriTemplate.matches(path, new HashMap<String, String>())) { List<String> whiteListedVerbs = whiteListedResourcePathsMap.get(uriTemplate); if (whiteListedVerbs.contains(httpMethod)) { message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); return; } } } } catch (APIManagementException e) { RestApiUtil .handleInternalServerError("Unable to retrieve/process white-listed URIs for REST API", e, logger); } }
Example 12
Source File: UserMgtInitializer.java From carbon-identity with Apache License 2.0 | 5 votes |
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 13
Source File: EntitlementEngineCache.java From carbon-identity with Apache License 2.0 | 5 votes |
public void put(int key, EntitlementEngine engine) { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); getEntitlementCache().put(key, engine); if (log.isDebugEnabled()) { log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is populated with new entry " + "with tenantId : " + key); } } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 14
Source File: RegistryManager.java From attic-stratos with Apache License 2.0 | 5 votes |
/** * 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 15
Source File: ProvisioningApplicationMgtListener.java From carbon-identity-framework with Apache License 2.0 | 5 votes |
private void destroySpProvConnectors(String applicationName, String tenantDomain) { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); // reading from the cache ServiceProviderProvisioningConnectorCacheKey key = new ServiceProviderProvisioningConnectorCacheKey(applicationName, tenantDomain); ServiceProviderProvisioningConnectorCacheEntry entry = ServiceProviderProvisioningConnectorCache .getInstance().getValueFromCache(key); // cache hit if (entry != null) { ServiceProviderProvisioningConnectorCache.getInstance().clearCacheEntry(key); if (log.isDebugEnabled()) { log.debug("Provisioning cached entry removed for sp " + applicationName); } } else { if (log.isDebugEnabled()) { log.debug("Provisioning cached entry not found for sp " + applicationName); } } } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 16
Source File: EntitlementEngineCache.java From carbon-identity-framework with Apache License 2.0 | 5 votes |
public void put(int key, EntitlementEngine engine) { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); getEntitlementCache().put(key, engine); if (log.isDebugEnabled()) { log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is populated with new entry " + "with tenantId : " + key); } } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 17
Source File: BaseCache.java From carbon-identity with Apache License 2.0 | 4 votes |
private Cache<K, V> getBaseCache() { Cache<K, V> cache = null; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); CacheManager cacheManager = Caching.getCacheManagerFactory() .getCacheManager(CACHE_MANAGER_NAME); if (getCacheTimeout() > 0 && cacheBuilder == null) { synchronized (cacheName.intern()) { if (cacheBuilder == null) { cacheManager.removeCache(cacheName); cacheBuilder = cacheManager.<K, V>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration .Duration(TimeUnit.SECONDS, getCacheTimeout())). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration .Duration(TimeUnit.SECONDS, getCacheTimeout())). setStoreByValue(false); cache = cacheBuilder.build(); for (AbstractCacheListener cacheListener : cacheListeners) { if (cacheListener.isEnable()) { this.cacheBuilder.registerCacheEntryListener(cacheListener); } } setCapacity((CacheImpl) cache); } else { cache = cacheManager.getCache(cacheName); setCapacity((CacheImpl) cache); } } } else { cache = cacheManager.getCache(cacheName); setCapacity((CacheImpl) cache); } } finally { PrivilegedCarbonContext.endTenantFlow(); } return cache; }
Example 18
Source File: ProxyTimerTask.java From carbon-commons with Apache License 2.0 | 4 votes |
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 19
Source File: UserMgtDSComponent.java From carbon-identity with Apache License 2.0 | 4 votes |
protected void activate(ComponentContext ctxt) { log.debug("User Mgt bundle is activated "); // for new cahing, every thread should has its own populated CC. During the deployment time we assume super tenant PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantDomain(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); carbonContext.setTenantId(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); UserMgtInitializer userMgtInitializer = new UserMgtInitializer(); try { userMgtInitializer.start(ctxt.getBundleContext(), registryService); ManagementPermissionsAdder uiPermissionAdder = new ManagementPermissionsAdder(); ctxt.getBundleContext().addBundleListener(uiPermissionAdder); Bundle[] bundles = ctxt.getBundleContext().getBundles(); for (Bundle bundle : bundles) { if (bundle.getState() == Bundle.ACTIVE) { uiPermissionAdder.addUIPermissionFromBundle(bundle); } } // register the Authorization listener to restriction tenant!=0 setting super tenant // specific permissions ServiceRegistration serviceRegistration = ctxt.getBundleContext().registerService (AuthorizationManagerListener.class.getName(), new PermissionAuthorizationListener(), null); if (serviceRegistration == null) { log.error("Error while registering PermissionAuthorizationListener."); } else { if (log.isDebugEnabled()) { log.debug("PermissionAuthorizationListener successfully registered."); } } serviceRegistration = ctxt.getBundleContext().registerService(UserOperationEventListener.class.getName(), new UserMgtAuditLogger(), null); if (serviceRegistration == null) { log.error("Error while registering UserMgtAuditLogger."); } else { if (log.isDebugEnabled()) { log.debug("UserMgtAuditLogger successfully registered."); } } } catch (Throwable e) { log.error(e.getMessage(), e); // don't throw exception } }
Example 20
Source File: StratosAuthenticationHandler.java From attic-stratos with Apache License 2.0 | 4 votes |
/** * 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(); } }