public static String getUserName() {
   String username = "";
   RealmService realmService = DynamicClientRegistrationDataHolder.getInstance().getRealmService();
   if (realmService != null) {
     username = realmService.getBootstrapRealmConfiguration().getAdminUserName();
   }
   return username;
 }
Пример #2
0
  @Override
  public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
      throws IdentityOAuth2Exception {
    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    String username = oAuth2AccessTokenReqDTO.getResourceOwnerUsername();
    int tenantId;
    try {
      tenantId = IdentityUtil.getTenantIdOFUser(username);
    } catch (IdentityException e) {
      throw new IdentityOAuth2Exception(e.getMessage(), e);
    }

    // tenantId == -1, means an invalid tenant.
    if (tenantId == -1) {
      /*if (log.isDebugEnabled()) {
          log.debug("Token request with Password Grant Type for an invalid tenant : " +
                  MultitenantUtils.getTenantDomain(username));
      }
      return false;*/
      tenantId = MultitenantConstants.SUPER_TENANT_ID;
    }

    RealmService realmService = OAuthComponentServiceHolder.getRealmService();
    boolean authStatus;
    try {
      UserStoreManager userStoreManager =
          realmService.getTenantUserRealm(tenantId).getUserStoreManager();
      authStatus =
          userStoreManager.authenticate(
              MultitenantUtils.getTenantAwareUsername(username),
              oAuth2AccessTokenReqDTO.getResourceOwnerPassword());

      if (log.isDebugEnabled()) {
        log.debug(
            "Token request with Password Grant Type received. "
                + "Username : "******"Scope : "
                + OAuth2Util.buildScopeString(oAuth2AccessTokenReqDTO.getScope())
                + ", Authentication State : "
                + authStatus);
      }

    } catch (UserStoreException e) {
      throw new IdentityOAuth2Exception("Error when authenticating the user credentials.", e);
    }

    tokReqMsgCtx.setAuthorizedUser(oAuth2AccessTokenReqDTO.getResourceOwnerUsername());
    tokReqMsgCtx.setScope(oAuth2AccessTokenReqDTO.getScope());
    return authStatus;
  }
 private String getTenantDomainName() throws KeyStoreMgtException {
   RealmService realmService = RealmServiceHolder.getRealmService();
   if (realmService == null) {
     String msg = "Error in getting the domain name, realm service is null.";
     log.error(msg);
     throw new KeyStoreMgtException(msg);
   }
   try {
     return realmService.getTenantManager().getDomain(tenantId);
   } catch (org.wso2.carbon.user.api.UserStoreException e) {
     String msg = "Error in getting the domain name for the tenant id: " + tenantId;
     log.error(msg, e);
     throw new KeyStoreMgtException(msg, e);
   }
 }
  public String getGroupingIdentifiers(String loginResponse) {

    JSONObject obj;
    String username = null;
    Boolean isSuperTenant;
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    String claim = "http://wso2.org/claims/organization";
    String organization = null;
    try {
      obj = new JSONObject(loginResponse);
      username = (String) obj.get("user");
      isSuperTenant = (Boolean) obj.get("isSuperTenant");

      RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();

      // if the user is not in the super tenant domain then find the domain name and tenant id.
      if (!isSuperTenant) {
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        tenantId =
            ServiceReferenceHolder.getInstance()
                .getRealmService()
                .getTenantManager()
                .getTenantId(tenantDomain);
      }

      UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
      UserStoreManager manager = realm.getUserStoreManager();
      organization =
          manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
      if (organization != null) {
        organization = tenantDomain + "/" + organization.trim();
      }
    } catch (JSONException e) {
      log.error("Exception occured while trying to get group Identifier from login response");
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
      log.error("Error while checking user existence for " + username);
    }

    return organization;
  }
