【问题标题】:testing Spring-Security测试 Spring-Security
【发布时间】:2014-07-27 04:06:51
【问题描述】:

我的 Spring-Boot (1.1.4.RELEASE)/Spring-Security 应用程序中有几个控制器,我想在这些控制器上运行一些集成测试。但是,我不知道如何发出请求以便处理身份验证。

这是我的测试:

@ContextConfiguration(classes = OFAC, loader = SpringApplicationContextLoader)
@Transactional
@WebAppConfiguration
@IntegrationTest
class AdminControllerIntegrationTest extends Specification {

    def adminUrl = "http://localhost:9001/admin"

    @Autowired
    private AdminController adminController;

    def "test retrieving users from db table"() {

        def model = Mock(Model)
        RestTemplate restTemplate = new TestRestTemplate()

        when:
        def result = restTemplate.getForEntity(adminUrl, String.class, model)

        then:
        result != null
    }

这是我的安全配置:

@Configuration
@EnableWebMvcSecurity
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers( "/" ).permitAll()
                .antMatchers( "/resources/**" ).permitAll()
                .antMatchers( "/css/**" ).permitAll()
                .antMatchers( "/libs/**" ).permitAll();

        http
                .formLogin().failureUrl( "/login?error" )
                .defaultSuccessUrl( "/" )
                .loginPage( "/login" )
                .permitAll()
                .and()
                .logout().logoutRequestMatcher( new AntPathRequestMatcher( "/logout" ) ).logoutSuccessUrl( "/" )
                .permitAll();

        http
                .sessionManagement()
                .maximumSessions( 1 )
                .expiredUrl( "/login?expired" )
                .maxSessionsPreventsLogin( true )
                .and()
                .sessionCreationPolicy( SessionCreationPolicy.IF_REQUIRED )
                .invalidSessionUrl( "/" );

        http
                .authorizeRequests().anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService( customUserDetailsService ).passwordEncoder( encoder );
    }

当我调试该代码时,我得到的结果是登录 html。我相信这意味着身份验证失败(并且因为我没有在任何地方定义用户/密码)并且我的请求被重定向到登录页面。

我寻找了一种针对此类运行集成测试的好方法,但没有找到好的解决方案。如果有人有任何关于如何处理这个问题的例子,我希望你能帮助

【问题讨论】:

    标签: spring-security spring-boot


    【解决方案1】:

    我认为要进行这种测试,您别无选择,只能 POST 到登录表单并提取会话 cookie,这样您就可以将它与您实际需要测试的请求一起发送。像这样的:

    private String loginAndGrabCookie() {
    
        ResponseEntity<String> page = serverRunning.getForString("/sparklr2/login.jsp");
        String cookie = page.getHeaders().getFirst("Set-Cookie");
        Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*").matcher(page.getBody());
    
        MultiValueMap<String, String> formData;
        formData = new LinkedMultiValueMap<String, String>();
        formData.add("j_username", "marissa");
        formData.add("j_password", "koala");
        if (matcher.matches()) {
            formData.add("_csrf", matcher.group(1));
        }
    
        String location = "/sparklr2/login.do";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cookie", cookie);
        headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
        ResponseEntity<Void> result = serverRunning.postForStatus(location, headers , formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        cookie = result.getHeaders().getFirst("Set-Cookie");
    
        assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
    
        return cookie;
    
    }
    

    (取自https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/sparklr/src/test/java/org/springframework/security/oauth2/provider/AuthorizationCodeProviderTests.java#L381。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2013-01-11
      • 2017-07-08
      • 2013-12-21
      • 1970-01-01
      • 2021-12-08
      • 2015-07-14
      相关资源
      最近更新 更多