Java Code Examples for org.wso2.carbon.user.core.service.RealmService

The following examples show how to use org.wso2.carbon.user.core.service.RealmService. These examples are extracted from open source projects. 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
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example 2
Source Project: carbon-commons   Source File: CarbonUserRealmHostObject.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example 3
Source Project: carbon-apimgt   Source File: HostObjectComponent.java    License: Apache License 2.0 5 votes vote down vote up
@Reference(
         name = "user.realm.service", 
         service = org.wso2.carbon.user.core.service.RealmService.class, 
         cardinality = ReferenceCardinality.MANDATORY, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
    if (realmService != null && log.isDebugEnabled()) {
        log.debug("Realm service initialized");
    }
    ServiceReferenceHolder.getInstance().setRealmService(realmService);
}
 
Example 4
Source Project: carbon-apimgt   Source File: SelfSignupUtilTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSelfSignupConfigFromRegistryTenant() throws Exception {
    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("foo.com");
    Mockito.when(privilegedCarbonContext.getRegistry(RegistryType.SYSTEM_GOVERNANCE)).thenReturn(registry);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId("foo.com")).thenReturn(4444);

    PowerMockito.mockStatic(APIUtil.class);
    Mockito.when(registry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(true);
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(resource.getContent()).thenReturn("wsdl".getBytes());
    Mockito.when(registry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(resource);
    OMElement omElement = Mockito.mock(OMElement.class);
    Mockito.when(omElement.getFirstChildWithName(Matchers.any(QName.class))).thenReturn(omElement);
    PowerMockito.mockStatic(AXIOMUtil.class);
    Mockito.when(omElement.getChildrenWithLocalName(APIConstants.SELF_SIGN_UP_REG_ROLE_ELEM)).thenReturn(Mockito.mock(Iterator.class));
    PowerMockito.when(AXIOMUtil.stringToOM("wsdl")).thenReturn(omElement);
    PowerMockito.mockStatic(PasswordResolverFactory.class);
    PasswordResolver passwordResolver = Mockito.mock(PasswordResolver.class);
    PowerMockito.when(PasswordResolverFactory.getInstance()).thenReturn(passwordResolver);
    UserRegistrationConfigDTO userRegistrationConfigDTO = SelfSignUpUtil.getSignupConfiguration("bar.com");
    Assert.assertNotNull(userRegistrationConfigDTO);
    PowerMockito.verifyStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext.endTenantFlow();
}
 
Example 5
protected void unsetRealmService(RealmService realmService) {

        if (log.isDebugEnabled()) {
            log.debug("RealmService is unset in the Application Authentication Framework bundle");
        }
        FrameworkServiceDataHolder.getInstance().setRealmService(null);
    }
 
Example 6
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws UserStoreException, RegistryException {
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    userRealm = Mockito.mock(UserRealm.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    userStoreManager = Mockito.mock(UserStoreManager.class);
    keyManager = Mockito.mock(KeyManager.class);
    cacheInvalidator = Mockito.mock(CacheInvalidator.class);
    registryService = Mockito.mock(RegistryService.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registry = Mockito.mock(Registry.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    authorizationManager = Mockito.mock(AuthorizationManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ApplicationUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.mockStatic(CacheInvalidator.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(CacheInvalidator.getInstance()).thenReturn(cacheInvalidator);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(KeyManagerHolder.getKeyManagerInstance(Mockito.anyString(),Mockito.anyString())).thenReturn(keyManager);
    PowerMockito.when(APIUtil.replaceSystemProperty(anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
}
 
Example 7
/**
 * Sets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void setRealmService(RealmService realmService) {

    if (log.isDebugEnabled()) {
        log.debug("Setting Realm Service");
    }
    PolicyManagementDataHolder.getInstance().setRealmService(realmService);
}
 
Example 8
Source Project: attic-stratos   Source File: ClaimsMgtUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets first name from the user store manager
 *
 * @param tenant   tenant
 * @param tenantId tenant id
 * @return first name
 * @throws UserStoreException , if error in getting the claim GIVEN_NAME
 */
public static String getFirstNamefromUserStoreManager(RealmService realmService,
                                                      int tenantId) throws UserStoreException {
    try {
        return getClaimfromUserStoreManager(realmService, tenantId,
                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
    } catch (Exception e) {
        String msg = "First Name not found for the tenant";
        log.debug(msg, e);
        return ""; // returns empty string
    }
}
 
Example 9
/**
 * Unsets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting Realm Service");
    }
    PolicyDecisionPointDataHolder.getInstance().setRealmService(null);
}
 
Example 10
/**
 * @param userName
 * @param tenantDomain
 * @return
 * @throws CarbonException
 * @throws UserStoreException
 */
private Map<String, String> getUserClaims(String userName, String tenantDomain) throws CarbonException,
                                                                                       UserStoreException {

    Map<String, String> inboundAttributes = new HashMap<>();

    RegistryService registryService = IdentityProvisionServiceComponent.getRegistryService();
    RealmService realmService = IdentityProvisionServiceComponent.getRealmService();

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

    UserStoreManager userstore = null;
    userstore = realm.getUserStoreManager();
    Claim[] claimArray = null;
    try {
        claimArray = userstore.getUserClaimValues(userName, null);
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + userName + " not found in user store");
            }
        } else {
            throw e;
        }
    }
    if (claimArray != null) {
        for (Claim claim : claimArray) {
            inboundAttributes.put(claim.getClaimUri(), claim.getValue());
        }
    }

    return inboundAttributes;
}
 
Example 11
/**
 * @param realmService
 */
@Reference(
         name = "realm.service", 
         service = org.wso2.carbon.user.core.service.RealmService.class, 
         cardinality = ReferenceCardinality.MANDATORY, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Setting the Realm Service");
    }
    ProvisioningServiceDataHolder.getInstance().setRealmService(realmService);
}
 
Example 12
Source Project: carbon-commons   Source File: ClaimsMgtUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets first name from the user store manager
 * 
 * @param tenant
 *            tenant
 * @param tenantId
 *            tenant id
 * @return first name
 * @throws UserStoreException
 *             , if error in getting the claim GIVEN_NAME
 */
public static String getFirstNamefromUserStoreManager(RealmService realmService,
                                                      int tenantId) throws UserStoreException {
    try {
        return getClaimfromUserStoreManager(realmService, tenantId,
                                            UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
    } catch (Exception e) {
        String msg = "First Name not found for the tenant";
        log.debug(msg, e);
        return ""; // returns empty string
    }
}
 
Example 13
Source Project: carbon-apimgt   Source File: RoleBasedScopesIssuer.java    License: 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 14
@Reference(
        name = "realm.service",
        service = org.wso2.carbon.user.core.service.RealmService.class,
        cardinality = ReferenceCardinality.MANDATORY,
        policy = ReferencePolicy.DYNAMIC,
        unbind = "unsetRealmService"
)
protected void setRealmService(RealmService realmService) {

    TemplateManagementUIServiceDataHolder.getInstance().setRealmService(realmService);
    if (realmService != null && log.isDebugEnabled()) {
        log.debug("RealmService is registered in ConsentManager service.");
    }
}
 
Example 15
Source Project: product-ei   Source File: MigrationServiceComponent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to unset realm service.
 *
 * @param realmService service to get tenant data.
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting RealmService from WSO2 EI Config component");
    }
    MigrationServiceDataHolder.setRealmService(null);
}
 
Example 16
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for delete role received without the mandatory " +
                "parameter 'username'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteRole(roleName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting role is aborted for role '" + roleName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 17
/**
 * Unsets Realm Service
 *
 * @param realmService An instance of RealmService
 */
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting Realm Service");
    }
    PolicyManagementDataHolder.getInstance().setRealmService(null);
}
 
Example 18
Source Project: carbon-commons   Source File: EventBrokerBuilderDS.java    License: Apache License 2.0 5 votes vote down vote up
@Reference(
        name = "realm.service",
        service = org.wso2.carbon.user.core.service.RealmService.class,
        cardinality = ReferenceCardinality.MANDATORY,
        policy = ReferencePolicy.DYNAMIC,
        unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {

    EventBrokerHolder.getInstance().registerRealmService(realmService);
}
 
Example 19
/**
 * @param userName
 * @param tenantDomain
 * @return
 * @throws CarbonException
 * @throws UserStoreException
 */
private List<String> getUserRoles(String userName, String tenantDomain) throws CarbonException,
        UserStoreException {

    RegistryService registryService = IdentityProvisionServiceComponent.getRegistryService();
    RealmService realmService = IdentityProvisionServiceComponent.getRealmService();

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

    UserStoreManager userstore = null;
    userstore = realm.getUserStoreManager();
    String[] newRoles = userstore.getRoleListOfUser(userName);
    return Arrays.asList(newRoles);
}
 
Example 20
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting the RealmService");
    }
    this.realmService = null;
    SecurityServiceHolder.setRealmService(null);
}
 
Example 21
Source Project: product-es   Source File: EsMigrationServiceComponent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to set realm service.
 *
 * @param realmService service to get tenant data.
 */
protected void setRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Setting RealmService for WSO2 Enterprise Store migration");
    }
    ServiceHolder.setRealmService(realmService);
}
 
