【发布时间】:2016-05-24 07:06:33
【问题描述】:
我正在学习 Spring 博客 (https://spring.io/guides/tutorials/spring-security-and-angular-js/) 的教程。但是我从现有的 Spring 应用程序开始,因此我没有使用 Spring Boot 开始,我必须找到一种方法以 XML 和 Java 配置混合样式实现组件。
这是我的 CORS 过滤器:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {
public SimpleCORSFilter(){
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
//x-auth-token is a custom header for Spring Security AngularJS implementation
response.setHeader("Access-Control-Allow-Headers", "Options, authentication, authorization, X-Auth-Token, Origin, X-Requested-With, Content-Type, Accept, XSRF-TOKEN");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
System.out.println("OPTIONS request from AngularJS");
response.setStatus(HttpServletResponse.SC_OK);
}
chain.doFilter(req, response);
}
@Override
public void destroy() {}
这是我的 CsrfHeaderFilter.java,几乎是从教程中复制的:
@Component
public class CsrfHeaderFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("CsrfHeaderFilter vvv");
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if(csrf != null){
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
System.out.println("CSRFToken Value: "+token);
if(cookie == null || token != null && !token.equals(cookie.getValue()) ){
cookie = new Cookie("XSRF-TOKEN", token); //use XSRF-TOKEN as the response header for CSRF token
cookie.setPath("/");
response.addCookie(cookie);
}
}
System.out.println("CsrfHeaderFilter ^^^");
filterChain.doFilter(request, response);
}
并且CsrfHeaderFilter配置在Spring的CsrfFilter之后:
<sec:custom-filter ref="csrfHeaderFilter" after="CSRF_FILTER" />
<sec:csrf token-repository-ref="csrfTokenRepository"/>
csrfTokenRepository:
@Configuration
public class CustomCsrfTokenRepository {
@Bean
public CsrfTokenRepository csrfTokenRepository(){
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
repository.setParameterName("_csrf");
return repository;
}
}
我有自己的带有自定义登录 URL 的身份验证过滤器:
public class CustomerAuthenticationTokenProcessingFilter extends AbstractAuthenticationProcessingFilter{
private static final String SECURITY_TOKEN_HEADER = "x-auth-token";
private static final String AUTHORIZATION_HEADER = "authorization";
@Autowired
private CustomerTokenAuthenticationService tokenAuthenticationService;
@Autowired
CustomerAuthenticationService customerAuthenticationService;
@Autowired
@Qualifier("customerAuthenticationManager")
AuthenticationManager authenticationManager;
protected CustomerAuthenticationTokenProcessingFilter(){
super("/company/login");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
Authentication authentication = null;
//Authentication Logics...
...
return authentication;
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
}
}
当然还有一个自定义的注销网址:
<sec:logout invalidate-session="true" delete-cookies="JSESSION,XSRF-TOKEN"
logout-url="/resource/logout" success-handler-ref="customerLogoutSuccessHandler"/>
customerLogoutSuccessHandler:
public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler{
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
if (authentication != null && authentication.getDetails() != null) {
try {
SecurityContextHolder.clearContext();
System.out.println("User Successfully Logout");
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
e.printStackTrace();
e = null;
}
}
}
}
AngularJS 代码非常简单。最初我显示登录表单,只是向 Spring 的 /company/login 端点发出 HTTP POST 请求,但不知何故我的 AngularJS 应用程序没有获得它需要的 CSRF 令牌......所以我在启动时添加了一个 HTTP GET 请求来请求来自一个开放的 URL (access="permitAll()") 以便为我即将到来的请求获取 XSRF-TOKEN。登录和注销工作正常,直到我再次登录。错误是“POST http://localhost:8080/company/login403 (Forbidden)”和“Invalid CSRF Token was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'”
我认为我的浏览器中的 cookie 有问题。当我在我的 CORS 过滤器中输出 cookie 数据时,我可以看到与传递给 Spring 之前相同的 XSRF-TOKEN,并且 Spring 的 CsrfFilter 拒绝了进一步的请求,因为 CSRF 令牌不正确。
FilterChainProxy DEBUG - /company/login at position 3 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
CsrfFilter DEBUG - Invalid CSRF token found for http://localhost:8080/company/login
也许我在注销部分缺少一些功能?如果我的请求从未通过 Spring 的 CsrfFilter,我该如何更新 XSRF-TOKEN?
如有必要,请随时向我询问更多详细信息。我真的很想解决这个问题,因为我已经花了很多时间试图找出问题所在:(
【问题讨论】:
标签: java angularjs spring spring-security