测试期间的Spring MockMVC,Spring安全性和全局方法安全性

问题描述 投票:0回答:2

我有以下用户资源,方法createUser被保护到ADMIN角色。

@RestController
@RequestMapping("/api")
public class UserResource {

    @PostMapping("/users")
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException {
        log.debug("REST request to save User : {}", userDTO);
        // rest of code
    }
}

并按照春季开机测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyappApp.class)
public class UserResourceIntTest {

    // other dependencies

    @Autowired
    FilterChainProxy springSecurityFilterChain;

    private MockMvc restUserMockMvc;

    private User user;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        UserResource userResource = new UserResource(userRepository, userService, mailService);
        this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setMessageConverters(jacksonMessageConverter)
            .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
            .build();
    }



@Test
@Transactional
@WithMockUser(username="user", password = "user", authorities = {"ROLE_USER"})
public void createUser() throws Exception {
    // Create the User
    ManagedUserVM managedUserVM = new ManagedUserVM();
    // set user properties

    restUserMockMvc.perform(post("/api/users")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
        .andExpect(status().isCreated());
    }
}

我希望测试失败,因为api仅允许ADMIN角色,而mock使用USER角色,但测试正在通过。任何帮助将非常感激。

java spring spring-boot spring-security jhipster
2个回答
0
投票

注意:我使用的JHipster版本是5.2.0。不保证这适用于所有版本。

如果您正在使用服务(您应该使用),则可以注释服务方法。在集成测试中使用@WithMockUser应该只需工作而无需进行任何其他更改。这是一个例子。请注意,我也使用服务接口(在JDL中传递“serviceImpl”标志),但它也可以在服务实现中使用。

/**
* Service Interface for managing Profile.
*/
public interface ProfileService {

/**
 * Delete the "id" profile.
 *
 * @param id the id of the entity
 */
@Secured(AuthoritiesConstants.ADMIN)
void delete(Long id);

相应的休息控制器方法(由JHipster自动生成):

/**
 * DELETE  /profiles/:id : delete the "id" profile.
 *
 * @param id the id of the profileDTO to delete
 * @return the ResponseEntity with status 200 (OK)
 */
@DeleteMapping("/profiles/{id}")
@Timed
public ResponseEntity<Void> deleteProfile(@PathVariable Long id) {
    log.debug("REST request to delete Profile : {}", id);
    profileService.delete(id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}

-1
投票

尝试删除@WithMockUser注释并更改测试方法,如下所示

ManagedUserVM managedUserVM = new ManagedUserVM();
    managedUserVM.setLogin(DEFAULT_LOGIN);
    managedUserVM.setPassword(DEFAULT_PASSWORD);
   managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

完整的测试。你可以参考这个。

Test Class

© www.soinside.com 2019 - 2024. All rights reserved.