Search in sources :

Example 1 with IdmTokenDto

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

the class IdmTokenController method post.

/**
 */
@Override
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("hasAuthority('" + CoreGroupPermission.TOKEN_CREATE + "')")
@ApiOperation(value = "Geerate new token", nickname = "generateToken", response = IdmTokenDto.class, tags = { IdmTokenController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = CoreGroupPermission.TOKEN_CREATE, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = CoreGroupPermission.TOKEN_CREATE, description = "") }) })
public ResponseEntity<?> post(@RequestBody IdmTokenDto dto) {
    // generate token
    BaseDto owner = getLookupService().lookupDto(dto.getOwnerType(), dto.getOwnerId());
    Assert.notNull(owner, "Owner is required to generate new token.");
    Assert.isInstanceOf(IdmIdentityDto.class, owner, "Identity owner is required to generate new token.");
    IdmIdentityDto identity = (IdmIdentityDto) owner;
    Assert.isTrue(!identity.isDisabled(), MessageFormat.format("Check identity can login: The identity [{0}] is disabled.", identity.getUsername()));
    // 
    // set static properties
    dto.setModuleId(CoreModule.MODULE_ID);
    dto.getProperties().put(JwtAuthenticationMapper.PROPERTY_PRESERVE_EXPIRATION, Boolean.TRUE);
    // 
    IdmTokenDto token = jwtTokenMapper.createToken(identity, dto);
    IdmJwtAuthenticationDto authenticationDto = jwtTokenMapper.toDto(token);
    // 
    // usable token in response after create - only once after create
    // we need to create copy to prevent changes cached token by reference
    IdmTokenDto clone = new IdmTokenDto(token);
    clone.setProperties(new ConfigurationMap(token.getProperties()));
    clone.setDisabled(token.isDisabled());
    clone.setSecretVerified(token.isSecretVerified());
    clone.setExpiration(token.getExpiration());
    clone.setIssuedAt(token.getIssuedAt());
    clone.setTokenType(token.getTokenType());
    clone.setOwnerId(token.getOwnerId());
    clone.setOwnerType(token.getOwnerType());
    clone.setExternalId(token.getExternalId());
    clone.setToken(token.getToken());
    clone.setModuleId(token.getModuleId());
    clone.getProperties().put(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, jwtTokenMapper.writeToken(authenticationDto));
    // 
    return new ResponseEntity<>(toResource(clone), HttpStatus.CREATED);
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) ResponseEntity(org.springframework.http.ResponseEntity) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) ConfigurationMap(eu.bcvsolutions.idm.core.api.domain.ConfigurationMap) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with IdmTokenDto

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

the class IdmTokenController method find.

@Override
public Page<IdmTokenDto> find(IdmTokenFilter filter, Pageable pageable, BasePermission permission) {
    Page<IdmTokenDto> results = super.find(filter, pageable, permission);
    // fill entity embedded for FE
    Map<UUID, BaseDto> loadedDtos = new HashMap<>();
    results.getContent().forEach(dto -> {
        UUID ownerId = dto.getOwnerId();
        if (!loadedDtos.containsKey(ownerId)) {
            try {
                loadedDtos.put(ownerId, getLookupService().lookupDto(dto.getOwnerType(), ownerId));
            } catch (IllegalArgumentException ex) {
                LOG.debug("Class [{}] not found on classpath (e.g. module was uninstalled)", dto.getOwnerType(), ex);
            }
        }
        dto.getEmbedded().put("ownerId", loadedDtos.get(ownerId));
    });
    return results;
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) HashMap(java.util.HashMap) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) UUID(java.util.UUID)

Example 3 with IdmTokenDto

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

the class LoginControllerRestTest method testUseDeletedToken.

@Test
public void testUseDeletedToken() throws Exception {
    IdmIdentityDto manager = getHelper().createIdentity();
    getHelper().createIdentityRole(manager, roleConfiguration.getAdminRole());
    // 
    // login as manager
    Map<String, String> login = new HashMap<>();
    login.put("username", manager.getUsername());
    login.put("password", manager.getPassword().asString());
    String response = getMockMvc().perform(post(BaseController.BASE_PATH + LoginController.AUTH_PATH).content(serialize(login)).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    UUID tokenId = getTokenId(response);
    String token = getToken(response);
    // 
    Assert.assertNotNull(tokenId);
    IdmTokenDto tokenDto = tokenManager.getToken(tokenId);
    Assert.assertFalse(tokenDto.isDisabled());
    // 
    // delete token
    tokenManager.deleteToken(tokenDto.getId());
    // 
    // test call api
    getMockMvc().perform(put(BaseController.BASE_PATH + "/identities").param(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, token).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().is4xxClientError());
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) HashMap(java.util.HashMap) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) UUID(java.util.UUID) AbstractRestTest(eu.bcvsolutions.idm.test.api.AbstractRestTest) Test(org.junit.Test)

Example 4 with IdmTokenDto

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

the class LoginControllerRestTest method testLogoutWithParameter.