Example 22
Source Project: carbon-device-mgt   Source File: DeviceMgtAPIUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
    RealmService realmService =
            (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
    if (realmService == null) {
        throw new IllegalStateException("Realm service has not been initialized.");
    }
    try {
        return realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new DeviceManagementException("Error occured while trying to " +
                "obtain tenant id of currently logged in user");
    }
}
 
Example 23
Source Project: carbon-identity   Source File: IdentityTenantUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void setRealmService(RealmService realmService) {
    IdentityTenantUtil.realmService = realmService;
}
 
Example 24
protected void setRealmService(RealmService realmService) {
    IdentityAccountAssociationServiceDataHolder.getInstance().setRealmService(realmService);
}
 
Example 25
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 4 votes vote down vote up
public boolean login(AuthnReqDTO authDto) {
    String username = null;
    String tenantDomain = null;
    String auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_FAILED;

    HttpSession httpSession = getHttpSession();
    try {
        XMLObject xmlObject = Util.unmarshall(org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.decode(authDto.getResponse()));

        username = org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.getUsername(xmlObject);

        if ((username == null) || "".equals(username.trim())) {
            log.error("Authentication Request is rejected. " +
                    "SAMLResponse does not contain the username of the subject.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, -1,
                    "SAML2 SSO Authentication", "SAMLResponse does not contain the username of the subject");
            // Unable to call #handleAuthenticationCompleted since there is no way to determine
            // tenantId without knowing the username.
            return false;
        }

        if (!validateAudienceRestrictionInXML(xmlObject)) {
            log.error("Authentication Request is rejected. SAMLResponse AudienceRestriction validation failed.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, -1,
                    "SAML2 SSO Authentication", "AudienceRestriction validation failed");
            return false;
        }

        RegistryService registryService = SAML2SSOAuthBEDataHolder.getInstance().getRegistryService();
        RealmService realmService = SAML2SSOAuthBEDataHolder.getInstance().getRealmService();
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        handleAuthenticationStarted(tenantId);
        if (isResponseSignatureValidationEnabled()) {
            boolean isSignatureValid = validateSignature(xmlObject, tenantDomain);
            if (!isSignatureValid) {
                log.error("Authentication Request is rejected. Signature validation failed.");
                CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, tenantId,
                        "SAML2 SSO Authentication", "Invalid Signature");
                handleAuthenticationCompleted(tenantId, false);
                return false;
            }
        }

        username = MultitenantUtils.getTenantAwareUsername(username);
        UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                realmService, tenantDomain);
        // Authentication is done

        // Starting user provisioning
        provisionUser(username, realm, xmlObject);
        // End user provisioning

        // Starting Authorization

        PermissionUpdateUtil.updatePermissionTree(tenantId);
        boolean isAuthorized = false;
        if (realm != null) {
            isAuthorized = realm.getAuthorizationManager().isUserAuthorized(username,
                    "/permission/admin/login", CarbonConstants.UI_PERMISSION_ACTION);
        }
        if (isAuthorized) {
            CarbonAuthenticationUtil.onSuccessAdminLogin(httpSession, username,
                    tenantId, tenantDomain, "SAML2 SSO Authentication");
            handleAuthenticationCompleted(tenantId, true);
            auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_SUCCESS;
            return true;
        } else {
            log.error("Authentication Request is rejected. Authorization Failure.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, tenantId,
                    "SAML2 SSO Authentication", "Authorization Failure");
            handleAuthenticationCompleted(tenantId, false);
            return false;
        }
    } catch (Exception e) {
        String msg = "System error while Authenticating/Authorizing User : " + e.getMessage();
        log.error(msg, e);
        return false;
    } finally {
        if (username != null && username.trim().length() > 0 && AUDIT_LOG.isInfoEnabled()) {

            String auditInitiator = username + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain;
            String auditData = "";

            AUDIT_LOG.info(String.format(SAML2SSOAuthenticatorConstants.AUDIT_MESSAGE,
                    auditInitiator, SAML2SSOAuthenticatorConstants.AUDIT_ACTION_LOGIN, AUTHENTICATOR_NAME,
                    auditData, auditResult));
        }
    }
}
 
