use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultRequestPathBasedSequenceHandler method handlePostAuthentication.
protected void handlePostAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {
if (log.isDebugEnabled()) {
log.debug("Handling Post Authentication tasks");
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
Map<String, String> mappedAttrs;
StringBuilder jsonBuilder = new StringBuilder();
// build the authenticated idps JWT to send to the calling servlet.
jsonBuilder.append("\"idps\":");
jsonBuilder.append("[");
// build the JSON object for this step
jsonBuilder.append("{");
jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
jsonBuilder.append("\"authenticator\":\"").append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator().getName()).append("\"");
// wrap up the JSON object
jsonBuilder.append("}");
jsonBuilder.append("]");
sequenceConfig.setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder.toString(), sequenceConfig.getApplicationConfig().getServiceProvider()));
mappedAttrs = handleClaimMappings(context);
String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
String roleAttr = mappedAttrs.get(spRoleUri);
if (StringUtils.isNotBlank(roleAttr)) {
String[] roles = roleAttr.split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()));
mappedAttrs.put(spRoleUri, getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
}
sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));
if (StringUtils.isNotBlank(context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri())) {
Map<String, String> unfilteredClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
String subjectClaimUri = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim();
String subjectClaimValue;
if (unfilteredClaimValues != null) {
subjectClaimValue = unfilteredClaimValues.get(subjectClaimUri);
} else {
subjectClaimValue = mappedAttrs.get(subjectClaimUri);
}
if (subjectClaimValue != null) {
AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
authenticatedUser.setAuthenticatedSubjectIdentifier(subjectClaimValue);
if (log.isDebugEnabled()) {
log.debug("Authenticated User: " + sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
}
}
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class IdentityMgtEventListener method doPostAuthenticate.
/**
* This method locks the accounts after a configured number of
* authentication failure attempts. And unlocks accounts based on successful
* authentications.
*/
@Override
public boolean doPostAuthenticate(String userName, boolean authenticated, UserStoreManager userStoreManager) throws UserStoreException {
if (!isEnable()) {
return true;
}
IdentityUtil.threadLocalProperties.get().remove(IdentityCoreConstants.USER_ACCOUNT_STATE);
String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
String usernameWithDomain = IdentityUtil.addDomainToName(userName, domainName);
boolean isUserExistInCurrentDomain = userStoreManager.isExistingUser(usernameWithDomain);
if (authenticated && isUserExistInCurrentDomain) {
if (isUserExistInCurrentDomain) {
UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);
userIdentityDTO.setLastLogonTime(System.currentTimeMillis());
try {
module.store(userIdentityDTO, userStoreManager);
} catch (IdentityException e) {
throw new UserStoreException(String.format("Error while saving user store data : %s for user : %s.", UserIdentityDataStore.LAST_LOGON_TIME, userName), e);
}
}
}
// Top level try and finally blocks are used to unset thread local variables
try {
if (!IdentityUtil.threadLocalProperties.get().containsKey(DO_POST_AUTHENTICATE)) {
IdentityUtil.threadLocalProperties.get().put(DO_POST_AUTHENTICATE, true);
if (log.isDebugEnabled()) {
log.debug("Post authenticator is called in IdentityMgtEventListener");
}
IdentityMgtConfig config = IdentityMgtConfig.getInstance();
if (!config.isEnableAuthPolicy()) {
return true;
}
UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);
if (userIdentityDTO == null) {
userIdentityDTO = new UserIdentityClaimsDO(userName);
userIdentityDTO.setTenantId(userStoreManager.getTenantId());
}
boolean userOTPEnabled = userIdentityDTO.getOneTimeLogin();
// One time password check
if (authenticated && config.isAuthPolicyOneTimePasswordCheck() && (!userStoreManager.isReadOnly()) && userOTPEnabled) {
// reset password of the user and notify user of the new password
String password = new String(UserIdentityManagementUtil.generateTemporaryPassword());
userStoreManager.updateCredentialByAdmin(userName, password);
// Get email user claim value
String email = userStoreManager.getUserClaimValue(userName, UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS, null);
if (StringUtils.isBlank(email)) {
throw new UserStoreException("No user email provided for user : " + userName);
}
List<NotificationSendingModule> notificationModules = config.getNotificationSendingModules();
if (notificationModules != null) {
NotificationDataDTO notificationData = new NotificationDataDTO();
if (MessageContext.getCurrentMessageContext() != null && MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS) != null) {
Map<String, String> transportHeaderMap = (Map) MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS);
if (MapUtils.isNotEmpty(transportHeaderMap)) {
TransportHeader[] transportHeadersArray = new TransportHeader[transportHeaderMap.size()];
int i = 0;
for (Map.Entry<String, String> entry : transportHeaderMap.entrySet()) {
TransportHeader transportHeader = new TransportHeader();
transportHeader.setHeaderName(entry.getKey());
transportHeader.setHeaderValue(entry.getValue());
transportHeadersArray[i] = transportHeader;
++i;
}
notificationData.setTransportHeaders(transportHeadersArray);
}
}
NotificationData emailNotificationData = new NotificationData();
String emailTemplate = null;
int tenantId = userStoreManager.getTenantId();
String firstName = null;
String userStoreDomain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
String domainSpecificUserName = UserCoreUtil.addDomainToName(userName, userStoreDomain);
String tenantDomain = IdentityTenantUtil.getTenantDomain(userStoreManager.getTenantId());
try {
firstName = Utils.getClaimFromUserStoreManager(domainSpecificUserName, tenantId, UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
} catch (IdentityException e2) {
throw new UserStoreException("Could not load user given name", e2);
}
emailNotificationData.setTagData("first-name", firstName);
emailNotificationData.setTagData("user-name", userName);
emailNotificationData.setTagData("otp-password", password);
emailNotificationData.setTagData("userstore-domain", userStoreDomain);
emailNotificationData.setTagData("tenant-domain", tenantDomain);
emailNotificationData.setSendTo(email);
Config emailConfig = null;
ConfigBuilder configBuilder = ConfigBuilder.getInstance();
try {
emailConfig = configBuilder.loadConfiguration(ConfigType.EMAIL, StorageType.REGISTRY, tenantId);
} catch (Exception e1) {
throw new UserStoreException("Could not load the email template configuration for user : " + userName, e1);
}
emailTemplate = emailConfig.getProperty("otp");
Notification emailNotification = null;
try {
emailNotification = NotificationBuilder.createNotification(EMAIL_NOTIFICATION_TYPE, emailTemplate, emailNotificationData);
} catch (Exception e) {
throw new UserStoreException("Could not create the email notification for template: " + emailTemplate, e);
}
NotificationSender sender = new NotificationSender();
for (NotificationSendingModule notificationSendingModule : notificationModules) {
if (IdentityMgtConfig.getInstance().isNotificationInternallyManaged()) {
notificationSendingModule.setNotificationData(notificationData);
notificationSendingModule.setNotification(emailNotification);
sender.sendNotification(notificationSendingModule);
notificationData.setNotificationSent(true);
}
}
} else {
throw new UserStoreException("No notification modules configured");
}
}
// Password expire check. Not for OTP enabled users.
if (authenticated && config.isAuthPolicyExpirePasswordCheck() && !userOTPEnabled && (!userStoreManager.isReadOnly())) {
// TODO - password expire impl
// Refactor adduser and change password api to stamp the time
// Check user's expire time in the claim
// if expired redirect to change password
// else pass through
}
if (!authenticated && config.isAuthPolicyAccountLockOnFailure()) {
// reading the max allowed #of failure attempts
if (isUserExistInCurrentDomain) {
userIdentityDTO.setFailAttempts();
if (userIdentityDTO.getFailAttempts() >= config.getAuthPolicyMaxLoginAttempts()) {
log.info("User, " + userName + " has exceed the max failed login attempts. " + "User account would be locked");
IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.USER_IS_LOCKED + ":" + IdentityMgtConstants.LockedReason.MAX_ATTEMTS_EXCEEDED.toString(), userIdentityDTO.getFailAttempts(), config.getAuthPolicyMaxLoginAttempts());
IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
IdentityUtil.threadLocalProperties.get().put(IdentityCoreConstants.USER_ACCOUNT_STATE, UserCoreConstants.ErrorCode.USER_IS_LOCKED);
if (log.isDebugEnabled()) {
log.debug("Username :" + userName + "Exceeded the maximum login attempts. User locked, ErrorCode :" + UserCoreConstants.ErrorCode.USER_IS_LOCKED);
}
userIdentityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, IdentityMgtConstants.LockedReason.MAX_ATTEMTS_EXCEEDED.toString());
userIdentityDTO.setAccountLock(true);
userIdentityDTO.setFailAttempts(0);
// lock time from the config
int lockTime = IdentityMgtConfig.getInstance().getAuthPolicyLockingTime();
if (lockTime != 0) {
userIdentityDTO.setUnlockTime(System.currentTimeMillis() + (lockTime * 60 * 1000L));
}
} else {
IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.INVALID_CREDENTIAL, userIdentityDTO.getFailAttempts(), config.getAuthPolicyMaxLoginAttempts());
IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
if (log.isDebugEnabled()) {
log.debug("Username :" + userName + "Invalid Credential, ErrorCode :" + UserCoreConstants.ErrorCode.INVALID_CREDENTIAL);
}
}
try {
module.store(userIdentityDTO, userStoreManager);
} catch (IdentityException e) {
throw new UserStoreException("Error while saving user store data for user : " + userName, e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("User, " + userName + " is not exists in " + domainName);
}
}
} else {
// the unlock the account and reset the number of failedAttempts
if (userIdentityDTO.isAccountLocked() || userIdentityDTO.getFailAttempts() > 0 || userIdentityDTO.getAccountLock()) {
userIdentityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, "");
userIdentityDTO.setAccountLock(false);
userIdentityDTO.setFailAttempts(0);
userIdentityDTO.setUnlockTime(0);
try {
module.store(userIdentityDTO, userStoreManager);
} catch (IdentityException e) {
throw new UserStoreException("Error while saving user store data for user : " + userName, e);
}
}
}
}
return true;
} finally {
// Remove thread local variable
IdentityUtil.threadLocalProperties.get().remove(DO_POST_AUTHENTICATE);
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultApplicationValidator method validateLocalAndOutBoundAuthenticationConfig.
/**
* Validate local and outbound authenticator related configurations and append to the validation msg list.
*
* @param validationMsg validation error messages
* @param localAndOutBoundAuthenticationConfig local and out bound authentication config
* @param tenantDomain tenant domain
* @throws IdentityApplicationManagementException Identity Application Management Exception when unable to get the
* authenticator params
*/
private void validateLocalAndOutBoundAuthenticationConfig(List<String> validationMsg, LocalAndOutboundAuthenticationConfig localAndOutBoundAuthenticationConfig, String tenantDomain) throws IdentityApplicationManagementException {
if (localAndOutBoundAuthenticationConfig == null) {
return;
}
AuthenticationStep[] authenticationSteps = localAndOutBoundAuthenticationConfig.getAuthenticationSteps();
if (authenticationSteps == null || authenticationSteps.length == 0) {
return;
}
ApplicationManagementService applicationMgtService = ApplicationManagementService.getInstance();
Map<String, Property[]> allLocalAuthenticators = Arrays.stream(applicationMgtService.getAllLocalAuthenticators(tenantDomain)).collect(Collectors.toMap(LocalAuthenticatorConfig::getName, LocalAuthenticatorConfig::getProperties));
AtomicBoolean isAuthenticatorIncluded = new AtomicBoolean(false);
for (AuthenticationStep authenticationStep : authenticationSteps) {
for (IdentityProvider idp : authenticationStep.getFederatedIdentityProviders()) {
validateFederatedIdp(idp, isAuthenticatorIncluded, validationMsg, tenantDomain);
}
for (LocalAuthenticatorConfig localAuth : authenticationStep.getLocalAuthenticatorConfigs()) {
if (!allLocalAuthenticators.containsKey(localAuth.getName())) {
validationMsg.add(String.format(AUTHENTICATOR_NOT_AVAILABLE, localAuth.getName()));
} else if (!isAuthenticatorIncluded.get()) {
Property[] properties = allLocalAuthenticators.get(localAuth.getName());
if (properties.length == 0) {
isAuthenticatorIncluded.set(true);
} else {
for (Property property : properties) {
if (!(IS_HANDLER.equals(property.getName()) && Boolean.parseBoolean(property.getValue()))) {
isAuthenticatorIncluded.set(true);
}
}
}
}
}
}
if (!isAuthenticatorIncluded.get()) {
validationMsg.add("No authenticator have been registered in the authentication flow.");
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class ApplicationManagementServiceImplTest method addApplicationConfigurations.
private void addApplicationConfigurations(ServiceProvider serviceProvider) {
serviceProvider.setDescription("Created for testing");
serviceProvider.setSaasApp(TRUE);
// Inbound Authentication Configurations.
InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
InboundAuthenticationRequestConfig authRequestConfig = new InboundAuthenticationRequestConfig();
authRequestConfig.setInboundAuthKey("auth key");
authRequestConfig.setInboundAuthType("oauth2");
InboundAuthenticationRequestConfig[] authRequests = new InboundAuthenticationRequestConfig[] { authRequestConfig };
inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(authRequests);
serviceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
// Inbound Provisioning Configurations.
InboundProvisioningConfig provisioningConfig = new InboundProvisioningConfig();
provisioningConfig.setProvisioningUserStore("UserStore");
serviceProvider.setInboundProvisioningConfig(provisioningConfig);
// OutBound Provisioning Configurations.
IdentityProvider provisioningIdP = new IdentityProvider();
provisioningIdP.setIdentityProviderName("Provisioning IdP");
OutboundProvisioningConfig outboundProvisioningConfig = new OutboundProvisioningConfig();
outboundProvisioningConfig.setProvisioningIdentityProviders(new IdentityProvider[] { provisioningIdP });
ProvisioningConnectorConfig provisioningConnectorConfig = new ProvisioningConnectorConfig();
provisioningConnectorConfig.setName("Provisioning connector");
provisioningIdP.setDefaultProvisioningConnectorConfig(provisioningConnectorConfig);
serviceProvider.setOutboundProvisioningConfig(outboundProvisioningConfig);
// Local And OutBound Authentication Configuration.
LocalAndOutboundAuthenticationConfig authenticationConfig = new LocalAndOutboundAuthenticationConfig();
AuthenticationStep authenticationStep = new AuthenticationStep();
IdentityProvider identityProvider = new IdentityProvider();
identityProvider.setIdentityProviderName(IDP_NAME_1);
FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig();
federatedAuthenticatorConfig.setName("Federated authenticator");
identityProvider.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[] { federatedAuthenticatorConfig });
authenticationStep.setFederatedIdentityProviders(new IdentityProvider[] { identityProvider });
LocalAuthenticatorConfig localAuthenticatorConfig = new LocalAuthenticatorConfig();
localAuthenticatorConfig.setName("Local authenticator");
authenticationStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[] { localAuthenticatorConfig });
authenticationConfig.setAuthenticationSteps(new AuthenticationStep[] { authenticationStep });
serviceProvider.setLocalAndOutBoundAuthenticationConfig(authenticationConfig);
// Request Path Authenticator Configuration.
RequestPathAuthenticatorConfig requestPathAuthenticatorConfig = new RequestPathAuthenticatorConfig();
requestPathAuthenticatorConfig.setName("Request path authenticator");
serviceProvider.setRequestPathAuthenticatorConfigs(new RequestPathAuthenticatorConfig[] { requestPathAuthenticatorConfig });
// Claim Configurations.
ClaimConfig claimConfig = new ClaimConfig();
claimConfig.setRoleClaimURI("Role claim uri");
claimConfig.setSpClaimDialects(new String[] { "SP claim dialect" });
ClaimMapping claimMapping = new ClaimMapping();
Claim localClaim = new Claim();
localClaim.setClaimUri("Local claim uri");
Claim remoteClaim = new Claim();
remoteClaim.setClaimUri("Remote claim uri");
claimMapping.setLocalClaim(localClaim);
claimMapping.setRemoteClaim(remoteClaim);
claimConfig.setClaimMappings(new ClaimMapping[] { claimMapping });
serviceProvider.setClaimConfig(claimConfig);
// Permission Role Configurations.
PermissionsAndRoleConfig permissionsAndRoleConfig = new PermissionsAndRoleConfig();
RoleMapping roleMapping = new RoleMapping();
LocalRole localRole = new LocalRole("Local role");
roleMapping.setLocalRole(localRole);
roleMapping.setRemoteRole("Remote role");
RoleMapping[] roleMappings = new RoleMapping[] { roleMapping };
permissionsAndRoleConfig.setRoleMappings(roleMappings);
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultAuthSeqMgtServiceImpl method validateAuthSeqConfiguration.
private void validateAuthSeqConfiguration(DefaultAuthenticationSequence sequence, String tenantDomain, String errorMsg) throws DefaultAuthSeqMgtException {
List<String> validationMsg = new ArrayList<>();
LocalAndOutboundAuthenticationConfig authenticationConfig = sequence.getContent();
if (authenticationConfig == null) {
return;
}
AuthenticationStep[] authenticationSteps = authenticationConfig.getAuthenticationSteps();
if (authenticationSteps == null || authenticationSteps.length == 0) {
return;
}
Map<String, Property[]> allLocalAuthenticators;
try {
allLocalAuthenticators = getAllLocalAuthenticators(tenantDomain);
} catch (IdentityApplicationManagementException e) {
throw new DefaultAuthSeqMgtServerException(errorMsg, e);
}
AtomicBoolean isAuthenticatorIncluded = new AtomicBoolean(false);
for (AuthenticationStep authenticationStep : authenticationSteps) {
if (authenticationStep == null || (authenticationStep.getFederatedIdentityProviders() == null && authenticationStep.getLocalAuthenticatorConfigs() == null)) {
validationMsg.add("Some authentication steps do not have authenticators.");
break;
}
for (IdentityProvider idp : authenticationStep.getFederatedIdentityProviders()) {
validateFederatedIdp(idp, isAuthenticatorIncluded, validationMsg, tenantDomain);
}
validateLocalAuthenticatorConfig(validationMsg, allLocalAuthenticators, isAuthenticatorIncluded, authenticationStep);
}
if (!isAuthenticatorIncluded.get()) {
validationMsg.add("No authenticator have been registered in the authentication flow.");
}
if (!validationMsg.isEmpty()) {
log.error(errorMsg + tenantDomain);
for (String msg : validationMsg) {
log.error(msg);
}
throw new DefaultAuthSeqMgtException(validationMsg.toArray(new String[0]));
}
removeUnsupportedConfigurations(authenticationConfig);
}
Aggregations