首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Springboot单元测试中,MockMvc返回403禁止

在Springboot单元测试中,MockMvc返回403禁止
EN

Stack Overflow用户
提问于 2020-11-14 00:37:57
回答 2查看 685关注 0票数 1

在Springboot unit Test always return 403 error中,我尝试了各种不同的配置,使用带有secure false的AutoConfigureMockMvc,并且排除了安全自动配置,得到了403 error。有人能帮我这个忙吗。

下面是我的安全实现

代码语言:javascript
运行
复制
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationEventPublisher(authenticationEventPublisher())
                .userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .anonymous()
                .disable()
                .authorizeRequests()
                .antMatchers("/api-docs/**")
                .permitAll();
    }

    @Bean
    public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
        return new DefaultAuthenticationEventPublisher();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
   }

共享Api实现类,添加了PreAuthorize -Admin,以查看所有用户

代码语言:javascript
运行
复制
@RestController
@RequestMapping("/api/userInfo")
public class UserController {

    private final Logger LOG = Logger.getLogger(getClass());

    private String serviceMsg = "serviceMsg";

    @Autowired
    private UserService userService;

    @Autowired
    private UserServiceUtil util;

    
    @PreAuthorize("hasAnyRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, produces = "application/json" )
    @ApiOperation(value = "Get details of all RA2 users in a paginated JSON format")
    public Page<User> listUser(Pageable pageable) {
        return userService.getUserSummary(pageable);
    }

这是我的JUnit测试,我发送get请求并返回403错误。

代码语言:javascript
运行
复制
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc(addFilters = false)

public class UserControllerTest {
    
    @Configuration
    
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class TestConfiguration {
         @Bean
         @Primary
         public UserService getUserService(){
               return Mockito.mock(UserService.class);
         }
         
         @Bean
         @Primary
         public UserServiceUtil getUserServiceUtil(){
               return Mockito.mock(UserServiceUtil.class);
         }
    }
    @Autowired
    private MockMvc mockMvc;
    
    @Autowired
    private WebApplicationContext webApplicationContext ;

    
    
    private String serviceMsg = "serviceMsg";

    @Autowired
    private UserService userService;

    @Autowired
    private UserServiceUtil util;
    
    private User admin;
    private User user;
    
    @Before
    public void setup() {

        mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext ).apply(springSecurity()).build();
        }

    @WithMockUser(username = "test",authorities ="ADMIN")
    @Test
    public void getuserList() throws Exception {
        List<User> list = new ArrayList<User>();
        list.add(new User());
        Page<User> page = new PageImpl<User>(list, null, list.size());
        Mockito.when(userService.getUserSummary(any(Pageable.class))).thenReturn(page);
        this.mockMvc.perform(get("/api/userInfo?page=1&size=10").with(csrf()).contentType(MediaType.APPLICATION_JSON)).
        andExpect(status().isOk()).andDo(MockMvcResultHandlers.print());
      }
    ```
EN

回答 2

Stack Overflow用户

发布于 2020-11-16 16:00:36

使用@WithMockUser时,authoritiesroles是不同的

代码语言:javascript
运行
复制
/**
 * <p>
 * The roles to use. The default is "USER". A {@link GrantedAuthority} will be created
 * for each value within roles. Each value in roles will automatically be prefixed
 * with "ROLE_". For example, the default will result in "ROLE_USER" being used.
 * </p>
 * <p>
 * If {@link #authorities()} is specified this property cannot be changed from the
 * default.
 * </p>
 * @return
 */
String[] roles() default { "USER" };

/**
 * <p>
 * The authorities to use. A {@link GrantedAuthority} will be created for each value.
 * </p>
 *
 * <p>
 * If this property is specified then {@link #roles()} is not used. This differs from
 * {@link #roles()} in that it does not prefix the values passed in automatically.
 * </p>
 * @return
 */
String[] authorities() default {};

无论您使用authorities 设置什么,都不会为提供任何前缀。

由于您的控制器需要ROLE_ADMIN,因此请尝试使用roles

除此之外,我还会尝试使用使用@WebMvcTestsliced Spring Context来进行此测试。对于这样的测试,不需要使用@SpringBootTest启动整个Spring上下文。

票数 0
EN

Stack Overflow用户

发布于 2020-11-16 18:49:33

删除了@SpringBootTest,添加了@WebMvcTest和角色,但得到了403。

代码语言:javascript
运行
复制
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = UserController.class)
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc(addFilters = false)

public class UserControllerTest {
    
    @Configuration
    
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class TestConfiguration {
         @Bean
         @Primary
         public UserService getUserService(){
               return Mockito.mock(UserService.class);
         }
         
         @Bean
         @Primary
         public UserServiceUtil getUserServiceUtil(){
               return Mockito.mock(UserServiceUtil.class);
         }
    }
    @Autowired
    private MockMvc mockMvc;
    
    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private UserService userService;

    @Autowired
    private UserServiceUtil util;

    
    @Before
    public void setup() {

        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity()).build();
           }
    @WithMockUser(username = "Ram",roles ="ADMIN")
    @Test
    public void getuserList() throws Exception {
        List<User> list = new ArrayList<User>();
        Page<User> page = new PageImpl<User>(list, null, list.size());
        Mockito.when(userService.getUserSummary(any(Pageable.class))).thenReturn(page);
        this.mockMvc.perform(get("/api/userInfo?page=1&size=10").with(csrf()).contentType(MediaType.APPLICATION_JSON)).
        andExpect(status().isOk()).andDo(MockMvcResultHandlers.print());
      }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64824625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档