use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.
the class OAuthAuthenticationManagerUnitTest method testAuthExpired.
/**
* Expired tokens are not accepted.
*/
@Test(expected = ResultCodeException.class)
public void testAuthExpired() {
IdmIdentityDto i = getTestIdentity();
IdmTokenDto token = new IdmTokenDto(UUID.randomUUID());
token.setExpiration(ZonedDateTime.now().minusHours(1));
when(tokenService.get(token.getId())).thenReturn(token);
when(cacheManager.getValue(TokenManager.TOKEN_CACHE_NAME, token.getId())).thenReturn(null);
IdmJwtAuthentication authentication = getAuthentication(token.getId(), i, ZonedDateTime.now().minusHours(1), ZonedDateTime.now().plusHours(2));
authManager.authenticate(authentication);
Assert.fail("Cannot authenticate with expired token.");
}
use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.
the class ExtendExpirationFilterTest method testSuccBasicAuthTokenExtension.
@Test
public void testSuccBasicAuthTokenExtension() throws Exception {
LoginDto login = getHelper().loginAdmin();
securityService.logout();
//
String basicAuth = getBasicAuth(TestHelper.ADMIN_USERNAME, TestHelper.ADMIN_PASSWORD);
//
IdmTokenDto originalToken = tokenService.get(login.getAuthentication().getId());
originalToken.setExpiration(originalToken.getExpiration().minusMinutes(2));
originalToken = tokenService.save(originalToken);
//
MvcResult result = getMockMvc().perform(get(getSelfPath(TestHelper.ADMIN_USERNAME)).header("Authorization", "Basic " + basicAuth).header(JwtAuthenticationMapper.AUTHENTICATION_TOKEN_NAME, login.getToken()).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(jsonPath("$.username", equalTo(TestHelper.ADMIN_USERNAME))).andReturn();
IdmJwtAuthenticationDto extended = getIdmJwtDto(result);
Assert.assertEquals(originalToken.getOwnerId(), extended.getCurrentIdentityId());
Assert.assertEquals(originalToken.getIssuedAt().toInstant().toEpochMilli(), extended.getIssuedAt().toInstant().toEpochMilli());
// token expiration - orignal exp. time is lower or equal to new one
Assert.assertTrue(originalToken.getExpiration().toInstant().toEpochMilli() < extended.getExpiration().toInstant().toEpochMilli());
}
use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.
the class DefaultLoginService method loginAuthenticatedUser.
@Override
public LoginDto loginAuthenticatedUser() {
if (!securityService.isAuthenticated()) {
throw new IdmAuthenticationException("Not authenticated!");
}
String username = securityService.getAuthentication().getCurrentUsername();
LOG.info("Identity with username [{}] authenticating", username);
//
IdmIdentityDto identity = identityService.getByUsername(username);
// identity doesn't exist
if (identity == null) {
throw new IdentityNotFoundException(MessageFormat.format("Check identity can login: The identity " + "[{0}] either doesn't exist or is deleted.", username));
}
//
// prevent to create duplicate token for logged identity
IdmTokenDto preparedToken = tokenManager.getCurrentToken();
if (preparedToken == null || !Objects.equals(preparedToken.getOwnerId(), identity.getId())) {
preparedToken = new IdmTokenDto();
preparedToken.setModuleId(CoreModuleDescriptor.MODULE_ID);
}
//
LoginDto loginDto = new LoginDto();
loginDto.setUsername(username);
loginDto = jwtAuthenticationService.createJwtAuthenticationAndAuthenticate(loginDto, identity, preparedToken);
LOG.info("Identity with username [{}] is authenticated", username);
return loginDto;
}
use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.
the class DefaultTwoFactorAuthenticationManager method authenticate.
@Override
@Transactional
public LoginDto authenticate(LoginDto loginTwoFactorRequestDto) {
Assert.notNull(loginTwoFactorRequestDto, "Login request is required.");
//
IdmJwtAuthenticationDto claims = null;
String loggedAction = siemLogger.buildAction(SiemLoggerManager.LOGIN_LEVEL_KEY);
String targetName = loginTwoFactorRequestDto.getUsername();
String targetUuid = null;
try {
Optional<Jwt> jwt = HttpFilterUtils.parseToken(loginTwoFactorRequestDto.getToken());
if (!jwt.isPresent()) {
throw new ResultCodeException(CoreResultCode.AUTH_FAILED, "Verification code must be filled");
}
HttpFilterUtils.verifyToken(jwt.get(), jwtAuthenticationMapper.getVerifier());
// authentication dto from request
try {
claims = jwtAuthenticationMapper.getClaims(jwt.get());
targetName = claims.getCurrentUsername();
targetUuid = Objects.toString(claims.getCurrentIdentityId(), "");
} catch (IOException ex) {
throw new ResultCodeException(CoreResultCode.TOKEN_READ_FAILED, ex);
}
// we need to check expiration, before current (automatically prolonged) token is used by mapper
if (claims.getExpiration() != null && claims.getExpiration().isBefore(ZonedDateTime.now())) {
throw new ResultCodeException(CoreResultCode.AUTH_EXPIRED);
}
UUID identityId = claims.getCurrentIdentityId();
IdmIdentityDto identity = identityService.get(identityId);
if (identity == null) {
throw new EntityNotFoundException(IdmIdentityDto.class, identityId);
}
IdmPasswordDto password = passwordService.findOneByIdentity(identityId);
if (password == null) {
throw new EntityNotFoundException(IdmPasswordDto.class, identityId);
}
if (!verifyCode(password, loginTwoFactorRequestDto.getPassword())) {
throw new ResultCodeException(CoreResultCode.TWO_FACTOR_VERIFICATION_CODE_FAILED);
}
//
if (password.isMustChange() && !loginTwoFactorRequestDto.isSkipMustChange()) {
throw new MustChangePasswordException(claims.getCurrentUsername());
}
// set token verified
IdmTokenDto token = tokenManager.getToken(claims.getId());
token.setSecretVerified(true);
// and login - new login dto new to be constructed to preserve original login metadata
LoginDto loginDto = new LoginDto();
loginDto.setUsername(claims.getCurrentUsername());
loginDto.setAuthenticationModule(claims.getFromModule());
//
LoginDto resultLoginDto = jwtAuthenticationService.createJwtAuthenticationAndAuthenticate(loginDto, identity, token);
siemLogger.log(loggedAction, SiemLoggerManager.SUCCESS_ACTION_STATUS, targetName, targetUuid, null, null, null, null);
return resultLoginDto;
} catch (Exception e) {
siemLogger.log(loggedAction, SiemLoggerManager.FAILED_ACTION_STATUS, targetName, targetUuid, null, null, null, e.getMessage());
throw e;
}
}
use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.
the class JwtAuthenticationMapper method prolongExpiration.
/**
* Prolong authentication expiration - but only if difference from old expiration is greater than one minute.
* If persistent token for given authentication is found, then persisted token is updated
*
* @param tokenId
* @return returns actual token
*/
public IdmJwtAuthenticationDto prolongExpiration(IdmJwtAuthenticationDto authenticationDto) {
if (authenticationDto == null || authenticationDto.getId() == null) {
return authenticationDto;
}
//
ZonedDateTime newExpiration = getNewExpiration();
ZonedDateTime oldExpiration = authenticationDto.getExpiration();
if (oldExpiration == null) {
LOG.trace("Authentication token with id [{}] has unlimited expiration (e.g. system token), expiration will not be changed.", authenticationDto.getId());
return authenticationDto;
}
// TODO: #1198
long seconds = ChronoUnit.SECONDS.between(authenticationDto.getExpiration(), newExpiration);
if (seconds < 60) {
LOG.trace("Authentication [{}] expiration will not be prolonged - expiration differs by [{}]s only.", authenticationDto.getId(), seconds);
return authenticationDto;
}
//
authenticationDto.setExpiration(newExpiration);
IdmTokenDto token = tokenManager.getToken(authenticationDto.getId());
if (token == null) {
LOG.trace("Persisted token for authentication with id [{}] not found, persisted token expiration will not be prolonged.", authenticationDto.getId());
return authenticationDto;
}
if (token.getExpiration() == null) {
LOG.trace("Persisted token with id [{}] has unlimited expiration (e.g. system token), expiration will not be changed.", token.getId());
return authenticationDto;
}
//
// expiration and token attribute has to be updated
token.setExpiration(newExpiration);
token.setToken(getTokenHash(token));
token = tokenManager.saveToken(new IdmIdentityDto(token.getOwnerId()), token);
//
return toDto(token);
}
Aggregations