Angular2请求中的自定义标头



我有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 始终为空。我已经尝试从Google-Chrome浏览器中从REST-CLIEN扩展程序发送请求,并且它可以正常运行(我只添加到的标题中>一个标头:SocialMedia-Auth-auth-Token:Asdfghhj(。我能够在我的authtokenfilter中收到asdfghhj。

Google Chrome网络:没有SocialMedia-auth-token参数

你能帮我吗?我不知道此代码怎么了。

解决方案

谢谢 chaoluo 。在Corsfilter中,我更改了

chain.doFilter

to

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

它有效。谢谢。

当请求是 CORS滤波器中的请求是前飞行请求(Option方法(时,您应该立即使用这些标头返回200。更多信息请参见(不那么简单的请求(。

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

相关内容

  • 没有找到相关文章

最新更新