无法在Chrome中看到来自服务器的Cookie响应

时间:2018-09-26 14:18:05

标签: google-chrome setcookie

Why does Chrome ignore Set-Cookie header?相同,但是我提供了我正在使用的框架的代码。

这是我的原始文本,我将其作为上面的答案(不是真正的答案,但确实提供了所请求的一些代码,但是sysop告诉我,因为这不是答案,因此我应该再次提出该问题。所以这里是...

我对此坚持了太久了。一切在Postman,Firefox等中都可以正常工作,但是Chrome顽固地拒绝接受Set-Cookie标头。

我的服务器(Spring Zuul代理)

@Bean
public CorsFilter corsFilter() {
    logger.info("=================> corsFilter intialization.");

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
   config.setAllowedOrigins(Collections.singletonList("http://neptune.local.mydoman.org:4200"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    config.setAllowedMethods(Arrays.stream(HttpMethod.values()).map(HttpMethod::name).collect(Collectors.toList()));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

很开放,但并不担心,一旦它起作用,我就会收紧。

我想将refresh_token存储在仅HTTP的cookie中,为了测试是否设置了cookie,我放宽了它。

我的PostFilter,用于在发送响应之前设置Cookie。

@Component

公共类CustomPostZuulFilter扩展了ZuulFilter {

private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ObjectMapper mapper = new ObjectMapper();
// Default is 30 days
@Value("${oauth.http.cookie.maxAge:2592000}")
private int cookieMaxAge;

@Override
public Object run() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    logger.info("PostZuulFilter called: " + ctx.getRequest().getRequestURI());

    final String requestURI = ctx.getRequest().getRequestURI();
    final String requestMethod = ctx.getRequest().getMethod();

    try {
        final InputStream is = ctx.getResponseDataStream();
        String responseBody = IOUtils.toString(is, "UTF-8");
        if (responseBody.contains("refresh_token")) {
            final Map<String, Object> responseMap =
                    mapper.readValue(responseBody,
                            new TypeReference<Map<String, Object>>() {
            });
            final String refreshToken = responseMap.get("refresh_token").toString();
            logger.info("Decoding refresh token from response.");
            decodeJwtToken(refreshToken);
            responseMap.remove("refresh_token");
            responseBody = mapper.writeValueAsString(responseMap);

            final Cookie cookie = new Cookie("refreshToken", refreshToken);

            // cookie.setHttpOnly(true);
            // cookie.setSecure(true);
            cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token");
            cookie.setMaxAge(cookieMaxAge); // 30 days

            ctx.getResponse().addCookie(cookie);
            logger.info("PostZuulFilter refresh token now stored in HTTP ONLY cookie:");
            logger.info(refreshToken);

        }
        if (requestURI.contains("oauth/token") && requestMethod.equals("DELETE")) {
            final Cookie cookie = new Cookie("refreshToken", "");
            cookie.setMaxAge(0);
            cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token");
            ctx.getResponse().addCookie(cookie);
        }
        ctx.setResponseBody(responseBody);

    } catch (final IOException e) {
        logger.error("Error occured in zuul post filter", e);
    }
    return null;
}

@Override
public boolean shouldFilter() {
    return true;
}

@Override
public int filterOrder() {
    return 10;
}

@Override
public String filterType() {
    return "post";
}


private String decodeJwtToken(String jwtToken) {
    logger.info("------------ Decode JWT ------------");
    String[] split_string = jwtToken.split("\\.");
    String base64EncodedHeader = split_string[0];
    String base64EncodedBody = split_string[1];
    String base64EncodedSignature = split_string[2];

    logger.info("~~~~~~~~~ JWT Header ~~~~~~~");
    Base64 base64Url = new Base64(true);
    String header = new String(base64Url.decode(base64EncodedHeader));
    System.out.println("JWT Header : " + header);


    logger.info("~~~~~~~~~ JWT Body ~~~~~~~");
    String body = new String(base64Url.decode(base64EncodedBody));
    logger.info("JWT Body : "+body);

    return "";
}

}

最后是我的Angular Service请求。

public obtainAccessToken(params: URLSearchParams): Observable<string> {                                                             
 console.log('obtainAccessToken');                                                                                              

 console.log('Getting access token from ', appConfig.tokenServerUrl);                                                           
 console.log('Using params: ');                                                                                                 
 console.dir(params.toString());                                                                                                


// Now fire the request                                                                                                         
this.http.post(                                                                                                                 
    'http://neptune.local.domain.org:8084/oauth/token',                                                                         
    params.toString(), {                                                                                                        
        headers: new HttpHeaders({                                                                                              
           'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}),                                                
           withCredentials: true,                                                                                               
           observe: 'response'                                                                                                  
 })                                                                                                                             
  .pipe(map((response) => {                                                                                                                                                                             
    // Try and find the Set-Cookie header! (Good luck)                                                                          
    console.log(response);                                                                                                      
    console.log('response headers',response.headers.keys());                                                                    
    const respKeySet = response.headers.keys();                                                                                 
    for( let x = 0; x < respKeySet.length; x++ ) {                                                                              
     console.log('Key: %s, Value: %s',                                                                                          
       respKeySet[x],                                                                                                           
       response.headers.get(respKeySet[x]));                                                                                    
    }                                                                      

}));
  }

我的服务器和客户端在同一工作站上运行,我已经设置了FQD名称。

因此客户端正在运行。 http://neptune.local.mydomain.org:4200

我的服务器正在运行。 http://neptune.local.mydomain.org:8084

我从没在Chrome中获得Set-Cookie?

有人知道为什么吗? 嗯,帮助。...

1 个答案:

答案 0 :(得分:0)

我的问题中的代码实际上正在工作。 Angular服务请求从不显示Set-Cookie标头。

但是......

在进行了无数次更改并停止/重新启动后再次检查时,我触发了另一个请求,但仍然没有任何内容输出到控制台。然后,我检查了Google Chrome DevTools的“网络”标签中是否有我发送的请求,请记住,它在那里。 enter image description here 耶!!!!!!