Code development platform for open source projects from the European Union institutions :large_blue_circle: EU Login authentication by SMS has been phased out. To see alternatives please check here

Skip to content
Snippets Groups Projects
Commit 7ee8e102 authored by Joze RIHTARSIC's avatar Joze RIHTARSIC
Browse files

Pull request #202: Feature/EDELIVERY-8806 force change password expiration at exipation

Merge in EDELIVERY/smp from feature/EDELIVERY-8806-force-change-password-expiration-at-exipation to EDELIVERY-8907-ebcoreparty-identifier-in-xml-schema

* commit '1f5379f0e2e84c61a320b709e841a3f11c75425f':
  Update alerts for credentials verification and suspension
  Implement force change + warning before expire
parents b0cfc269 08e5e968
No related branches found
No related tags found
No related merge requests found
Showing
with 397 additions and 136 deletions
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>eDelivery SMP</title>
</head>
<body style="margin:0; padding:0; background-color: #f1f1f1;">
<center>
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #f1f1f1;">
<tr>
<td><!-- MARGIN TOP -->
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #f1f1f1;">
<tr>
<td>&nbsp;</td>
</tr>
</table>
<!-- / MARGIN TOP -->
<table width="540" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<!-- MARGIN LEFT -->
<td width="20" valign="top">&nbsp;</td>
<!-- / MARGIN LEFT -->
<td width="500" valign="top"><!-- WRAPPER -->
<table width="500" border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="top" style="border:5px solid #4cbdce;"><table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #ffffff;">
<tr>
<!-- COL LEFT -->
<td width="20" valign="top">&nbsp;</td>
<!-- / COL LEFT -->
<!-- CENTER -->
<td width="460" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="20" valign="top">&nbsp;</td>
</tr>
<!-- TITLE -->
<tr>
<td valign="top" align="left" style=" font-size: 30px; font-family: Arial, Helvetica, sans-serif; color: #000;">eDelivery SMP<br/></td>
</tr>
<!-- / TITLE -->
<!-- UNDERLINE -->
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="60" height="10" style="border-bottom:3px solid #4cbdce"></td>
<td width="400" height="5"></td>
</tr>
</table></td>
</tr>
<!-- / UNDERLINE -->
<!-- TITLE -->
<tr>
<td valign="top" align="left" style=" font-size: 20px; font-family: Arial, Helvetica, sans-serif; color: #000;"><br/>
Account is temporarly suspended</td>
</tr>
<!-- / TITLE -->
<!-- UNDERLINE -->
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="30" height="10" style="border-bottom:3px solid #000000"></td>
<td width="430" height="5"></td>
</tr>
</table></td>
</tr>
<!-- / UNDERLINE -->
<!-- MAIN CONTENT -->
<tr>
<td valign="top" align="left" style=" font-size: 13px; font-family: Arial, Helvetica, sans-serif; color: #000;"><br/>
<br/>
<p><strong>Credential type:</strong> ${CREDENTIAL_TYPE}</p>
<p><strong>Credential id:</strong> ${CREDENTIAL_ID}</p>
<p><strong>Failed login attempt count:</strong> ${FAILED_LOGIN_ATTEMPT}</p>
<p><strong>Last failed login time:</strong> ${LAST_LOGIN_FAILURE_DATETIME}</p>
<p><strong>Reporting time:</strong> ${REPORTING_TIME}</p>
<p><strong>Alert level:</strong> ${ALERT_LEVEL}</p>
<p><strong>Server name:</strong> ${SERVER_NAME}</p>
</td>
</tr>
<!-- / MAIN CONTENT -->
<tr>
<td height="20" valign="top">&nbsp;</td>
</tr>
</table></td>
<!-- / CENTER -->
<!-- COL RIGHT -->
<td width="20" valign="top">&nbsp;</td>
<!-- / COL RIGHT -->
</tr>
</table></td>
</tr>
</table>
<!-- / WRAPPER --></td>
<!-- MARGIN RIGHT -->
<td width="20" valign="top"></td>
<!-- / MARGIN RIGHT -->
</tr>
</table>
</td>
</tr>
</table>
</center>
</body>
</html>
\ No newline at end of file
......@@ -46,7 +46,8 @@ public class DBUserToUserROConverterTest {
whenConvertingTheExistingUser();
thenThePasswordIsMarkedAsExpired("The passwords should be marked as expired when converting users having passwords that have been reset by SystemAdministrators");
thenThePasswordIsMarkedAsExpired("The passwords should be marked as expired when converting users" +
" having passwords that have been reset by SystemAdministrators");
}
@Test
......@@ -89,6 +90,7 @@ public class DBUserToUserROConverterTest {
source.setCertificate(certificate);
source.setPassword(password);
source.setPasswordChanged(passwordChange);
source.setPasswordExpireOn(passwordChange!=null?passwordChange.plusMonths(3):null);
}
private void whenConvertingTheExistingUser() {
......
......@@ -88,7 +88,7 @@ public class AuditIntegrationTest {
DBAlert dbAlert = createDBAlert();
Map<String, Object> alterVal = new HashMap<>();
alterVal.put("processed", false);
alterVal.put("alertType", AlertTypeEnum.CREDENTIALS_IMMINENT_EXPIRATION);
alterVal.put("alertType", AlertTypeEnum.CREDENTIAL_IMMINENT_EXPIRATION);
alterVal.put("alertStatus", AlertStatusEnum.FAILED);
testAuditEntity(dbAlert, alterVal);
}
......
......@@ -25,7 +25,6 @@ public class TestDBUtils {
return domain;
}
public static DBDomain createDBDomain() {
return createDBDomain(TestConstants.TEST_DOMAIN_CODE_1);
}
......@@ -85,7 +84,7 @@ public class TestDBUtils {
DBAlert dbalert = new DBAlert();
dbalert.setAlertLevel(AlertLevelEnum.MEDIUM);
dbalert.setAlertStatus(AlertStatusEnum.SUCCESS);
dbalert.setAlertType(AlertTypeEnum.CREDENTIALS_IMMINENT_EXPIRATION);
dbalert.setAlertType(AlertTypeEnum.CREDENTIAL_IMMINENT_EXPIRATION);
dbalert.setProcessed(true);
dbalert.setProcessedTime(OffsetDateTime.now());
dbalert.setReportingTime(OffsetDateTime.now());
......
......@@ -6,6 +6,8 @@ import eu.europa.ec.edelivery.smp.data.dao.UserDao;
import eu.europa.ec.edelivery.smp.data.model.DBCertificate;
import eu.europa.ec.edelivery.smp.data.model.DBUser;
import eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority;
import eu.europa.ec.edelivery.smp.data.ui.enums.AlertSuspensionMomentEnum;
import eu.europa.ec.edelivery.smp.data.ui.enums.CredentialTypeEnum;
import eu.europa.ec.edelivery.smp.data.ui.enums.SMPPropertyEnum;
import eu.europa.ec.edelivery.smp.logging.SMPLogger;
import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory;
......@@ -244,6 +246,9 @@ public class SMPAuthenticationProvider implements AuthenticationProvider {
LOG.warn("User [{}] failed login attempt [{}]! did not reach the max failed attempts [{}]", user.getUsername(), user.getSequentialTokenLoginFailureCount(), configurationService.getAccessTokenLoginMaxAttempts());
return;
}
if (configurationService.getAlertBeforeUserSuspendedAlertMoment() == AlertSuspensionMomentEnum.AT_LOGON) {
alertService.alertCredentialsSuspended(user, CredentialTypeEnum.ACCESS_TOKEN);
}
LOG.securityWarn(SMPMessageCode.SEC_USER_SUSPENDED, user.getUsername());
throw new BadCredentialsException("The user is suspended. Please try again later or contact your administrator.");
}
......@@ -311,7 +316,9 @@ public class SMPAuthenticationProvider implements AuthenticationProvider {
LOG.securityWarn(SMPMessageCode.SEC_INVALID_PASSWORD, user.getUsername());
if (user.getSequentialTokenLoginFailureCount() >= configurationService.getAccessTokenLoginMaxAttempts()) {
LOG.info("User access token [{}] failed sequential attempt exceeded the max allowed attempts [{}]!", user.getAccessToken(), configurationService.getAccessTokenLoginMaxAttempts());
alertService.alertAccessTokenCredentialsSuspended(user);
alertService.alertCredentialsSuspended(user, CredentialTypeEnum.ACCESS_TOKEN);
} else {
alertService.alertCredentialVerificationFailed(user, CredentialTypeEnum.ACCESS_TOKEN);
}
throw new BadCredentialsException(LOGIN_FAILED_MESSAGE);
}
......
......@@ -3,6 +3,8 @@ package eu.europa.ec.edelivery.smp.auth;
import eu.europa.ec.edelivery.smp.data.dao.UserDao;
import eu.europa.ec.edelivery.smp.data.model.DBUser;
import eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority;
import eu.europa.ec.edelivery.smp.data.ui.enums.AlertSuspensionMomentEnum;
import eu.europa.ec.edelivery.smp.data.ui.enums.CredentialTypeEnum;
import eu.europa.ec.edelivery.smp.data.ui.enums.SMPPropertyEnum;
import eu.europa.ec.edelivery.smp.logging.SMPLogger;
import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory;
......@@ -83,7 +85,6 @@ public class SMPAuthenticationProviderForUI implements AuthenticationProvider {
LOG.debug("User with username does not exists [{}], continue with next authentication provider");
return null;
}
user = oUsr.get();
} catch (AuthenticationException ex) {
LOG.securityWarn(SMPMessageCode.SEC_USER_NOT_AUTHENTICATED, username, ExceptionUtils.getRootCause(ex), ex);
......@@ -122,7 +123,9 @@ public class SMPAuthenticationProviderForUI implements AuthenticationProvider {
LOG.securityWarn(SMPMessageCode.SEC_INVALID_PASSWORD, user.getUsername());
if (user.getSequentialLoginFailureCount() >= configurationService.getLoginMaxAttempts()) {
LOG.info("User [{}] failed sequential attempt exceeded the max allowed attempts [{}]!", user.getUsername(), configurationService.getLoginMaxAttempts());
alertService.alertUsernamePasswordCredentialsSuspended(user);
alertService.alertCredentialsSuspended(user, CredentialTypeEnum.USERNAME_PASSWORD);
} else {
alertService.alertCredentialVerificationFailed(user, CredentialTypeEnum.USERNAME_PASSWORD);
}
throw new BadCredentialsException("Login failed; Invalid userID or password");
}
......@@ -162,6 +165,9 @@ public class SMPAuthenticationProviderForUI implements AuthenticationProvider {
LOG.warn("User [{}] failed login attempt [{}]! did not reach the max failed attempts [{}]", user.getUsername(), user.getSequentialLoginFailureCount(), configurationService.getLoginMaxAttempts());
return;
}
if (configurationService.getAlertBeforeUserSuspendedAlertMoment() == AlertSuspensionMomentEnum.AT_LOGON) {
alertService.alertCredentialsSuspended(user, CredentialTypeEnum.USERNAME_PASSWORD);
}
LOG.securityWarn(SMPMessageCode.SEC_USER_SUSPENDED, user.getUsername());
throw new BadCredentialsException("The user is suspended. Please try again later or contact your administrator.");
}
......
......@@ -10,9 +10,17 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static eu.europa.ec.edelivery.smp.utils.SMPCookieWriter.CSRF_COOKIE_NAME;
import static eu.europa.ec.edelivery.smp.utils.SMPCookieWriter.SESSION_COOKIE_NAME;
@Service
public class SMPAuthenticationService {
......@@ -30,4 +38,18 @@ public class SMPAuthenticationService {
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication;
}
public void logout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
LOG.debug("Cannot perform logout: no user is authenticated");
return;
}
LOG.info("Logging out user [{}]", auth.getName());
new CookieClearingLogoutHandler(SESSION_COOKIE_NAME, CSRF_COOKIE_NAME).logout(request, response, null);
LOG.info("Cleared cookies");
new SecurityContextLogoutHandler().logout(request, response, auth);
LOG.info("Logged out");
}
}
\ No newline at end of file
......@@ -85,7 +85,9 @@ public class SMPAuthorizationService {
userRO.setPassword("");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication!=null ){
userRO.setAuthorities(authentication.getAuthorities().stream().map(val -> (SMPAuthority) val).collect(Collectors.toList()));
}
return userRO;
}
......
......@@ -5,7 +5,6 @@ import eu.europa.ec.edelivery.smp.auth.SMPAuthenticationService;
import eu.europa.ec.edelivery.smp.auth.SMPAuthenticationToken;
import eu.europa.ec.edelivery.smp.auth.SMPAuthorizationService;
import eu.europa.ec.edelivery.smp.data.model.DBUser;
import eu.europa.ec.edelivery.smp.data.ui.ErrorRO;
import eu.europa.ec.edelivery.smp.data.ui.LoginRO;
import eu.europa.ec.edelivery.smp.data.ui.UserRO;
import eu.europa.ec.edelivery.smp.logging.SMPLogger;
......@@ -15,14 +14,9 @@ import eu.europa.ec.edelivery.smp.services.ui.UIUserService;
import eu.europa.ec.edelivery.smp.utils.SMPCookieWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.transaction.annotation.Transactional;
......@@ -31,9 +25,9 @@ import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.OffsetDateTime;
import static eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority.*;
import static eu.europa.ec.edelivery.smp.utils.SMPCookieWriter.CSRF_COOKIE_NAME;
import static eu.europa.ec.edelivery.smp.utils.SMPCookieWriter.SESSION_COOKIE_NAME;
/**
......@@ -87,23 +81,14 @@ public class AuthenticationResource {
csrfTokenRepository.saveToken(csfrToken, request, response);
SMPAuthenticationToken authentication = (SMPAuthenticationToken) authenticationService.authenticate(loginRO.getUsername(), loginRO.getPassword());
UserRO userRO = conversionService.convert(authentication.getUser(), UserRO.class);
return authorizationService.sanitize(userRO);
DBUser user = authentication.getUser();
return getUserData(user);
}
@DeleteMapping(value = "authentication")
public void logout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
LOG.debug("Cannot perform logout: no user is authenticated");
return;
}
LOG.info("Logging out user [{}]", auth.getName());
new CookieClearingLogoutHandler(SESSION_COOKIE_NAME, CSRF_COOKIE_NAME).logout(request, response, null);
LOG.info("Cleared cookies");
new SecurityContextLogoutHandler().logout(request, response, auth);
LOG.info("Logged out");
LOG.info("Logging out user for the session");
authenticationService.logout(request, response);
}
/**
......@@ -123,11 +108,11 @@ public class AuthenticationResource {
@GetMapping(value = "user")
@Secured({S_AUTHORITY_TOKEN_SYSTEM_ADMIN, S_AUTHORITY_TOKEN_SMP_ADMIN, S_AUTHORITY_TOKEN_SERVICE_GROUP_ADMIN})
public UserRO getUser() {
public UserRO getUser(HttpServletRequest request, HttpServletResponse response) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserRO) {
return (UserRO) principal;
return getUpdatedUserData((UserRO) principal);
}
String username = (String) principal;
......@@ -138,8 +123,27 @@ public class AuthenticationResource {
LOG.warn("User: [{}] does not exists anymore or is not active.", username);
return null;
}
return getUserData(user);
}
protected UserRO getUserData(DBUser user) {
UserRO userRO = conversionService.convert(user, UserRO.class);
return getUpdatedUserData(userRO);
}
/**
* Method updates data with "show expire dialog" flag, forces the password change flag and
* sanitize ui data/
* @param userRO
* @return updated user data according to SMP configuration
*/
protected UserRO getUpdatedUserData(UserRO userRO) {
userRO.setShowPasswordExpirationWarning(userRO.getPasswordExpireOn() != null &&
OffsetDateTime.now()
.minusDays(configurationService.getPasswordPolicyUIWarningDaysBeforeExpire())
.isBefore(userRO.getPasswordExpireOn()));
userRO.setForceChangePassword(userRO.isPasswordExpired() && configurationService.getPasswordPolicyForceChangeIfExpired()) ;
return authorizationService.sanitize(userRO);
}
......
package eu.europa.ec.edelivery.smp.ui.external;
import eu.europa.ec.edelivery.smp.auth.SMPAuthenticationService;
import eu.europa.ec.edelivery.smp.auth.SMPAuthorizationService;
import eu.europa.ec.edelivery.smp.data.model.DBUser;
import eu.europa.ec.edelivery.smp.data.ui.AccessTokenRO;
......@@ -13,6 +14,9 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static eu.europa.ec.edelivery.smp.ui.ResourceConstants.CONTEXT_PATH_PUBLIC_USER;
import static eu.europa.ec.edelivery.smp.utils.SessionSecurityUtils.decryptEntityId;
......@@ -25,12 +29,15 @@ import static eu.europa.ec.edelivery.smp.utils.SessionSecurityUtils.decryptEntit
public class UserResource {
private static final SMPLogger LOG = SMPLoggerFactory.getLogger(UserResource.class);
@Autowired
private UIUserService uiUserService;
@Autowired
protected UIUserService uiUserService;
protected SMPAuthorizationService authorizationService;
protected SMPAuthenticationService authenticationService;
public UserResource(UIUserService uiUserService, SMPAuthorizationService authorizationService, SMPAuthenticationService authenticationService) {
this.uiUserService = uiUserService;
this.authorizationService = authorizationService;
this.authenticationService = authenticationService;
}
@PreAuthorize("@smpAuthorizationService.isCurrentlyLoggedIn(#userId)")
@PostMapping(path = "/{user-id}/generate-access-token", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
......@@ -43,10 +50,15 @@ public class UserResource {
@PreAuthorize("@smpAuthorizationService.isCurrentlyLoggedIn(#userId)")
@PutMapping(path = "/{user-id}/change-password", consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public boolean changePassword(@PathVariable("user-id") String userId, @RequestBody PasswordChangeRO newPassword) {
public boolean changePassword(@PathVariable("user-id") String userId, @RequestBody PasswordChangeRO newPassword, HttpServletRequest request, HttpServletResponse response) {
Long entityId = decryptEntityId(userId);
LOG.info("Validating the password of the currently logged in user:[{}] with id:[{}] ", userId, entityId);
return uiUserService.updateUserPassword(entityId, newPassword.getCurrentPassword(), newPassword.getNewPassword());
boolean result = uiUserService.updateUserPassword(entityId, newPassword.getCurrentPassword(), newPassword.getNewPassword());
if (result){
LOG.info("Password successfully changed. Logout the user, to be able to login with the new password!");
authenticationService.logout(request, response);
}
return result;
}
/**
......
package eu.europa.ec.edelivery.smp.ui;
import eu.europa.ec.edelivery.smp.data.ui.UserRO;
import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.assertNotNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {SmpTestWebAppConfig.class})
@Sql(scripts = {
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class AuthenticationResourceIntegrationTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_PUBLIC_SECURITY + "/authentication";
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mvc;
private static final RequestPostProcessor ADMIN_CREDENTIALS = httpBasic("smp_admin", "test123");
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(webAppContext)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
initServletContext();
}
private void initServletContext() {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener(webAppContext);
ServletContextEvent event = new ServletContextEvent(sc);
}
@Test
public void authenticateSuccessTest() throws Exception {
// given when
HttpSession session = mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin\",\"password\":\"test123\"}"))
.andExpect(status().isOk()).andReturn()
.getRequest()
.getSession();
assertNotNull(session);
}
@Test
public void authenticateInvalidPasswordTest() throws Exception {
// given when then
mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin\",\"password\":\"test1235\"}"))
.andExpect(status().isUnauthorized()).andReturn()
.getRequest()
.getSession();
}
@Test
public void authenticateInvalidUsernameTest() throws Exception {
// given when
mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin1\",\"password\":\"test123\"}"))
.andExpect(status().isUnauthorized()).andReturn()
.getRequest()
.getSession();
}
}
\ No newline at end of file
package eu.europa.ec.edelivery.smp.ui;
import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig;
import org.junit.Before;
import org.junit.Ignore;
import eu.europa.ec.edelivery.smp.auth.SMPAuthenticationService;
import eu.europa.ec.edelivery.smp.auth.SMPAuthorizationService;
import eu.europa.ec.edelivery.smp.data.ui.UserRO;
import eu.europa.ec.edelivery.smp.services.ConfigurationService;
import eu.europa.ec.edelivery.smp.services.ui.UIUserService;
import eu.europa.ec.edelivery.smp.utils.SMPCookieWriter;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.assertNotNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {SmpTestWebAppConfig.class})
@Sql(scripts = {
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class AuthenticationResourceTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_PUBLIC_SECURITY + "/authentication";
@Autowired
private WebApplicationContext webAppContext;
import org.mockito.Mockito;
import org.springframework.core.convert.ConversionService;
import org.springframework.security.web.csrf.CsrfTokenRepository;
private MockMvc mvc;
private static final RequestPostProcessor ADMIN_CREDENTIALS = httpBasic("smp_admin", "test123");
import java.time.OffsetDateTime;
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(webAppContext)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
initServletContext();
}
public class AuthenticationResourceTest {
private void initServletContext() {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener(webAppContext);
ServletContextEvent event = new ServletContextEvent(sc);
SMPAuthenticationService authenticationService = Mockito.mock(SMPAuthenticationService.class);
SMPAuthorizationService authorizationService = Mockito.mock(SMPAuthorizationService.class);
ConversionService conversionService = Mockito.mock(ConversionService.class);
ConfigurationService configurationService = Mockito.mock(ConfigurationService.class);
SMPCookieWriter smpCookieWriter = Mockito.mock(SMPCookieWriter.class);
CsrfTokenRepository csrfTokenRepository = Mockito.mock(CsrfTokenRepository.class);
UIUserService uiUserService = Mockito.mock(UIUserService.class);
AuthenticationResource testInstance= new AuthenticationResource(authenticationService,
authorizationService,
conversionService,
configurationService,
smpCookieWriter,
csrfTokenRepository,
uiUserService);
@Test
public void testGetUpdatedUserData() {
UserRO user = new UserRO();
user.setPasswordExpireOn(OffsetDateTime.now().minusDays(1));
Mockito.doReturn(10).when(configurationService).getPasswordPolicyUIWarningDaysBeforeExpire();
Mockito.doReturn(false).when(configurationService).getPasswordPolicyForceChangeIfExpired();
Mockito.doReturn(user).when(authorizationService).sanitize(Mockito.any());
user = testInstance.getUpdatedUserData(user);
Assert.assertTrue(user.isShowPasswordExpirationWarning());
Assert.assertFalse(user.isForceChangeExpiredPassword());
Assert.assertFalse(user.isPasswordExpired());
}
@Test
public void authenticateSuccessTest() throws Exception {
// given when
HttpSession session = mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin\",\"password\":\"test123\"}"))
.andExpect(status().isOk()).andReturn()
.getRequest()
.getSession();
assertNotNull(session);
public void testGetUpdatedUserDataDoNotShowWarning() {
UserRO user = new UserRO();
user.setPasswordExpireOn(OffsetDateTime.now().minusDays(11));
Mockito.doReturn(10).when(configurationService).getPasswordPolicyUIWarningDaysBeforeExpire();
Mockito.doReturn(false).when(configurationService).getPasswordPolicyForceChangeIfExpired();
Mockito.doReturn(user).when(authorizationService).sanitize(Mockito.any());
user = testInstance.getUpdatedUserData(user);
Assert.assertFalse(user.isShowPasswordExpirationWarning());
Assert.assertFalse(user.isForceChangeExpiredPassword());
Assert.assertFalse(user.isPasswordExpired());
}
@Test
@Ignore
public void authenticateInvalidPasswordTest() throws Exception {
// given when then
mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin\",\"password\":\"test1235\"}"))
.andExpect(status().isForbidden()).andReturn()
.getRequest()
.getSession();
public void testGetUpdatedUserDataForceChange() {
UserRO user = new UserRO();
user.setPasswordExpireOn(OffsetDateTime.now().plusDays(1));
user.setPasswordExpired(true);
Mockito.doReturn(10).when(configurationService).getPasswordPolicyUIWarningDaysBeforeExpire();
Mockito.doReturn(true).when(configurationService).getPasswordPolicyForceChangeIfExpired();
Mockito.doReturn(user).when(authorizationService).sanitize(Mockito.any());
user = testInstance.getUpdatedUserData(user);
Assert.assertTrue(user.isForceChangeExpiredPassword());
Assert.assertTrue(user.isPasswordExpired());
}
@Test
@Ignore
public void authenticateInvalidUsernameTest() throws Exception {
// given when
mvc.perform(post(PATH)
.header("Content-Type", "application/json")
.content("{\"username\":\"smp_admin1\",\"password\":\"test123\"}"))
.andExpect(status().isForbidden()).andReturn()
.getRequest()
.getSession();
public void testGetUpdatedUserDataForceChangeFalse() {
UserRO user = new UserRO();
user.setPasswordExpireOn(OffsetDateTime.now().plusDays(1));
user.setPasswordExpired(true);
Mockito.doReturn(10).when(configurationService).getPasswordPolicyUIWarningDaysBeforeExpire();
Mockito.doReturn(false).when(configurationService).getPasswordPolicyForceChangeIfExpired();
Mockito.doReturn(user).when(authorizationService).sanitize(Mockito.any());
user = testInstance.getUpdatedUserData(user);
Assert.assertFalse(user.isForceChangeExpiredPassword());
Assert.assertTrue(user.isPasswordExpired());
}
}
......@@ -41,7 +41,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"smp.artifact.version=TestApplicationVersion",
"smp.artifact.build.time=2018-11-27 00:00:00",
})
public class ApplicationResourceTest {
public class ApplicationResourceIntegrationTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_PUBLIC_APPLICATION;
@Autowired
......
......@@ -39,7 +39,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class DomainResourceTest {
public class DomainResourceIntegrationTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_PUBLIC_DOMAIN;
@Autowired
......
......@@ -41,7 +41,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class SearchResourceTest {
public class SearchResourceIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
......
......@@ -49,7 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class ServiceGroupResourceTest {
public class ServiceGroupResourceIntegrationTest {
@Autowired
ServiceGroupDao serviceGroupDao;
......@@ -75,7 +75,7 @@ public class ServiceGroupResourceTest {
.build();
initServletContext();
validExtension = new String(IOUtils.toByteArray(ServiceGroupResourceTest.class.getResourceAsStream("/input/extensionMarshal.xml")));
validExtension = new String(IOUtils.toByteArray(ServiceGroupResourceIntegrationTest.class.getResourceAsStream("/input/extensionMarshal.xml")));
}
private void initServletContext() {
......
......@@ -43,7 +43,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class ServiceMetadataResourceTest {
public class ServiceMetadataResourceIntegrationTest {
// For the following test data see the: webapp_integration_test_data.sql
......
package eu.europa.ec.edelivery.smp.ui;
package eu.europa.ec.edelivery.smp.ui.external;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europa.ec.edelivery.smp.data.ui.CertificateRO;
......@@ -6,6 +6,7 @@ import eu.europa.ec.edelivery.smp.data.ui.DeleteEntityValidation;
import eu.europa.ec.edelivery.smp.data.ui.ServiceResult;
import eu.europa.ec.edelivery.smp.data.ui.UserRO;
import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig;
import eu.europa.ec.edelivery.smp.ui.ResourceConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
......@@ -42,7 +43,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class UserResourceTest {
public class UserResourceIntegrationTest {
private static final String PATH_PUBLIC = ResourceConstants.CONTEXT_PATH_PUBLIC_USER;
......
......@@ -44,7 +44,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"smp.artifact.version=TestApplicationVersion",
"smp.artifact.build.time=2018-11-27 00:00:00",
})
public class ApplicationAdminResourceTest {
public class ApplicationAdminResourceIntegrationTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_INTERNAL_APPLICATION;
private static final RequestPostProcessor SMP_ADMIN_CREDENTIALS = httpBasic("smp_admin", "test123");
private static final RequestPostProcessor SG_ADMIN_CREDENTIALS = httpBasic("sg_admin", "test123");
......
......@@ -42,7 +42,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
"classpath:/cleanup-database.sql",
"classpath:/webapp_integration_test_data.sql"},
executionPhase = BEFORE_TEST_METHOD)
public class DomainAdminResourceTest {
public class DomainAdminResourceIntegrationTest {
private static final String PATH = ResourceConstants.CONTEXT_PATH_INTERNAL_DOMAIN;
@Autowired
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment