【问题标题】:How to test spring boot security ssl controller如何测试 Spring Boot 安全 ssl 控制器
【发布时间】:2017-06-08 23:04:19
【问题描述】:

我们有一个使用 spring-boot-security 并配置为使用 ssl 的应用程序。

以下是我的安全配置

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .anyRequest().fullyAuthenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error").permitAll()
            .and()
                .logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
                .exceptionHandling().accessDeniedPage("/access?error");
        // @formatter:on
    }

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception
{
    auth.inMemoryAuthentication().withUser("admin").password("admin")
            .roles("ADMIN", "USER", "ACTUATOR").and().withUser("user")
            .password("user").roles("USER");
}

我们有一个方法级别的安全控制器,代码如下

@GetMapping("/")
@Secured("ROLE_ADMIN")
public String home(Map<String, Object> model)
{
    model.put("message", "Hello World");
    model.put("title", "Hello Home");
    model.put("date", new Date());
    return "home";
}

现在我们想使用@WebMvcTest注解为控制器编写Junit案例,所以首先我想登录然后检查映射/

我把JUNIT测试用例写成

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HomeController.class, secure = true)
public class HomeControllerTest
{
    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup()
    {
        mvc = MockMvcBuilders.webAppContextSetup(context)
                .apply(springSecurity()).build();
    }

    @Test
    // @WithMockUser(authorities = "ADMIN")
    public void testHome() throws Exception
    {
        /*
         * TestSecurityContextHolder.getContext().setAuthentication( new
         * UsernamePasswordAuthenticationToken("admin", "admin", AuthorityUtils
         * .commaSeparatedStringToAuthorityList("ROLE_ADMIN")));
         */
        this.mvc.perform(formLogin("/login").user("u", "admin").password("p", "admin"))
                /*
                 * get("/").with(user("admin").password("pass").roles("USER",
                 * "ADMIN")) .accept(MediaType.APPLICATION_JSON_UTF8))
                 */
                .andExpect(authenticated()).andDo(print());
    }

}

如何确保我的 JUNIT 按预期工作。下面是我的 print() 方法日志。我看到那个端口不见了,怎么设置?

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /login
       Parameters = {u=[admin], p=[admin], _csrf=[3f104e63-4a77-487c-9d1c-8b7cf2c2cead]}
          Headers = {Accept=[application/x-www-form-urlencoded]}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 302
    Error message = null
          Headers = {Location=[https://localhost/login]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = https://localhost/login
          Cookies = []

项目代码库见github

【问题讨论】:

    标签: spring-boot spring-security spring-test-mvc


    【解决方案1】:

    对于初学者,您可能应该在配置基于表单的登录时设置defaultSuccessUrl()(例如,通过将其设置为“/”)。然后用户将在成功登录尝试后被重定向。

    配置完成后,测试用例会更容易。

    您可以先使用.andExpect(redirectedUrl("/")) 测试成功登录是否重定向到主页(“/”)。这应该是一种测试方法。

    在使用@WithMockUser(roles = "ADMIN") 注释的第二种测试方法中,您可以验证 ADMIN 是否被允许访问主页(“/”)。

    关于端口号,如果确定确实需要设置自定义端口,应该可以在ApplicationContext中注册一个自定义的SpringBootMockMvcBuilderCustomizer作为bean,用它来设置可以指定的默认请求您的自定义端口。

    问候,

    山姆

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 2018-01-02
      • 2016-05-28
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多