use of org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException in project studio by craftercms.
the class AuthenticationChainImpl method doAuthenticate.
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, String username, String password) throws Exception {
boolean authenticated = false;
Iterator<AuthenticationProvider> iterator = authenticationChain.iterator();
Exception lastError = null;
while (iterator.hasNext()) {
AuthenticationProvider authProvider = iterator.next();
if (authProvider.isEnabled()) {
try {
authenticated = authProvider.doAuthenticate(request, response, this, username, password);
} catch (Exception e) {
lastError = e;
}
if (authenticated)
break;
}
}
String ipAddress = request.getRemoteAddr();
SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
if (authenticated) {
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_LOGIN);
auditLog.setActorId(username);
auditLog.setSiteId(siteFeed.getId());
auditLog.setPrimaryTargetId(username);
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(username);
auditServiceInternal.insertAuditLog(auditLog);
logger.info("User " + username + " logged in from IP: " + ipAddress);
} else {
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_LOGIN_FAILED);
auditLog.setActorId(username);
auditLog.setSiteId(siteFeed.getId());
auditLog.setPrimaryTargetId(StringUtils.isEmpty(username) ? StringUtils.EMPTY : username);
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(username);
auditServiceInternal.insertAuditLog(auditLog);
logger.info("Failed to authenticate user " + username + " logging in from IP: " + ipAddress);
if (lastError == null) {
lastError = new AuthenticationSystemException("Unknown service error");
}
throw lastError;
}
return authenticated;
}
use of org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException in project studio by craftercms.
the class DbAuthenticationProvider method doAuthenticate.
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationChain authenticationChain, String username, String password) throws AuthenticationSystemException, BadCredentialsException {
Map<String, Object> params = new HashMap<String, Object>();
params.put(USER_ID, -1);
params.put(USERNAME, username);
User user = null;
UserDAO userDao = authenticationChain.getUserDao();
try {
user = userDao.getUserByIdOrUsername(params);
} catch (Exception e) {
logger.debug("Unknown database error", e);
throw new AuthenticationSystemException("Unknown database error", e);
}
if (user != null && !user.isDeleted() && user.isEnabled() && CryptoUtils.matchPassword(user.getPassword(), password)) {
String token = createToken(user, authenticationChain);
storeAuthentication(new Authentication(username, token, AuthenticationType.DB));
return true;
} else {
throw new BadCredentialsException();
}
}
use of org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException in project studio by craftercms.
the class HeadersAuthenticationProvider method doAuthenticate.
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationChain authenticationChain, String username, String password) throws AuthenticationSystemException, UserNotFoundException {
if (isEnabled()) {
logger.debug("Authenticating user using authentication headers.");
RequestContext requestContext = RequestContext.getCurrent();
if (requestContext != null) {
String securekeyHeader = request.getHeader(secureKeyHeader);
logger.debug("Verifying authentication header secure key.");
if (StringUtils.equals(securekeyHeader, secureKeyHeaderValue)) {
String usernameHeaderValue = request.getHeader(usernameHeader);
String firstName = request.getHeader(firstNameHeader);
String lastName = request.getHeader(lastNameHeader);
String email = request.getHeader(emailHeader);
String groups = request.getHeader(groupsHeader);
try {
UserServiceInternal userServiceInternal = authenticationChain.getUserServiceInternal();
AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
SiteService siteService = authenticationChain.getSiteService();
SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
if (userServiceInternal.userExists(-1, usernameHeaderValue)) {
User user = userServiceInternal.getUserByIdOrUsername(-1, usernameHeaderValue);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
if (StringUtils.isNoneEmpty(firstName, lastName, email)) {
logger.debug("If user already exists in studio DB, update details.");
try {
userServiceInternal.updateUser(user);
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_UPDATE);
auditLog.setActorId(usernameHeaderValue);
auditLog.setSiteId(siteFeed.getId());
auditLog.setPrimaryTargetId(usernameHeaderValue);
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(user.getUsername());
auditServiceInternal.insertAuditLog(auditLog);
} catch (Exception e) {
logger.debug("Error updating user " + usernameHeaderValue + " with data from authentication headers", e);
throw new AuthenticationSystemException("Error updating user " + usernameHeaderValue + " with data from " + "external authentication provider", e);
}
}
} else {
logger.debug("User does not exist in studio db. Adding user " + usernameHeader);
try {
User user = new User();
user.setUsername(usernameHeaderValue);
user.setPassword(UUID.randomUUID().toString());
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setExternallyManaged(true);
user.setEnabled(true);
userServiceInternal.createUser(user);
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_CREATE);
auditLog.setSiteId(siteFeed.getId());
auditLog.setActorId(usernameHeaderValue);
auditLog.setPrimaryTargetId(usernameHeaderValue);
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(user.getUsername());
auditServiceInternal.insertAuditLog(auditLog);
} catch (UserAlreadyExistsException | ServiceLayerException e) {
logger.debug("Error adding user " + usernameHeaderValue + " from authentication " + "headers", e);
throw new AuthenticationSystemException("Error adding user " + usernameHeaderValue + " from external " + "authentication provider", e);
}
}
} catch (ServiceLayerException e) {
logger.debug("Unknown service error", e);
throw new AuthenticationSystemException("Unknown service error", e);
}
User user = new User();
user.setUsername(usernameHeaderValue);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setGroups(new ArrayList<UserGroup>());
logger.debug("Update user groups in database.");
if (StringUtils.isNoneEmpty(groups)) {
String[] groupsArray = groups.split(",");
for (int i = 0; i < groupsArray.length; i++) {
Group g = new Group();
try {
g.setGroupName(StringUtils.trim(groupsArray[i]));
g.setGroupDescription("Externally managed group");
g.setOrganization(null);
UserGroup ug = new UserGroup();
ug.setGroup(g);
user.getGroups().add(ug);
upsertUserGroup(g.getGroupName(), usernameHeaderValue, authenticationChain);
} catch (Exception e) {
logger.debug("Error updating user group " + g.getGroupName() + " with data from authentication headers", e);
}
}
}
String token = createToken(user, authenticationChain);
if (isLogoutEnabled()) {
storeAuthentication(new Authentication(usernameHeaderValue, token, AuthenticationType.AUTH_HEADERS, logoutUrl));
} else {
storeAuthentication(new Authentication(usernameHeaderValue, token, AuthenticationType.AUTH_HEADERS));
}
return true;
}
}
logger.debug("Unable to authenticate user using authentication headers");
return false;
} else {
logger.debug("Authentication using headers disabled");
return false;
}
}
use of org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException in project studio by craftercms.
the class LdapAuthenticationProvider method doAuthenticate.
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationChain authenticationChain, String username, String password) throws AuthenticationSystemException, BadCredentialsException {
LdapContextSource lcs = new LdapContextSource();
lcs.setUrl(ldapUrl);
lcs.setUserDn(ldapUsername);
lcs.setPassword(ldapPassword);
lcs.setBase(ldapBaseContext);
lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
lcs.afterPropertiesSet();
LdapTemplate ldapTemplate = new LdapTemplate(lcs);
// Mapper for user data if user is successfully authenticated
AuthenticatedLdapEntryContextMapper<User> mapper = (dirContext, ldapEntryIdentification) -> {
try {
// User entry - extract attributes
DirContextOperations dirContextOperations = (DirContextOperations) dirContext.lookup(ldapEntryIdentification.getRelativeName());
Attributes attributes = dirContextOperations.getAttributes();
Attribute emailAttrib = attributes.get(emailLdapAttribute);
Attribute firstNameAttrib = attributes.get(firstNameLdapAttribute);
Attribute lastNameAttrib = attributes.get(lastNameLdapAttribute);
Attribute groupNameAttrib = attributes.get(groupNameLdapAttribute);
User user = new User();
user.setEnabled(true);
user.setExternallyManaged(true);
user.setUsername(username);
user.setPassword(UUID.randomUUID().toString());
if (emailAttrib != null && emailAttrib.get() != null) {
user.setEmail(emailAttrib.get().toString());
} else {
logger.warn("No LDAP attribute " + emailLdapAttribute + " found for username " + username + ". User will not be imported into DB.");
return null;
}
if (firstNameAttrib != null && firstNameAttrib.get() != null) {
user.setFirstName(firstNameAttrib.get().toString());
} else {
logger.warn("No LDAP attribute " + firstNameLdapAttribute + " found for username " + username);
}
if (lastNameAttrib != null && lastNameAttrib.get() != null) {
user.setLastName(lastNameAttrib.get().toString());
} else {
logger.warn("No LDAP attribute " + lastNameLdapAttribute + " found for username " + username);
}
extractGroupsFromAttribute(user, groupNameLdapAttribute, groupNameAttrib);
return user;
} catch (NamingException e) {
logger.debug("Error getting details from LDAP for username " + username, e);
return null;
}
};
// Create ldap query to authenticate user
LdapQuery ldapQuery = query().where(usernameLdapAttribute).is(username);
User user;
try {
user = ldapTemplate.authenticate(ldapQuery, password, mapper);
} catch (EmptyResultDataAccessException e) {
logger.debug("User " + username + " not found with external security provider.");
return false;
} catch (CommunicationException e) {
logger.debug("Failed to connect with external security provider", e);
return false;
} catch (AuthenticationException e) {
logger.debug("Authentication failed with the LDAP system (bad credentials)", e);
throw new BadCredentialsException();
} catch (Exception e) {
logger.debug("Unexpected exception when authenticating with the LDAP system", e);
return false;
}
if (user != null) {
// When user authenticated against LDAP, upsert user data into studio database
UserServiceInternal userServiceInternal = authenticationChain.getUserServiceInternal();
AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
SiteService siteService = authenticationChain.getSiteService();
try {
SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
if (userServiceInternal.userExists(-1, username)) {
try {
userServiceInternal.updateUser(user);
} catch (UserNotFoundException e) {
// Shouldn't happen
throw new IllegalStateException(e);
}
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_UPDATE);
auditLog.setSiteId(siteFeed.getId());
auditLog.setActorId(user.getUsername());
auditLog.setPrimaryTargetId(user.getUsername());
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(user.getUsername());
auditServiceInternal.insertAuditLog(auditLog);
} else {
try {
userServiceInternal.createUser(user);
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_CREATE);
auditLog.setSiteId(siteFeed.getId());
auditLog.setActorId(user.getUsername());
auditLog.setPrimaryTargetId(user.getUsername());
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(user.getUsername());
auditServiceInternal.insertAuditLog(auditLog);
} catch (UserAlreadyExistsException e) {
logger.debug("Error adding user " + username + " from external authentication provider", e);
throw new AuthenticationSystemException("Error adding user " + username + " from external authentication provider", e);
}
}
} catch (ServiceLayerException e) {
logger.debug("Unknown service error", e);
throw new AuthenticationSystemException("Unknown service error", e);
}
for (UserGroup userGroup : user.getGroups()) {
upsertUserGroup(userGroup.getGroup().getGroupName(), user.getUsername(), authenticationChain);
}
String token = createToken(user, authenticationChain);
storeAuthentication(new Authentication(username, token, AuthenticationType.LDAP));
return true;
} else {
logger.debug("Failed to retrieve LDAP user details");
throw new AuthenticationSystemException("Failed to retrieve LDAP user details");
}
}
Aggregations