Search in sources :

Example 16 with IdmTokenDto

use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.

the class LoginController method casLoginResponse.

/**
 * Redirect to FE, after CAS authentication.
 *
 * @return redirect to FE
 * @since 12.0.0
 */
@RequestMapping(path = CAS_LOGIN_RESPONSE_PATH, method = RequestMethod.GET)
public ResponseEntity<Void> casLoginResponse() {
    // process ticket + add token into url parameter
    IdmTokenDto currentToken = tokenManager.getCurrentToken();
    StringBuilder url = new StringBuilder(configurationService.getFrontendUrl(CAS_LOGIN_RESPONSE_PATH));
    // set token into url - ok
    if (currentToken != null) {
        IdmJwtAuthentication authentication = jwtTokenMapper.fromDto(currentToken);
        url.append('?');
        url.append(JwtAuthenticationMapper.AUTHENTICATION_TOKEN_NAME.toLowerCase());
        url.append('=');
        url.append(jwtTokenMapper.writeToken(authentication));
    } else if (ctx != null) {
        // not - ok => resolve exception
        ResultCodeException resultCodeException = ctx.getCodeEx();
        if (resultCodeException == null) {
            // resolve concrete exception
            url.append("?status-code=");
            if (ctx.getAuthEx() instanceof IdentityNotFoundException) {
                // same as from standard login
                url.append(CoreResultCode.AUTH_FAILED.getCode().toLowerCase());
            } else if (ctx.getAuthEx() instanceof IdentityDisabledException) {
                // same as from standard login
                url.append(CoreResultCode.AUTH_FAILED.getCode().toLowerCase());
            } else if (ctx.getAuthEx() instanceof CasTicketValidationException) {
                url.append(CoreResultCode.CAS_TICKET_VALIDATION_FAILED.getCode().toLowerCase());
            } else {
                // common error - login failed
                url.append(CoreResultCode.LOG_IN_FAILED.getCode().toLowerCase());
            }
        } else if (resultCodeException instanceof TwoFactorAuthenticationRequiredException) {
            // handle two factor login
            url.append('?');
            url.append(JwtAuthenticationMapper.AUTHENTICATION_TOKEN_NAME.toLowerCase());
            url.append('=');
            url.append(((TwoFactorAuthenticationRequiredException) resultCodeException).getToken());
        } else {
            // concrete status code form result code exception
            url.append("?status-code=");
            url.append(resultCodeException.getError().getError().getStatusEnum().toLowerCase());
        }
    }
    // 
    return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, url.toString()).build();
}
Also used : IdentityDisabledException(eu.bcvsolutions.idm.core.security.api.exception.IdentityDisabledException) IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) CasTicketValidationException(eu.bcvsolutions.idm.core.security.api.exception.CasTicketValidationException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdentityNotFoundException(eu.bcvsolutions.idm.core.security.api.exception.IdentityNotFoundException) TwoFactorAuthenticationRequiredException(eu.bcvsolutions.idm.core.security.api.exception.TwoFactorAuthenticationRequiredException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 17 with IdmTokenDto

use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.

the class JwtAuthenticationMapper method fromDto.

/**
 * Converts dto to authentication.
 * Authentication authorities are loaded or filled from persisted token.
 * If token not exists, then is created.
 * Actual authentication informations are returned
 *
 * @param dto
 * @return
 */
public IdmJwtAuthentication fromDto(IdmJwtAuthenticationDto dto) {
    Assert.notNull(dto, "Authentication DTO is required to be transformed to authentication.");
    UUID currentIdentityId = dto.getCurrentIdentityId();
    Assert.notNull(dto.getCurrentIdentityId(), "Current identity identifier is required.");
    // 
    IdmIdentityDto identity = new IdmIdentityDto(currentIdentityId, dto.getCurrentUsername());
    // try to load token or create a new one
    IdmTokenDto token;
    if (dto.getId() == null) {
        token = new IdmTokenDto();
        // required not overridable properties
        token.setTokenType(AUTHENTICATION_TOKEN_NAME);
        token.setOwnerId(dto.getCurrentIdentityId());
        token.setOwnerType(tokenManager.getOwnerType(IdmIdentityDto.class));
        token.setIssuedAt(dto.getIssuedAt());
        token.setExpiration(dto.getExpiration());
        ConfigurationMap properties = token.getProperties();
        properties.put(PROPERTY_AUTHORITIES, getDtoAuthorities(grantedAuthoritiesFactory.getGrantedAuthoritiesForIdentity(currentIdentityId)));
        properties.put(PROPERTY_CURRENT_USERNAME, identity.getUsername());
        properties.put(PROPERTY_CURRENT_IDENTITY_ID, currentIdentityId);
        properties.put(PROPERTY_ORIGINAL_USERNAME, dto.getOriginalUsername());
        properties.put(PROPERTY_ORIGINAL_IDENTITY_ID, dto.getOriginalIdentityId());
        // 
        // token id has to be written into token
        token.setId(UUID.randomUUID());
        token.setToken(getTokenHash(token));
        token = tokenManager.saveToken(identity, token);
    } else {
        token = tokenManager.getToken(dto.getId());
        // delete token => same behavior as logout @since 10.8.0
        if (token == null) {
            LOG.debug("Token [{}] not found. New authentication is required.");
            // 
            throw new ResultCodeException(CoreResultCode.TOKEN_NOT_FOUND);
        }
    }
    IdmJwtAuthentication authentication = new IdmJwtAuthentication(token.getId(), identity, new IdmIdentityDto(dto.getOriginalIdentityId(), dto.getOriginalUsername()), token.getExpiration(), token.getIssuedAt(), null, dto.getFromModule());
    // 
    Collection<DefaultGrantedAuthorityDto> authorities = getDtoAuthorities(token);
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    if (authorities != null) {
        for (DefaultGrantedAuthorityDto a : authorities) {
            grantedAuthorities.add(new DefaultGrantedAuthority(a.getAuthority()));
        }
    } else {
        grantedAuthorities.addAll(grantedAuthoritiesFactory.getGrantedAuthoritiesForIdentity(currentIdentityId));
    }
    authentication.setAuthorities(grantedAuthorities);
    // 
    return authentication;
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) DefaultGrantedAuthorityDto(eu.bcvsolutions.idm.core.security.api.dto.DefaultGrantedAuthorityDto) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) ArrayList(java.util.ArrayList) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) ConfigurationMap(eu.bcvsolutions.idm.core.api.domain.ConfigurationMap) UUID(java.util.UUID) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority)

