首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试Spring-Security

测试Spring-Security
EN

Stack Overflow用户
提问于 2014-07-27 12:06:51
回答 1查看 450关注 0票数 0

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

这是我的测试:

代码语言:javascript
复制
@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
    }

下面是我的安全配置:

代码语言:javascript
复制
@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。我认为这意味着身份验证失败(因为我还没有定义用户/password anywhere),并且我的请求被重定向到登录页面。

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

EN

回答 1

Stack Overflow用户

发布于 2014-07-30 10:01:48

我认为要做这样的测试,你别无选择,只能发布到登录表单并提取会话cookie,这样你就可以将它与你实际需要测试的请求一起发送。如下所示:

代码语言:javascript
复制
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。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24977821

复制
相关文章

相似问题

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