use of org.wso2.carbon.identity.mgt.policy.PolicyViolationException in project carbon-identity-framework by wso2.
the class IdentityMgtEventListener method doPreAddUser.
/**
* This method will set the default/random password if the password provided is
* null. The thread local parameter EMPTY_PASSWORD_USED will be used to
* track if the password empty in the doPostAddUser.
* This method will filter the security question URIs from claims and put those
* to the thread local properties.
*/
@Override
public boolean doPreAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profile, UserStoreManager userStoreManager) throws UserStoreException {
if (!isEnable()) {
return true;
}
if (log.isDebugEnabled()) {
log.debug("Pre add user is called in IdentityMgtEventListener");
}
// Removing existing thread local before setting
IdentityUtil.threadLocalProperties.get().remove(EMPTY_PASSWORD_USED);
IdentityUtil.threadLocalProperties.get().remove(USER_IDENTITY_DO);
IdentityMgtConfig config = IdentityMgtConfig.getInstance();
try {
// Enforcing the password policies.
if (credential != null && (credential instanceof StringBuffer && (credential.toString().trim().length() > 0))) {
policyRegistry.enforcePasswordPolicies(credential.toString(), userName);
}
} catch (PolicyViolationException pe) {
throw new UserStoreException(pe.getMessage(), pe);
}
// empty password account creation
if (credential == null || (credential instanceof StringBuffer && (credential.toString().trim().length() < 1))) {
if (!config.isEnableTemporaryPassword()) {
log.error("Temporary password property is disabled");
throw new UserStoreException(ASK_PASSWORD_FEATURE_IS_DISABLED);
}
if (log.isDebugEnabled()) {
log.debug("Credentials are null. Using a temporary password as credentials");
}
// setting the thread-local to check in doPostAddUser
IdentityUtil.threadLocalProperties.get().put(EMPTY_PASSWORD_USED, true);
// temporary passwords will be used
char[] temporaryPassword = null;
temporaryPassword = UserIdentityManagementUtil.generateTemporaryPassword();
// setting the password value
((StringBuffer) credential).replace(0, temporaryPassword.length, new String(temporaryPassword));
}
// Filtering security question URIs from claims and add them to the thread local dto
Map<String, String> userDataMap = new HashMap<String, String>();
// TODO why challenge Q
Iterator<Entry<String, String>> it = claims.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> claim = it.next();
if (claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI) || claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
userDataMap.put(claim.getKey(), claim.getValue());
it.remove();
}
}
UserIdentityClaimsDO identityDTO = new UserIdentityClaimsDO(userName, userDataMap);
identityDTO.setTenantId(userStoreManager.getTenantId());
// adding dto to thread local to be read again from the doPostAddUser method
IdentityUtil.threadLocalProperties.get().put(USER_IDENTITY_DO, identityDTO);
return true;
}
use of org.wso2.carbon.identity.mgt.policy.PolicyViolationException in project identity-governance by wso2-extensions.
the class UserSelfRegistrationManager method registerUser.
public NotificationResponseBean registerUser(User user, String password, Claim[] claims, Property[] properties) throws IdentityRecoveryException {
publishEvent(user, claims, properties, IdentityEventConstants.Event.PRE_SELF_SIGNUP_REGISTER);
String consent = getPropertyValue(properties, IdentityRecoveryConstants.Consent.CONSENT);
String tenantDomain = user.getTenantDomain();
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
// Callback URL validation
String callbackURL = null;
try {
callbackURL = Utils.getCallbackURLFromRegistration(properties);
if (StringUtils.isNotBlank(callbackURL) && !Utils.validateCallbackURL(callbackURL, tenantDomain, IdentityRecoveryConstants.ConnectorConfig.SELF_REGISTRATION_CALLBACK_REGEX)) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CALLBACK_URL_NOT_VALID, callbackURL);
}
} catch (MalformedURLException | UnsupportedEncodingException | IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CALLBACK_URL_NOT_VALID, callbackURL);
}
if (StringUtils.isBlank(user.getTenantDomain())) {
user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
log.info("registerUser :Tenant domain is not in the request. set to default for user : " + user.getUserName());
}
if (StringUtils.isBlank(user.getUserStoreDomain())) {
user.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
log.info("registerUser :User store domain is not in the request. set to default for user : " + user.getUserName());
}
boolean enable = Boolean.parseBoolean(Utils.getSignUpConfigs(IdentityRecoveryConstants.ConnectorConfig.ENABLE_SELF_SIGNUP, user.getTenantDomain()));
if (!enable) {
throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_DISABLE_SELF_SIGN_UP, user.getUserName());
}
NotificationResponseBean notificationResponseBean;
try {
RealmService realmService = IdentityRecoveryServiceDataHolder.getInstance().getRealmService();
UserStoreManager userStoreManager;
try {
userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(user.getTenantDomain())).getUserStoreManager();
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, user.getUserName(), e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(IdentityTenantUtil.getTenantId(user.getTenantDomain()));
carbonContext.setTenantDomain(user.getTenantDomain());
Map<String, String> claimsMap = new HashMap<>();
for (Claim claim : claims) {
claimsMap.put(claim.getClaimUri(), claim.getValue());
}
// Set arbitrary properties to use in UserSelfRegistrationHandler
Utils.setArbitraryProperties(properties);
validateAndFilterFromReceipt(consent, claimsMap);
// User preferred notification channel.
String preferredChannel;
try {
// TODO It is required to add this role before tenant creation. And also, this role should not not be able remove.
if (!userStoreManager.isExistingRole(IdentityRecoveryConstants.SELF_SIGNUP_ROLE)) {
Permission permission = new Permission("/permission/admin/login", IdentityRecoveryConstants.EXECUTE_ACTION);
userStoreManager.addRole(IdentityRecoveryConstants.SELF_SIGNUP_ROLE, null, new Permission[] { permission });
}
String[] userRoles = new String[] { IdentityRecoveryConstants.SELF_SIGNUP_ROLE };
try {
NotificationChannelManager notificationChannelManager = Utils.getNotificationChannelManager();
preferredChannel = notificationChannelManager.resolveCommunicationChannel(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain(), claimsMap);
} catch (NotificationChannelManagerException e) {
throw mapNotificationChannelManagerException(e, user);
}
// resolved channel is not empty.
if (StringUtils.isEmpty(claimsMap.get(IdentityRecoveryConstants.PREFERRED_CHANNEL_CLAIM)) && StringUtils.isNotEmpty(preferredChannel)) {
claimsMap.put(IdentityRecoveryConstants.PREFERRED_CHANNEL_CLAIM, preferredChannel);
}
userStoreManager.addUser(IdentityUtil.addDomainToName(user.getUserName(), user.getUserStoreDomain()), password, userRoles, claimsMap, null);
} catch (UserStoreException e) {
Throwable cause = e;
while (cause != null) {
if (cause instanceof PolicyViolationException) {
throw IdentityException.error(IdentityRecoveryClientException.class, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_POLICY_VIOLATION.getCode(), cause.getMessage(), e);
}
cause = cause.getCause();
}
Utils.checkPasswordPatternViolation(e, user);
return handleClientException(user, e);
}
addUserConsent(consent, tenantDomain);
// Build the notification response.
notificationResponseBean = buildNotificationResponseBean(user, preferredChannel, claimsMap);
} finally {
Utils.clearArbitraryProperties();
PrivilegedCarbonContext.endTenantFlow();
}
publishEvent(user, claims, properties, IdentityEventConstants.Event.POST_SELF_SIGNUP_REGISTER);
return notificationResponseBean;
}
use of org.wso2.carbon.identity.mgt.policy.PolicyViolationException in project identity-governance by wso2-extensions.
the class UserSelfRegistrationManager method registerLiteUser.
public NotificationResponseBean registerLiteUser(User user, Claim[] claims, Property[] properties) throws IdentityRecoveryException {
String consent = getPropertyValue(properties, IdentityRecoveryConstants.Consent.CONSENT);
String tenantDomain = user.getTenantDomain();
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
// Callback URL validation
String callbackURL = null;
try {
callbackURL = Utils.getCallbackURLFromRegistration(properties);
if (StringUtils.isNotBlank(callbackURL) && !Utils.validateCallbackURL(callbackURL, tenantDomain, IdentityRecoveryConstants.ConnectorConfig.SELF_REGISTRATION_CALLBACK_REGEX)) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CALLBACK_URL_NOT_VALID, callbackURL);
}
} catch (MalformedURLException | UnsupportedEncodingException | IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CALLBACK_URL_NOT_VALID, callbackURL);
}
if (StringUtils.isBlank(user.getTenantDomain())) {
user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
log.info("registerUser :Tenant domain is not in the request. set to default for user : " + user.getUserName());
}
if (StringUtils.isBlank(user.getUserStoreDomain())) {
user.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
log.info("registerUser :User store domain is not in the request. set to default for user : " + user.getUserName());
}
boolean enable = Boolean.parseBoolean(Utils.getSignUpConfigs(IdentityRecoveryConstants.ConnectorConfig.ENABLE_LITE_SIGN_UP, user.getTenantDomain()));
if (!enable) {
throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_DISABLE_LITE_SIGN_UP, user.getUserName());
}
NotificationResponseBean notificationResponseBean;
try {
RealmService realmService = IdentityRecoveryServiceDataHolder.getInstance().getRealmService();
UserStoreManager userStoreManager;
try {
userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(user.getTenantDomain())).getUserStoreManager();
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, user.getUserName(), e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(IdentityTenantUtil.getTenantId(user.getTenantDomain()));
carbonContext.setTenantDomain(user.getTenantDomain());
Map<String, String> claimsMap = new HashMap<>();
for (Claim claim : claims) {
claimsMap.put(claim.getClaimUri(), claim.getValue());
}
// Set lite user sign up claim to indicate the profile
claimsMap.put(IdentityRecoveryConstants.LITE_USER_CLAIM, Boolean.TRUE.toString());
// Set arbitrary properties to use in UserSelfRegistrationHandler
Utils.setArbitraryProperties(properties);
validateAndFilterFromReceipt(consent, claimsMap);
// User preferred notification channel.
String preferredChannel;
try {
String[] userRoles = new String[] {};
try {
NotificationChannelManager notificationChannelManager = Utils.getNotificationChannelManager();
preferredChannel = notificationChannelManager.resolveCommunicationChannel(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain(), claimsMap);
} catch (NotificationChannelManagerException e) {
throw mapNotificationChannelManagerException(e, user);
}
// resolved channel is not empty.
if (StringUtils.isEmpty(claimsMap.get(IdentityRecoveryConstants.PREFERRED_CHANNEL_CLAIM)) && StringUtils.isNotEmpty(preferredChannel)) {
claimsMap.put(IdentityRecoveryConstants.PREFERRED_CHANNEL_CLAIM, preferredChannel);
}
userStoreManager.addUser(IdentityUtil.addDomainToName(user.getUserName(), user.getUserStoreDomain()), Utils.generateRandomPassword(12), userRoles, claimsMap, null);
} catch (UserStoreException e) {
Throwable cause = e;
while (cause != null) {
if (cause instanceof PolicyViolationException) {
throw IdentityException.error(IdentityRecoveryClientException.class, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_POLICY_VIOLATION.getCode(), cause.getMessage(), e);
}
cause = cause.getCause();
}
return handleClientException(user, e);
}
addUserConsent(consent, tenantDomain);
// Build the notification response for lite user.
notificationResponseBean = buildLiteNotificationResponseBean(user, preferredChannel, claimsMap);
} finally {
Utils.clearArbitraryProperties();
PrivilegedCarbonContext.endTenantFlow();
}
return notificationResponseBean;
}
use of org.wso2.carbon.identity.mgt.policy.PolicyViolationException in project identity-governance by wso2-extensions.
the class PasswordPolicyValidationHandler method handleEvent.
@Override
public void handleEvent(Event event) throws IdentityEventException {
// Skip password policy validation if skipPasswordPatternValidation thread local is set to true.
if (UserCoreUtil.getSkipPasswordPatternValidationThreadLocal()) {
return;
}
Map<String, Object> eventProperties = event.getEventProperties();
String userName = (String) eventProperties.get(IdentityEventConstants.EventProperty.USER_NAME);
String tenantDomain = (String) eventProperties.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
Object credentials = eventProperties.get(IdentityEventConstants.EventProperty.CREDENTIAL);
Property[] identityProperties;
try {
identityProperties = IdentityPasswordPolicyServiceDataHolder.getInstance().getIdentityGovernanceService().getConfiguration(getPropertyNames(), tenantDomain);
} catch (IdentityGovernanceException e) {
throw new IdentityEventException("Error while retrieving password policy properties.", e);
}
// initialize to default values
boolean passwordPolicyValidation;
String pwMinLength = "6";
String pwMaxLength = "12";
String pwPattern = "^((?=.*\\\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])).{0,100}$";
String errorMsg = "Password pattern policy violated. Password should contain a digit[0-9], a lower case " + "letter[a-z], an upper case letter[A-Z], one of !@#$%&* characters";
for (Property identityProperty : identityProperties) {
if (identityProperty == null) {
continue;
}
String propertyName = identityProperty.getName();
String propertyValue = identityProperty.getValue();
if (PasswordPolicyConstants.PW_POLICY_ENABLE.equals(propertyName)) {
passwordPolicyValidation = BooleanUtils.toBoolean(propertyValue);
if (!passwordPolicyValidation) {
if (log.isDebugEnabled()) {
log.debug("Password Policy validation is disabled");
}
return;
}
} else if (PasswordPolicyConstants.PW_POLICY_MIN_LENGTH.equals(propertyName)) {
if (NumberUtils.isNumber(propertyValue) && Integer.parseInt(propertyValue) > 0) {
pwMinLength = propertyValue;
} else {
log.warn("Password Policy MIN Length is not correct hence using default value: " + pwMinLength);
}
} else if (PasswordPolicyConstants.PW_POLICY_MAX_LENGTH.equals(propertyName)) {
if (NumberUtils.isNumber(propertyValue) && Integer.parseInt(propertyValue) > 0) {
pwMaxLength = propertyValue;
} else {
log.warn("Password Policy MAX Length is not correct hence using default value: " + pwMaxLength);
}
} else if (PasswordPolicyConstants.PW_POLICY_PATTERN.equals(propertyName)) {
if (StringUtils.isNotBlank(propertyValue)) {
pwPattern = propertyValue;
} else {
log.warn("Password Policy Pattern is not correct hence using default value: " + pwPattern);
}
} else if (PasswordPolicyConstants.PW_POLICY_ERROR_MSG.equals(propertyName)) {
if (StringUtils.isNotBlank(propertyValue)) {
errorMsg = propertyValue;
} else {
log.warn("Password Policy Error Msg cannot be Empty hence using default Msg: " + errorMsg);
}
}
}
PolicyRegistry policyRegistry = new PolicyRegistry();
String pwLengthPolicyCls = configs.getModuleProperties().getProperty(PasswordPolicyConstants.PW_POLICY_LENGTH_CLASS);
String pwNamePolicyCls = configs.getModuleProperties().getProperty(PasswordPolicyConstants.PW_POLICY_NAME_CLASS);
String pwPatternPolicyCls = configs.getModuleProperties().getProperty(PasswordPolicyConstants.PW_POLICY_PATTERN_CLASS);
try {
if (StringUtils.isNotBlank(pwLengthPolicyCls)) {
DefaultPasswordLengthPolicy defaultPasswordLengthPolicy = (DefaultPasswordLengthPolicy) Class.forName(pwLengthPolicyCls).newInstance();
HashMap pwPolicyLengthParams = new HashMap<String, String>();
pwPolicyLengthParams.put("min.length", pwMinLength);
pwPolicyLengthParams.put("max.length", pwMaxLength);
defaultPasswordLengthPolicy.init(pwPolicyLengthParams);
policyRegistry.addPolicy(defaultPasswordLengthPolicy);
}
if (StringUtils.isNotBlank(pwNamePolicyCls)) {
DefaultPasswordNamePolicy defaultPasswordNamePolicy = (DefaultPasswordNamePolicy) Class.forName(pwNamePolicyCls).newInstance();
policyRegistry.addPolicy(defaultPasswordNamePolicy);
}
if (StringUtils.isNotBlank(pwPatternPolicyCls)) {
DefaultPasswordPatternPolicy defaultPasswordPatternPolicy = (DefaultPasswordPatternPolicy) Class.forName(pwPatternPolicyCls).newInstance();
HashMap pwPolicyPatternParams = new HashMap<String, String>();
pwPolicyPatternParams.put("pattern", pwPattern);
pwPolicyPatternParams.put("errorMsg", errorMsg);
defaultPasswordPatternPolicy.init(pwPolicyPatternParams);
policyRegistry.addPolicy(defaultPasswordPatternPolicy);
}
} catch (Exception e) {
throw Utils.handleEventException(PasswordPolicyConstants.ErrorMessages.ERROR_CODE_LOADING_PASSWORD_POLICY_CLASSES, null, e);
}
try {
policyRegistry.enforcePasswordPolicies(credentials.toString(), userName);
} catch (PolicyViolationException e) {
throw Utils.handleEventException(PasswordPolicyConstants.ErrorMessages.ERROR_CODE_VALIDATING_PASSWORD_POLICY, e.getMessage(), e);
}
}
Aggregations