Example 18 with IdmTokenDto

use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.

the class DefaultTokenManager method getCurrentToken.

@Override
public IdmTokenDto getCurrentToken() {
    if (!securityService.isAuthenticated()) {
        // not authenticated
        return null;
    }
    // IdM token has to exist
    UUID tokenId = securityService.getId();
    if (tokenId == null) {
        LOG.debug("Identity [{}] was logged some external way, logout is not supported.", securityService.getCurrentUsername());
        return null;
    }
    IdmTokenDto token = getToken(tokenId);
    if (token == null) {
        LOG.debug("Identity [{}] was logged some external way, logout is not supported.", securityService.getCurrentUsername());
        return null;
    }
    // 
    return token;
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) UUID(java.util.UUID)

Example 19 with IdmTokenDto

use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.

the class DefaultTokenManager method getToken.

@Override
public IdmTokenDto getToken(UUID tokenId, BasePermission... permission) {
    ValueWrapper value = cacheManager.getValue(TOKEN_CACHE_NAME, tokenId);
    if (value != null) {
        return (IdmTokenDto) value.get();
    }
    // 
    IdmTokenDto token = tokenService.get(tokenId, permission);
    cacheManager.cacheValue(TOKEN_CACHE_NAME, tokenId, token);
    // 
    return token;
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) ValueWrapper(eu.bcvsolutions.idm.core.api.config.cache.domain.ValueWrapper)

Example 20 with IdmTokenDto

