angular2请求中的自定义标头

时间:2017-05-01 11:05:33

标签: angular spring-boot spring-security null header

我有2个申请:

localhost:4200 <- angular2 app
localhost:8080 <- spring boot app with security

在我的a2 auth.service中,我尝试像这样登录:

const customHeaders = new Headers({
        'socialmedia-auth-token': 'ABCDEFGJ'
});
//...
      return this.http.post(loginpoint, JSON.stringify(worker), new RequestOptions({ headers: customHeaders, withCredentials: true }))
        .toPromise()
        .then(result => console.log(result))
        .catch(this.errorHandler);

我的springboot cors过滤器:

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

private Logger log = Logger.getLogger(CORSFilter.class);

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {


    log.info("####### CORS FILTER ###########");

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Expose-Headers", "socialmedia-auth-token");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, socialmedia-auth-token");

    chain.doFilter(req, res);
}

我的AuthTokenFilter:

public class AuthTokenFilter extends UsernamePasswordAuthenticationFilter {

private static final String TOKEN_HEADER = "socialmedia-auth-token";

private Logger log = Logger.getLogger(AuthTokenFilter.class);

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(TOKEN_HEADER);

    log.info("####### AuthTokenFilter: " + authToken + " ###########");

问题是 authToken 始终为空。 我尝试从go-chrome浏览器的rest-client扩展程序发送请求并且它可以正常工作(我只是添加标头来自单个标头:socialmedia-auth-token:asdfghhj)。我能够在我的AuthTokenFilter中收到asdfghhj。

Google Chrome网络:There is no socialmedia-auth-token parameter

你能帮帮我吗?我不知道这段代码有什么问题。

解决方案

谢谢 chaoluo 。在CORSFilter中我改变了

chain.doFilter

if(!request.getMethod().equals("OPTIONS")) {
        chain.doFilter(request, response);
}

它有效。谢谢。

1 个答案:

答案 0 :(得分:2)

200过滤器中的请求是预检请求(Option方法)时,您应立即返回CORS这些标头。更多信息请参阅http://eewang.github.io/blog/2013/03/12/how-and-when-to-use-single-table-inheritance-in-rails/(不那么简单的请求)。

if (request.getHeader("Access-Control-Allow-Origin") != null && "OPTIONS".equals(request.getMethod())) {
    // CORS "pre-flight" request
    return ;
}