Example 26
/**
 * 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
 */
@Override
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 = 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 27
Source Project: carbon-identity   Source File: STSServiceComponent.java    License: Apache License 2.0 4 votes vote down vote up
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.debug("Unsetting the RealmService");
    }
    STSServiceDataHolder.getInstance().setRealmService(null);
}
 
Example 28
Source Project: carbon-apimgt   Source File: APIUtilTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled() throws Exception {
    System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
                .SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    API expectedAPI = getUniqueAPI();

    final String provider = expectedAPI.getId().getProviderName();
    final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    final int tenantId = -1234;

    System.setProperty("carbon.home", "");

    File siteConfFile = new File(Thread.currentThread().getContextClassLoader().
            getResource("tenant-conf.json").getFile());

    String tenantConfValue = FileUtils.readFileToString(siteConfFile);

    GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
    Registry registry = Mockito.mock(Registry.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    Resource resource = Mockito.mock(Resource.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
    SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
    SubscriptionPolicy[] policies = new SubscriptionPolicy[]{policy};
    QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
    RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIID(Mockito.any(APIIdentifier.class), eq((Connection) null))).thenReturn(123);
    Mockito.when(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, provider)).thenReturn(new String[]{"Unlimited"});
    Mockito.when(artifact.getId()).thenReturn("");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_TIER)).thenReturn("Unlimited");
    Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    Mockito.when(registryService.getConfigSystemRegistry(tenantId)).thenReturn(userRegistry);
    Mockito.when(userRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(true);
    Mockito.when(userRegistry.get(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(resource);

    String artifactPath = "";
    Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
    Mockito.when(registry.get(artifactPath)).thenReturn(resource);
    Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
    Mockito.when(throttleProperties.isEnabled()).thenReturn(false);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
    Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
    Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));

    ArrayList<URITemplate> urlList = getURLTemplateList(expectedAPI.getUriTemplates());
    Mockito.when(apiMgtDAO.getAllURITemplates(Mockito.anyString(), Mockito.anyString())).thenReturn(urlList);

    CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();

    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).
            thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).
            thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).
            thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());

    API api = APIUtil.getAPI(artifact);

    Assert.assertNotNull(api);
}finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 29
protected void unsetRealmService(RealmService realmService) {
    if (log.isDebugEnabled()) {
        log.info("Unsetting the Realm Service");
    }
    UserRegistrationDSComponent.realmService = null;
}
 
Example 30
Source Project: carbon-identity   Source File: OAuthHandler.java    License: 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;
}