Search in sources :

Example 41 with IdmTokenDto

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.");
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) Test(org.junit.Test) AbstractUnitTest(eu.bcvsolutions.idm.test.api.AbstractUnitTest)

Example 42 with IdmTokenDto

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());
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) LoginDto(eu.bcvsolutions.idm.core.security.api.dto.LoginDto) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.Test) AbstractRestTest(eu.bcvsolutions.idm.test.api.AbstractRestTest)

Example 43 with IdmTokenDto

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;
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) IdmAuthenticationException(eu.bcvsolutions.idm.core.security.api.exception.IdmAuthenticationException) IdentityNotFoundException(eu.bcvsolutions.idm.core.security.api.exception.IdentityNotFoundException) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) LoginDto(eu.bcvsolutions.idm.core.security.api.dto.LoginDto)

Example 44 with IdmTokenDto

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;
    }
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) Jwt(org.springframework.security.jwt.Jwt) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IOException(java.io.IOException) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) CodeGenerationException(dev.samstevens.totp.exceptions.CodeGenerationException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) IOException(java.io.IOException) MustChangePasswordException(eu.bcvsolutions.idm.core.security.api.exception.MustChangePasswordException) MustChangePasswordException(eu.bcvsolutions.idm.core.security.api.exception.MustChangePasswordException) IdmPasswordDto(eu.bcvsolutions.idm.core.api.dto.IdmPasswordDto) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) UUID(java.util.UUID) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) LoginDto(eu.bcvsolutions.idm.core.security.api.dto.LoginDto) Transactional(org.springframework.transaction.annotation.Transactional)

Example 45 with IdmTokenDto

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);
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) ZonedDateTime(java.time.ZonedDateTime) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Aggregations

IdmTokenDto (eu.bcvsolutions.idm.core.api.dto.IdmTokenDto)58 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)38 Test (org.junit.Test)34 GuardedString (eu.bcvsolutions.idm.core.security.api.domain.GuardedString)16 UUID (java.util.UUID)16 AbstractIntegrationTest (eu.bcvsolutions.idm.test.api.AbstractIntegrationTest)15 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)9 IdmRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleDto)8 IdmJwtAuthentication (eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication)8 IdmIdentityContractDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto)7 IdmJwtAuthenticationDto (eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto)7 LoginDto (eu.bcvsolutions.idm.core.security.api.dto.LoginDto)7 AbstractRestTest (eu.bcvsolutions.idm.test.api.AbstractRestTest)7 ConfigurationMap (eu.bcvsolutions.idm.core.api.domain.ConfigurationMap)6 Transactional (org.springframework.transaction.annotation.Transactional)6 ZonedDateTime (java.time.ZonedDateTime)5 IdmTokenFilter (eu.bcvsolutions.idm.core.api.dto.filter.IdmTokenFilter)4 EntityNotFoundException (eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException)4 AbstractReadWriteDtoControllerRestTest (eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoControllerRestTest)4 TwoFactorRegistrationResponseDto (eu.bcvsolutions.idm.core.security.api.dto.TwoFactorRegistrationResponseDto)4