antmatcher()。permitAll仅在运行junit MVC测试时不起作用

时间:2019-11-02 16:58:24

标签: java spring junit

我有一个像这样的控制器:

@ExtendWith(SpringExtension.class)
@RestController
@RequestMapping("/")
public class TestController {
    @GetMapping(value = "test")
    public String test() {
        return "Api running";
    }
}

我有以下测试课:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestController.class)
@AutoConfigureMockMvc
public class TestControllerTest {
    private final String BASE_URL = "https://localhost:8080";
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnOk() throws Exception{
        this.mockMvc.perform(get("/test"))
                .andExpect(status().isOk());
    }
}

我的WebSecurityConfig http配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {

// Disable CSRF (cross site request forgery)
http.csrf().disable();

// No session will be created or used by spring security
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

// Entry points
http.authorizeRequests()//
    .antMatchers("/users/signin").permitAll()//
    .antMatchers("/users/signup").permitAll()//
    .antMatchers("/h2-console/**/**").permitAll()
    .antMatchers("/test").permitAll()
    // Disallow everything else..
    .anyRequest().authenticated();

// If a user try to access a resource without having enough permissions
http.exceptionHandling().accessDeniedPage("/login");

// Apply JWT
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

// Optional, if you want to test the API from a browser
// http.httpBasic();
}

当我从邮递员发出http呼叫时,antMatcher可以正常工作:

response to call in postman

但是当我运行测试类时,会得到以下响应:

java.lang.AssertionError: Status 
Expected :200
Actual   :401
<Click to see difference>

我正在使用intellij IDEA。我的文件夹结构如下:

folder structure

似乎我需要在测试中分别配置应用程序,但我不知道该怎么做。

如何使我的antmatcher允许请求通过测试?

更新: 不知道这是否重要,但是我注意到我的请求将转到与运行我的应用程序的端口不同的端口:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /test
       Parameters = {}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[https://localhost:8443/test]}

我的应用程序正在:8080上运行,但正在将请求发送到':8443`。如果我这样对URL进行硬编码,它甚至会执行此操作:(进一步更新:@SimonMartinelli指出这是因为它正在进行https调用,所以这不是问题。)

this.mockMvc.perform(get(BASE_URL+ "/test"))

又一次更新:似乎几乎可以肯定发生了,因为我的http.authorizeRequests()方法没有运行。那么如何获得授权请求呢?

0 个答案:

没有答案