Пример #5
0
 /**
  * Retrieves the current user's roles given the username.
  *
  * @param username The username
  * @return The user roles
  * @throws DataServiceFault
  */
 public static String[] getUserRoles(String username) throws DataServiceFault {
   RealmService realmService = DataServicesDSComponent.getRealmService();
   RegistryService registryService = DataServicesDSComponent.getRegistryService();
   username = MultitenantUtils.getTenantAwareUsername(username);
   String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
   int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
   username = MultitenantUtils.getTenantAwareUsername(username);
   try {
     if (tenantId < MultitenantConstants.SUPER_TENANT_ID) {
       tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
     }
     if (tenantId < MultitenantConstants.SUPER_TENANT_ID) {
       /* the tenant doesn't exist. */
       log.error("The tenant doesn't exist. Tenant domain:" + tenantDomain);
       throw new DataServiceFault("Access Denied. You are not authorized.");
     }
     if (!realmService.getTenantManager().isTenantActive(tenantId)) {
       /* the tenant is not active. */
       log.error("The tenant is not active. Tenant domain:" + tenantDomain);
       throw new DataServiceFault("The tenant is not active. Tenant domain:" + tenantDomain);
     }
     UserRealm realm = registryService.getUserRealm(tenantId);
     String roles[] = realm.getUserStoreManager().getRoleListOfUser(username);
     return roles;
   } catch (Exception e) {
     String msg =
         "Error in retrieving the realm for the tenant id: "
             + tenantId
             + ", username: "******". "
             + e.getMessage();
     log.error(msg);
     throw new DataServiceFault(msg);
   }
 }
 public static TenantManager getTenantManager() {
   return realmService.getTenantManager();
 }
  /**
   * This method used to confirm the self registered user account and unlock it.
   *
   * @param username
   * @param code
   * @param captcha
   * @param tenantDomain
   * @return
   * @throws IdentityMgtServiceException
   */
  public VerificationBean confirmUserSelfRegistration(
      String username, String code, CaptchaInfoBean captcha, String tenantDomain)
      throws IdentityMgtServiceException {

    VerificationBean bean = new VerificationBean();

    if (log.isDebugEnabled()) {
      log.debug("User registration verification request received with username :"******" Error while validating captcha for user : "******"Trying to confirm users in unauthorized tenant space";
        log.error(msg);
      }
      if (tenantDomain == null || tenantDomain.isEmpty()) {
        tenantDomain = loggedInTenant;
      }
    }

    UserDTO userDTO = null;
    try {
      userDTO = Utils.processUserId(username + "@" + tenantDomain);

    } catch (IdentityException e) {
      bean =
          handleError(
              VerificationBean.ERROR_CODE_INVALID_USER
                  + " Error verifying user account for user : "******"Error retrieving the user store manager for the tenant : " + tenantDomain, e);
        return bean;
      }

      try {
        bean = processor.verifyConfirmationCode(1, username, code);
        if (bean.isVerified()) {
          UserIdentityManagementUtil.unlockUserAccount(username, userStoreManager);
          bean.setVerified(true);

        } else {
          bean.setVerified(false);
          bean.setKey("");
          log.error("User verification failed against the given confirmation code");
        }
      } catch (IdentityException e) {
        bean = handleError("Error while validating confirmation code for user : " + username, e);
        return bean;
      }
    } finally {
      if (IdentityMgtConfig.getInstance().isSaasEnabled()) {
        PrivilegedCarbonContext.endTenantFlow();
      }
    }
    return bean;
  }
  /**
   * This method is used to register an user in the system. The account will be locked if the
   * Authentication.Policy.Account.Lock.On.Creation is set to true. Else user will be able to login
   * after registration.
   *
   * @param userName
   * @param password
   * @param claims
   * @param profileName
   * @param tenantDomain
   * @return
   * @throws IdentityMgtServiceException
   */
  public VerificationBean registerUser(
      String userName,
      String password,
      UserIdentityClaimDTO[] claims,
      String profileName,
      String tenantDomain)
      throws IdentityMgtServiceException {

    VerificationBean vBean = new VerificationBean();

    org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
    Permission permission = null;

    if (!IdentityMgtConfig.getInstance().isSaasEnabled()) {
      String loggedInTenant =
          PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
      if (tenantDomain != null && !tenantDomain.isEmpty() && !loggedInTenant.equals(tenantDomain)) {
        String msg = "Trying to create users in unauthorized tenant space";
        log.error(msg);
        throw new IdentityMgtServiceException(msg);
      }
      if (tenantDomain == null || tenantDomain.isEmpty()) {
        tenantDomain = loggedInTenant;
      }
    }

    RealmService realmService = IdentityMgtServiceComponent.getRealmService();
    int tenantId;

    try {

      tenantId = Utils.getTenantId(tenantDomain);
      if (realmService.getTenantUserRealm(tenantId) != null) {
        userStoreManager =
            (org.wso2.carbon.user.core.UserStoreManager)
                realmService.getTenantUserRealm(tenantId).getUserStoreManager();
      }

    } catch (Exception e) {
      vBean =
          handleError(
              VerificationBean.ERROR_CODE_UNEXPECTED
                  + " Error retrieving the user store manager for the tenant",
              e);
      return vBean;
    }

    try {

      if (userStoreManager == null) {
        vBean = new VerificationBean();
        vBean.setVerified(false);
        vBean.setError(
            VerificationBean.ERROR_CODE_UNEXPECTED
                + " Error retrieving the user store manager for the tenant");
        return vBean;
      }

      Map<String, String> claimsMap = new HashMap<String, String>();
      for (UserIdentityClaimDTO userIdentityClaimDTO : claims) {
        claimsMap.put(userIdentityClaimDTO.getClaimUri(), userIdentityClaimDTO.getClaimValue());
      }

      userStoreManager.addUser(userName, password, null, claimsMap, profileName);

      String identityRoleName =
          UserCoreConstants.INTERNAL_DOMAIN
              + CarbonConstants.DOMAIN_SEPARATOR
              + IdentityConstants.IDENTITY_DEFAULT_ROLE;

      if (!userStoreManager.isExistingRole(identityRoleName, false)) {
        permission = new Permission("/permission/admin/login", UserMgtConstants.EXECUTE_ACTION);
        userStoreManager.addRole(
            identityRoleName, new String[] {userName}, new Permission[] {permission}, false);
      } else {
        userStoreManager.updateUserListOfRole(
            identityRoleName, new String[] {}, new String[] {userName});
      }

      IdentityEventListener identityEventListener =
          IdentityUtil.readEventListenerProperty(
              UserOperationEventListener.class.getName(), IdentityMgtEventListener.class.getName());

      boolean isListenerEnable = true;

      if (identityEventListener != null) {
        if (StringUtils.isNotBlank(identityEventListener.getEnable())) {
          isListenerEnable = Boolean.parseBoolean(identityEventListener.getEnable());
        }
      }

      IdentityMgtConfig config = IdentityMgtConfig.getInstance();

      if (isListenerEnable && config.isAuthPolicyAccountLockOnCreation()) {
        UserDTO userDTO = new UserDTO(userName);
        userDTO.setTenantId(tenantId);

        UserRecoveryDTO dto = new UserRecoveryDTO(userDTO);
        dto.setNotification(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
        dto.setNotificationType("EMAIL");

        RecoveryProcessor processor = IdentityMgtServiceComponent.getRecoveryProcessor();
        vBean = processor.updateConfirmationCode(1, userName, tenantId);

        dto.setConfirmationCode(vBean.getKey());
        NotificationDataDTO notificationDto = processor.notifyWithEmail(dto);
        vBean.setVerified(notificationDto.isNotificationSent());

        //				Send email data only if not internally managed.
        if (!(IdentityMgtConfig.getInstance().isNotificationInternallyManaged())) {
          vBean.setNotificationData(notificationDto);
        }

      } else {
        vBean.setVerified(true);
      }
    } catch (UserStoreException | IdentityException e) {
      UserIdentityManagementUtil.getCustomErrorMessages(e, userName);
      // Rollback if user exists
      try {
        if (userStoreManager.isExistingUser(userName)) {
          userStoreManager.deleteUser(userName);
        }
      } catch (org.wso2.carbon.user.core.UserStoreException e1) {
        UserIdentityManagementUtil.getCustomErrorMessages(e1, userName);
      }

      return vBean;
    }

    return vBean;
  }
  /** Process the response of the Inwebo end-point */
  @Override
  protected void processAuthenticationResponse(
      HttpServletRequest request, HttpServletResponse response, AuthenticationContext context)
      throws AuthenticationFailedException {
    int waitTime;
    int retryInterval;
    String username = null;

    // Getting the last authenticated local user
    for (Integer stepMap : context.getSequenceConfig().getStepMap().keySet())
      if (context.getSequenceConfig().getStepMap().get(stepMap).getAuthenticatedUser() != null
          && context
                  .getSequenceConfig()
                  .getStepMap()
                  .get(stepMap)
                  .getAuthenticatedAutenticator()
                  .getApplicationAuthenticator()
              instanceof LocalApplicationAuthenticator) {
        username =
            String.valueOf(
                context.getSequenceConfig().getStepMap().get(stepMap).getAuthenticatedUser());
        break;
      }
    if (username != null) {
      UserRealm userRealm = null;
      try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        RealmService realmService = IdentityTenantUtil.getRealmService();
        userRealm = (UserRealm) realmService.getTenantUserRealm(tenantId);
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (userRealm != null) {
          userId =
              userRealm
                  .getUserStoreManager()
                  .getUserClaimValue(username, InweboConstants.INWEBO_USERID, null)
                  .toString();
        } else {
          throw new AuthenticationFailedException(
              "Cannot find the user claim for the given userId: " + userId);
        }
      } catch (UserStoreException e) {
        throw new AuthenticationFailedException(
            "Error while getting the user realm" + e.getMessage(), e);
      }
    }
    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    if (authenticatorProperties != null) {
      String serviceId = authenticatorProperties.get(InweboConstants.SERVICE_ID);
      String p12file = authenticatorProperties.get(InweboConstants.INWEBO_P12FILE);
      String p12password = authenticatorProperties.get(InweboConstants.INWEBO_P12PASSWORD);
      if (!StringUtils.isEmpty(authenticatorProperties.get(InweboConstants.RETRY_COUNT))) {
        waitTime = Integer.parseInt(authenticatorProperties.get(InweboConstants.RETRY_COUNT));
      } else {
        waitTime = Integer.parseInt(InweboConstants.WAITTIME_DEFAULT);
      }
      if (!StringUtils.isEmpty(authenticatorProperties.get(InweboConstants.RETRY_INTERVAL))) {
        retryInterval =
            Integer.parseInt(authenticatorProperties.get(InweboConstants.RETRY_INTERVAL));
      } else {
        retryInterval = Integer.parseInt(InweboConstants.RETRYINTERVAL_DEFAULT);
      }
      PushRestCall push =
          new PushRestCall(serviceId, p12file, p12password, userId, waitTime, retryInterval);
      pushResponse = push.run();

      if (pushResponse.contains(InweboConstants.PUSHRESPONSE)) {
        if (log.isDebugEnabled()) {
          log.info("Authentication successful");
        }
        context.setSubject(
            AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(userId));
      } else {
        throw new AuthenticationFailedException("Authentication failed");
      }
      pushResponse = null;
      userId = null;
    } else {
      throw new AuthenticationFailedException("Required parameters are empty");
    }
  }