use of eu.bcvsolutions.idm.core.api.dto.IdmTokenDto in project CzechIdMng by bcvsolutions.

the class DefaultIdmIdentityServiceIntegrationTest method testReferentialIntegrity.

@Test
@Transactional
public void testReferentialIntegrity() {
    IdmIdentityDto identity = getHelper().createIdentity();
    String username = identity.getUsername();
    // eav
    IdmFormDefinitionDto formDefinition = formService.getDefinition(IdmIdentity.class);
    IdmFormValueDto value1 = new IdmFormValueDto(formDefinition.getMappedAttributeByCode(InitDemoDataProcessor.FORM_ATTRIBUTE_PASSWORD));
    value1.setValue("one");
    formService.saveValues(identity.getId(), IdmIdentity.class, formDefinition, Lists.newArrayList(value1));
    // role with guarantee
    IdmRoleDto role = getHelper().createRole();
    getHelper().createRoleGuarantee(role, identity);
    // contract
    IdmIdentityContractDto contract = getHelper().createContract(identity);
    // contract guarantee
    IdmIdentityContractDto contract2 = getHelper().createContract(identityService.getByUsername(InitTestDataProcessor.TEST_USER_1));
    contractGuaranteeService.save(new IdmContractGuaranteeDto(contract2.getId(), identity.getId()));
    // assigned role
    getHelper().createIdentityRole(contract, role);
    IdmIdentityRoleFilter identityRolefilter = new IdmIdentityRoleFilter();
    identityRolefilter.setIdentityId(identity.getId());
    // profile
    getHelper().createProfile(identity);
    // token
    IdmTokenDto token = new IdmTokenDto();
    token.setToken("token");
    token.setTokenType("test");
    token = tokenManager.saveToken(identity, token);
    // 
    Assert.assertNotNull(tokenManager.getToken(token.getId()));
    Assert.assertNotNull(profileService.findOneByIdentity(identity.getId()));
    Assert.assertNotNull(identityService.getByUsername(username));
    Assert.assertNotNull(passwordService.findOneByIdentity(identity.getId()));
    Assert.assertEquals(1, formService.getValues(identity).size());
    Assert.assertEquals(identity.getId(), roleGuaranteeService.findByRole(role.getId(), null).getContent().get(0).getGuarantee());
    Assert.assertEquals(1, identityRoleService.find(identityRolefilter, null).getTotalElements());
    // + default contract is created
    Assert.assertEquals(2, identityContractService.findAllByIdentity(identity.getId()).size());
    IdmContractGuaranteeFilter filter = new IdmContractGuaranteeFilter();
    filter.setIdentityContractId(contract2.getId());
    List<IdmContractGuaranteeDto> guarantees = contractGuaranteeService.find(filter, null).getContent();
    Assert.assertEquals(1, guarantees.size());
    Assert.assertEquals(identity.getId(), guarantees.get(0).getGuarantee());
    // 
    identityService.delete(identity);
    role = roleService.get(role.getId());
    // 
    Assert.assertEquals(0L, roleGuaranteeService.findByRole(role.getId(), null).getTotalElements());
    Assert.assertNull(identityService.getByUsername(username));
    Assert.assertNull(passwordService.findOneByIdentity(identity.getId()));
    Assert.assertEquals(0, identityContractService.findAllByIdentity(identity.getId()).size());
    Assert.assertEquals(0, identityRoleService.find(identityRolefilter, null).getTotalElements());
    Assert.assertEquals(0, contractGuaranteeService.find(filter, null).getTotalElements());
    Assert.assertNull(profileService.findOneByIdentity(identity.getId()));
    Assert.assertTrue(tokenManager.getToken(token.getId()).isDisabled());
}
Also used : IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) IdmContractGuaranteeDto(eu.bcvsolutions.idm.core.api.dto.IdmContractGuaranteeDto) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) IdmIdentityContractDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto) IdmContractGuaranteeFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmContractGuaranteeFilter) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Test(org.junit.Test) Transactional(org.springframework.transaction.annotation.Transactional)

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