Spring Boot-@PreAuthorize在测试中不起作用

鲍里斯

我有这样的控制器

@RestController
@RequestMapping(value="/test")
@PreAuthorize("hasRole('ADMIN')")
public class TestController
{

    @RequestMapping( method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> test ()
    {

        return ResponseEntity.ok("test");
    }

}

我试图编写单元测试,它将测试访问此控制器方法的权限。

这是我的考验

@RunWith(SpringRunner.class)
@ContextConfiguration
 @WebMvcTest(value = TestController.class)
public class AUnitTest
{

    @Autowired
    private MockMvc mockMvc;

    private final String url = "/test";

    @Test
    @WithMockUser(roles="ADMIN")
    public void testAdminUser() throws Exception
    {
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(this.url );
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
    }

}

当我从@WithMockUser中删除角色并保留为空时,默认情况下它将具有USER用户角色,然后通过测试。当我放置USER和ADMIN角色时,由于USER角色,它也会通过。但是,每当我将角色设置为ADMIN时,即使我设置用户需要具有ADMIN角色才能访问控制器,它也会失败。

我尝试设置用户名,密码以及Spring Security Docs等中的所有内容

我想念什么吗?

神秘主义

尝试添加@EnableGlobalMethodSecurity(prePostEnabled = true)到测试课程。

或者像这样添加配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class Config {
    ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

@PreAuthorize isAnonymous在Spring Boot上不起作用

WebMvcConfigurer 在 Spring Boot 中不起作用?

使用autowire的Spring Boot字段注入在JUnit测试中不起作用

Spring Boot @Autowired在单元测试用例中不起作用

带有 Spring Boot 的 Ehcache 在测试环境中不起作用

使用@DataJpaTest时,Hibernate @Formula在Spring Boot测试中不起作用

json中的Json在Spring Boot中不起作用

@Transactional在带有CrudRepository的Spring Boot中不起作用

RestController在oauth2 Spring Boot中不起作用

Spring Boot 2.2.2 - Prometheus 在 Actuator 中不起作用

多模块组件扫描在Spring Boot中不起作用

注释CrossOrigin在Spring Boot中不起作用

我的BeanPostProcessor在Spring Boot中不起作用

Spring Boot - @Autowired 在 @Service 中不起作用

自定义MessageConverter在Spring Boot中不起作用

Spring Boot Kotlin项目在Eclipse中不起作用

Spring Boot DevTools在Eclipse中不起作用

Spring Boot @Scheduler 在 Google Kubernetes Engine 中不起作用

Primefaces FileUpload在Spring Boot中不起作用

spring boot中的BindingResult参数不起作用

实时重载在Spring Boot devtools中不起作用

事务注释在Spring Boot中不起作用

为什么RestController在Spring Boot中不起作用?

Spring Boot permitAll在WebSecurityConfigurerAdapter中不起作用

CommonsRequestLoggingFilter在Spring Boot应用程序中不起作用

@ConstructorBinding 在 Spring Boot 2.5.4 中似乎不起作用

部署的Spring-Boot战争在Tomcat中不起作用

Spring Boot中的异常处理程序不起作用?

Spring Boot方面在我的API中不起作用