Пример #10
0
 public static RealmConfiguration getBootstrapRealmConfiguration() {
   return realmService.getBootstrapRealmConfiguration();
 }
Пример #11
0
 public static void buildMenuItems(HttpServletRequest request, String s, String s1, String s2) {
   int menuOrder = 50;
   if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) {
     HttpSession session = request.getSession();
     String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
     try {
       WSRegistryServiceClient registry = new WSRegistryServiceClient(s2, cookie);
       List<GovernanceArtifactConfiguration> configurations =
           GovernanceUtils.findGovernanceArtifactConfigurations(registry);
       Map<String, String> customAddUIMap = new LinkedHashMap<String, String>();
       Map<String, String> customViewUIMap = new LinkedHashMap<String, String>();
       List<Menu> userCustomMenuItemsList = new LinkedList<Menu>();
       for (GovernanceArtifactConfiguration configuration : configurations) {
         Component component = new Component();
         OMElement uiConfigurations = configuration.getUIConfigurations();
         String key = configuration.getKey();
         String configurationPath =
             RegistryConstants.CONFIG_REGISTRY_BASE_PATH
                 + RegistryConstants.GOVERNANCE_COMPONENT_PATH
                 + "/configuration/";
         String layoutStoragePath = configurationPath + key;
         RealmService realmService = registry.getRegistryContext().getRealmService();
         if (realmService
                 .getTenantUserRealm(realmService.getTenantManager().getTenantId(s1))
                 .getAuthorizationManager()
                 .isUserAuthorized(s, configurationPath, ActionConstants.PUT)
             || registry.resourceExists(layoutStoragePath)) {
           List<Menu> menuList = component.getMenusList();
           if (uiConfigurations != null) {
             ComponentBuilder.processMenus("artifactType", uiConfigurations, component);
             ComponentBuilder.processCustomUIs(uiConfigurations, component);
           }
           if (menuList.size() == 0) {
             // if no menu definitions were present, define the default ones.
             menuOrder = buildMenuList(request, configuration, menuList, key, menuOrder);
           }
           userCustomMenuItemsList.addAll(menuList);
           customAddUIMap.putAll(component.getCustomAddUIMap());
           Map<String, String> viewUIMap = component.getCustomViewUIMap();
           if (viewUIMap.isEmpty()) {
             // if no custom UI definitions were present, define the default.
             buildViewUI(configuration, viewUIMap, key);
           }
           customViewUIMap.putAll(viewUIMap);
           OMElement layout = configuration.getContentDefinition();
           if (layout != null && !registry.resourceExists(layoutStoragePath)) {
             Resource resource = registry.newResource();
             resource.setContent(RegistryUtils.encodeString(layout.toString()));
             resource.setMediaType("application/xml");
             registry.put(layoutStoragePath, resource);
           }
         }
       }
       session.setAttribute(
           MenuAdminClient.USER_CUSTOM_MENU_ITEMS,
           userCustomMenuItemsList.toArray(new Menu[userCustomMenuItemsList.size()]));
       session.setAttribute("customAddUI", customAddUIMap);
       session.setAttribute("customViewUI", customViewUIMap);
     } catch (RegistryException e) {
       log.error("unable to create connection to registry");
     } catch (org.wso2.carbon.user.api.UserStoreException e) {
       log.error("unable to realm service");
     }
   }
 }