Spring Security不会使用Spring Session EnableRedisHttpSession重用身份验证数据

时间:2015-03-31 21:57:20

标签: java angularjs spring-security spring-boot spring-session

我能够使用https://github.com/dsyer/spring-security-angular/blob/master/vanilla/README.md中的示例spring boot Groovy Maven实现成功运行此配置。当应用程序代码在Java和Gradle 2.3中实现时,它无法正常工作。在这种情况下,OPTIONS响应有一个新的X-Auth-Token。

尝试使用提供的maven构建与我的java类,并仍然得到相同的OPTIONS 401未经授权的响应。所以这不是Gradle问题。

将两个ResourceApplication Groovy类复制到我的Gradle构建中,Angular ui成功获取OPTIONS 200 OK。因此,Java中的Spring CORS过滤器存在问题。

我有java和groovy的Gradle插件,sourceCompatibility和 targetCompatibility = 1.7

java版“1.8.0_31” Java(TM)SE运行时环境(版本1.8.0_31-b13) Java HotSpot(TM)64位服务器VM(版本25.31-b07,混合模式)

开发人员控制台日志验证是否已从ui服务器发送并由angular客户端接收到相同的令牌,但报告的CORS错误。

阻止跨源请求:同源策略禁止在http://localhost:9000/读取远程资源。这可以通过将资源移动到同一域或启用CORS来解决。本地主机:9000

@SpringBootApplication
@RestController
@EnableRedisHttpSession
public class AngularDemoApplication {
@RequestMapping("/user")
public Principal user(Principal user) {
  return user;
}

@RequestMapping("/token")
@ResponseBody
public Map<String,String> token(HttpSession session) {
  logger.debug("********** TOKEN *********** = "+session.getId());
  return Collections.singletonMap("token", session.getId());
}

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.httpBasic().and().logout().and().authorizeRequests()
        .antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll()
        .anyRequest().authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository())
        .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
  }

  private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                        .getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }


  private CsrfTokenRepository csrfTokenRepository() {
      HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
      repository.setHeaderName("X-XSRF-TOKEN");
      return repository;
  }
}

public static void main(String[] args) {
    SpringApplication.run(AngularDemoApplication.class, args);
}

}

@SpringBootApplication
@RestController
@EnableRedisHttpSession
public class ResourceApplication {

@RequestMapping("/")
public Map<String,Object> home() {
      Map<String,Object> model = new HashMap<String,Object>();
      model.put("id", UUID.randomUUID().toString());
      model.put("content", "Hello World");
      return model;
}


@Bean
public HeaderHttpSessionStrategy sessionStrategy() {
    return new HeaderHttpSessionStrategy();
 }

public static void main(String[] args) {
    SpringApplication.run(ResourceApplication.class, args);
}

}

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorsFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with");
    if (request.getMethod() != "OPTIONS" ) {
        chain.doFilter(req, res);
    } else {
         }

}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub

}

@Override
public void destroy() {
    // TODO Auto-generated method stub

}

}

Groovy版本:

请求方法:选项
状态代码:200 OK

请求标题:
主持人:localhost:9000
User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64; rv:36.0)Gecko / 20100101 Firefox / 36.0
接受:text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8
接受语言:en-US,en; q = 0.5
Accept-Encoding:gzip,deflate
来源:localhost:8080
访问控制请求方法:GET
Access-Control-Request-Headers:x-auth-token,x-requested-with
连接:保持活力

响应标题:
Access-Control-Allow-Headers:x-auth-token,x-requested-with
访问控制允许方法:POST,PUT,GET,OPTIONS,DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
内容长度:0
日期:2015年3月31日星期二21:20:28 GMT
服务器:Apache-Coyote / 1.1

请求方法:GET
状态代码:200 OK

请求标题:
主持人:localhost:9000 User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64; rv:36.0)Gecko / 20100101 Firefox / 36.0
接受:application / json,text / plain, /
接受语言:en-US,en; q = 0.5
Accept-Encoding:gzip,deflate
X-Auth-Token:80e0c2d2-dab4-435d-886e-ae28bc8e636f
X-Requested-With:XMLHttpRequest

响应标题:
Access-Control-Allow-Headers:x-auth-token,x-requested-with
访问控制允许方法:POST,PUT,GET,OPTIONS,DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Content-Type:application / json; charset = UTF-8
日期:2015年3月31日星期二21:20:28 GMT
服务器:Apache-Coyote / 1.1
严格运输安全:max-age = 31536000; includeSubDomains
转移编码:分块
推荐人:localhost:8080 /
来源:localhost:8080
连接:保持活力

Redis服务器密钥:
1)“spring:session:expirations:1427838660000”
2)“spring:session:sessions:80e0c2d2-dab4-435d-886e-ae28bc8e636f”

Java版本:

请求方法:选项
状态码:401未经授权

请求标题:
主持人:localhost:9000
User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64; rv:36.0)Gecko / 20100101 Firefox / 36.0
接受:text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8
接受语言:en-US,en; q = 0.5
Accept-Encoding:gzip,deflate
来源:localhost:8080
访问控制请求方法:GET
Access-Control-Request-Headers:x-auth-token,x-requested-with
连接:保持活力

响应标题:
Access-Control-Allow-Headers:x-auth-token,x-requested-with
访问控制允许方法:POST,PUT,GET,OPTIONS,DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
允许:GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH
内容长度:0
日期:2015年3月31日星期二20:50:26 GMT
服务器:Apache-Coyote / 1.1
严格运输安全:max-age = 31536000; includeSubDomains
WWW-Authenticate:Basic realm =“Spring”
X-Auth-Token:8af7e1f4-e723-4ce6-8d21-54a7b10369f8

Redis服务器密钥:
1)“spring:session:sessions:8af7e1f4-e723-4ce6-8d21-54a7b10369f8”
2)“spring:session:expirations:1427836860000”
3)“spring:session:sessions:c6a6cc31-eddc-40dd-99de-a6e1eecbf519”

1 个答案:

答案 0 :(得分:1)

在Java&#34;!=&#34;运算符与Groovy不同。要进行字符串对象比较,请使用equals方法。即

if( !"OPTIONS".equals(request.getMethod()))