java cookie安全,Java Web应用程序中会话cookie的安全标志

本文介绍了如何在Java Web应用程序中针对HTTPS请求设置安全会话Cookie,同时确保HTTP请求不受影响。由于负载均衡器的SSL卸载,标准方法无法区分HTTP和HTTPS。为解决此问题,作者实现了一个自定义阀门(Valve),该阀门检测'Front-End-Https'头来设置请求的安全标志。这样,只有HTTPS请求的Cookie才会带有secure标志。
摘要由CSDN通过智能技术生成

I'm trying to add the secure flag to the session cookie in a Java web application. The standard approach however presents a problem, in that when secure is true, even http requests will get the secure flag. This means that the web server does not pick up on the cookie on subsiquent requests and we end up with a new session. It works fine on HTTPS. The application in question has multiple entry points, from different domains and some internal entry points as well with an internal IP. Some are HTTPS, some are HTTP. I need to be able to get the secure flag to be set for HTTPS requests, but HTTP ones. This needs to be done by domain though, rather than by protocol because, all the HTTPS requests go through a load balancer that does SSL offloading, so by the request arrives at the web server (which is jboss 7.1.1) it is HTTP, even though the client would see it as HTTPS and would need the secure flag in the session cookie. Here is the config I tried:

60

true

true

COOKIE

I have had to set secure to false however, as otherwise none of the HTTP entry points work.

解决方案

This can be acheived with a custom valve, that provides a hook into the creation of the request object. The secure flag is set in a cookie automatically (without the web.xml setting) if the servlet request is secure. Setting the secure flag in the request can be done from the valve.

The load balancer adds on the header Front-End-Https which the valve detects and sets secure accordingly.

Here is the valve class:

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.catalina.Valve;

import org.apache.catalina.connector.Request;

import org.apache.catalina.connector.Response;

import org.apache.catalina.valves.ValveBase;

public class SecureRequestModifyingValve extends ValveBase

{

private static final String LB_HTTPS_HEADER = "Front-End-Https";

@Override

public void invoke(final Request request, final Response response) throws IOException, ServletException

{

final String httpsHeader = request.getHeader(LB_HTTPS_HEADER);

request.setSecure(httpsHeader != null && httpsHeader.equalsIgnoreCase("on"));

getNext().invoke(request, response);

}

}

I have got jboss to use it by adding the following to jboss-web.xml within the WAR.

com.lifecycle.framework.valve.SecureRequestModifyingValve

I imagine other containers let you do something similar as well.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值