@Test
public void testLogoutWithParameter() throws Exception {
    IdmIdentityDto identity = getHelper().createIdentity();
    Map<String, String> login = new HashMap<>();
    login.put("username", identity.getUsername());
    login.put("password", identity.getPassword().asString());
    String response = getMockMvc().perform(post(BaseController.BASE_PATH + LoginController.AUTH_PATH).content(serialize(login)).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    UUID tokenId = getTokenId(response);
    String token = getToken(response);
    // 
    Assert.assertNotNull(tokenId);
    // 
    IdmTokenDto tokenDto = tokenManager.getToken(tokenId);
    Assert.assertFalse(tokenDto.isDisabled());
    // 
    getMockMvc().perform(delete(BaseController.BASE_PATH + "/logout").param(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, token).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isNoContent());
    // 
    tokenDto = tokenManager.getToken(tokenId);
    Assert.assertTrue(tokenDto.isDisabled());
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) HashMap(java.util.HashMap) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) UUID(java.util.UUID) AbstractRestTest(eu.bcvsolutions.idm.test.api.AbstractRestTest) Test(org.junit.Test)

Example 5 with IdmTokenDto

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

the class LoginControllerRestTest method testSwitchUser.

@Test
public void testSwitchUser() throws Exception {
    IdmIdentityDto manager = getHelper().createIdentity();
    getHelper().createIdentityRole(manager, roleConfiguration.getAdminRole());
    // 
    // login as manager
    Map<String, String> login = new HashMap<>();
    login.put("username", manager.getUsername());
    login.put("password", manager.getPassword().asString());
    String response = getMockMvc().perform(post(BaseController.BASE_PATH + LoginController.AUTH_PATH).content(serialize(login)).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    UUID tokenId = getTokenId(response);
    String token = getToken(response);
    // 
    Assert.assertNotNull(tokenId);
    IdmTokenDto tokenDto = tokenManager.getToken(tokenId);
    Assert.assertFalse(tokenDto.isDisabled());
    List<DefaultGrantedAuthorityDto> dtoAuthorities = jwtTokenMapper.getDtoAuthorities(tokenDto);
    // 
    // check token authorities - APP_ADMIN
    Assert.assertTrue(dtoAuthorities.stream().anyMatch(a -> a.getAuthority().equals(IdmGroupPermission.APP_ADMIN)));
    // 
    // create different identity - identity create
    IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null);
    IdmRoleDto role = getHelper().createRole();
    getHelper().createIdentityRole(identity, role);
    getHelper().createBasePolicy(role.getId(), CoreGroupPermission.IDENTITY, IdmIdentity.class, IdmBasePermission.ADMIN);
    response = getMockMvc().perform(put(BaseController.BASE_PATH + "/authentication/switch-user?username=" + identity.getUsername()).param(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, token)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    // 
    // preserve token id
    UUID switchTokenId = getTokenId(response);
    token = getToken(response);
    Assert.assertEquals(tokenId, switchTokenId);
    IdmTokenDto switchTokenDto = tokenManager.getToken(switchTokenId);
    Assert.assertFalse(switchTokenDto.isDisabled());
    dtoAuthorities = jwtTokenMapper.getDtoAuthorities(switchTokenDto);
    // 
    // check authorities - no APP_ADMIN
    Assert.assertTrue(dtoAuthorities.stream().allMatch(a -> !a.getAuthority().equals(IdmGroupPermission.APP_ADMIN)));
    // 
    // check token => same owner, same id, different username in properties
    Assert.assertEquals(tokenDto.getOwnerId(), switchTokenDto.getOwnerId());
    Assert.assertEquals(identity.getUsername(), switchTokenDto.getProperties().getString(JwtAuthenticationMapper.PROPERTY_CURRENT_USERNAME));
    Assert.assertEquals(manager.getUsername(), switchTokenDto.getProperties().getString(JwtAuthenticationMapper.PROPERTY_ORIGINAL_USERNAME));
    // 
    // test create identity with switched token + check audit fields
    IdmIdentityDto createIdentity = new IdmIdentityDto(getHelper().createName());
    getMockMvc().perform(post(BaseController.BASE_PATH + "/identities").param(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, token).content(getMapper().writeValueAsString(createIdentity)).contentType(TestHelper.HAL_CONTENT_TYPE)).andExpect(status().isCreated()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    IdmIdentityDto createdIdentity = identityService.getByUsername(createIdentity.getUsername());
    Assert.assertEquals(manager.getUsername(), createdIdentity.getOriginalCreator());
    Assert.assertEquals(manager.getId(), createdIdentity.getOriginalCreatorId());
    Assert.assertEquals(identity.getUsername(), createdIdentity.getCreator());
    Assert.assertEquals(identity.getId(), createdIdentity.getCreatorId());
    // 
    // rename identity - use id in logout phase
    manager.setUsername(getHelper().createName());
    manager = identityService.save(manager);
    // 
    // switch logout => test token, authorities
    response = getMockMvc().perform(delete(BaseController.BASE_PATH + "/authentication/switch-user").param(IdmAuthenticationFilter.AUTHENTICATION_TOKEN_NAME, token)).andExpect(status().isOk()).andExpect(content().contentType(TestHelper.HAL_CONTENT_TYPE)).andReturn().getResponse().getContentAsString();
    tokenId = getTokenId(response);
    token = getToken(response);
    // 
    Assert.assertNotNull(tokenId);
    tokenDto = tokenManager.getToken(tokenId);
    Assert.assertFalse(tokenDto.isDisabled());
    dtoAuthorities = jwtTokenMapper.getDtoAuthorities(tokenDto);
    // 
    // check token authorities - APP_ADMIN
    Assert.assertTrue(dtoAuthorities.stream().anyMatch(a -> a.getAuthority().equals(IdmGroupPermission.APP_ADMIN)));
    Assert.assertEquals(tokenDto.getOwnerId(), switchTokenDto.getOwnerId());
    Assert.assertEquals(manager.getUsername(), tokenDto.getProperties().getString(JwtAuthenticationMapper.PROPERTY_CURRENT_USERNAME));
    Assert.assertEquals(manager.getUsername(), tokenDto.getProperties().getString(JwtAuthenticationMapper.PROPERTY_ORIGINAL_USERNAME));
}
Also used : IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) TwoFactorAuthenticationRequiredException(eu.bcvsolutions.idm.core.security.api.exception.TwoFactorAuthenticationRequiredException) Autowired(org.springframework.beans.factory.annotation.Autowired) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) IdmPasswordDto(eu.bcvsolutions.idm.core.api.dto.IdmPasswordDto) ResultActions(org.springframework.test.web.servlet.ResultActions) IdentityBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdentityBasePermission) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) After(org.junit.After) AuthenticationException(org.springframework.security.core.AuthenticationException) TwoFactorAuthenticationType(eu.bcvsolutions.idm.core.security.api.domain.TwoFactorAuthenticationType) TwoFactorRegistrationResponseDto(eu.bcvsolutions.idm.core.security.api.dto.TwoFactorRegistrationResponseDto) LoginService(eu.bcvsolutions.idm.core.security.api.service.LoginService) RestTemplate(org.springframework.web.client.RestTemplate) MockMvcRequestBuilders.put(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put) IdmIdentity(eu.bcvsolutions.idm.core.model.entity.IdmIdentity) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) CasConfiguration(eu.bcvsolutions.idm.core.api.config.domain.CasConfiguration) PublicCasConfiguration(eu.bcvsolutions.idm.core.api.config.domain.PublicCasConfiguration) UUID(java.util.UUID) MockMvcResultMatchers(org.springframework.test.web.servlet.result.MockMvcResultMatchers) RoleConfiguration(eu.bcvsolutions.idm.core.api.config.domain.RoleConfiguration) Resource(org.springframework.hateoas.Resource) IdmAuthenticationFilter(eu.bcvsolutions.idm.core.security.api.filter.IdmAuthenticationFilter) TokenManager(eu.bcvsolutions.idm.core.security.api.service.TokenManager) JwtAuthenticationMapper(eu.bcvsolutions.idm.core.security.service.impl.JwtAuthenticationMapper) List(java.util.List) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) IdmIdentityService(eu.bcvsolutions.idm.core.api.service.IdmIdentityService) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) LoginDto(eu.bcvsolutions.idm.core.security.api.dto.LoginDto) Mock(org.mockito.Mock) HashMap(java.util.HashMap) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) TwoFactorAuthenticationManager(eu.bcvsolutions.idm.core.security.api.service.TwoFactorAuthenticationManager) MockMvcResultMatchers.content(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content) IdmPasswordService(eu.bcvsolutions.idm.core.api.service.IdmPasswordService) MockMvcRequestBuilders.delete(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) MockMvcRequestBuilders.post(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post) InitTestDataProcessor(eu.bcvsolutions.idm.core.model.event.processor.module.InitTestDataProcessor) TestHelper(eu.bcvsolutions.idm.test.api.TestHelper) AbstractRestTest(eu.bcvsolutions.idm.test.api.AbstractRestTest) Before(org.junit.Before) DefaultGrantedAuthorityDto(eu.bcvsolutions.idm.core.security.api.dto.DefaultGrantedAuthorityDto) StringWriter(java.io.StringWriter) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) IdmProfileDto(eu.bcvsolutions.idm.core.api.dto.IdmProfileDto) IOException(java.io.IOException) Test(org.junit.Test) Mockito(org.mockito.Mockito) HttpStatus(org.springframework.http.HttpStatus) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) MockMvcRequestBuilders.get(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get) BaseController(eu.bcvsolutions.idm.core.api.rest.BaseController) ResponseEntity(org.springframework.http.ResponseEntity) IdmGroupPermission(eu.bcvsolutions.idm.core.security.api.domain.IdmGroupPermission) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) Transactional(org.springframework.transaction.annotation.Transactional) IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) HashMap(java.util.HashMap) DefaultGrantedAuthorityDto(eu.bcvsolutions.idm.core.security.api.dto.DefaultGrantedAuthorityDto) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) UUID(java.util.UUID) AbstractRestTest(eu.bcvsolutions.idm.test.api.AbstractRestTest) Test(org.junit.Test)

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