2016-09-11 135 views
0

我有一个现有的Web应用程序使用spring security进行身份验证。它也使用会话管理来允许用户登录一段预定的时间,并使用XSRF令牌来防止XSS攻击。Spring安全会话/ xsrf路径配置

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    // @formatter:off 
    http 
    .exceptionHandling() 
     .authenticationEntryPoint(restEntryPoint()) 
    .and() 
    .headers().addHeaderWriter(new StaticHeadersWriter("Server","")) 
    .and() 
    .httpBasic() 
     .authenticationEntryPoint(restEntryPoint()) 
    .and() 
    .logout().addLogoutHandler(myLogoutHandler()) 
    .logoutSuccessHandler(logoutSuccessHandler()) 
    .and() 
    .authorizeRequests() 
     .antMatchers("/index.html", "/login", "/").permitAll() 
     .antMatchers(HttpMethod.OPTIONS).denyAll() 
     .antMatchers(HttpMethod.HEAD).denyAll() 
     .anyRequest().authenticated() 
    .and() 
    .authenticationProvider(myAuthenticationProvider) 
     .csrf() 
      .csrfTokenRepository(csrfTokenRepository()) 
    .and() 
    .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); 
    // @formatter:on 
} 

这对Web应用程序非常有用。然而,现在我被要求添加一个配置,允许第三方客户端应用程序通过纯REST调用来调用我的服务,也就是说它们应该是完全无状态的并且使用http基本认证 - 不应该创建任何会话,并且应该禁用xsrf(I认为...)。

我可以为所有这些客户端API调用定义一个共享URL路径。但是,我如何利用现有的安全配置和服务器来支持这两种需求?

回答

0

回答我的问题...

春季安全允许您使用基于顺序多种配置。在本文档中,它提供了以下示例:

@EnableWebSecurity 
public class MultiHttpSecurityConfig { 
    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) { 1 
     auth 
      .inMemoryAuthentication() 
       .withUser("user").password("password").roles("USER").and() 
       .withUser("admin").password("password").roles("USER", "ADMIN"); 
    } 

    @Configuration 
    @Order(1)              2 
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
       .antMatcher("/api/**")        3 
       .authorizeRequests() 
        .anyRequest().hasRole("ADMIN") 
        .and() 
       .httpBasic(); 
     } 
    } 

    @Configuration             4 
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
       .authorizeRequests() 
        .anyRequest().authenticated() 
        .and() 
       .formLogin(); 
     } 
    } 
} 

在上述示例中,/ API将只允许用于ADMIN角色,而其它路径将与缺省FormLoginWebSecurityConfigurerAdapter进行配置。

查看更多的在this URL