问题描述
在我的应用程序中,我使用以下解决方案向会话标头添加了安全标志:https://stackoverflow.com/a/16616225
我遇到了以下问题:
- 它在我部署到远程机器时工作。我可以连接到它,没问题!
- 它在我的本地不起作用,因为 http://localhost:7001 不再有效,我需要使用 HTTPS 连接(https://localhost:7001)。
问题是我能否启用或知道我正在本地部署并且我将使用 HTTP 连接而不是 HTTPS?比如写一个switch case,本地部署的时候不用HTTPS,部署到远程服务器的时候用HTTPS?
public class SecurityFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws servletexception {
}
@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,servletexception {
// wrap the response
HttpServletResponse response = new SecureCookieSetter((HttpServletResponse)res);
// touch the session,so that it is added to the response header
((HttpServletRequest)req).getSession();
response.setHeader("Set-Cookie","JSESSIONID=" + ((HttpServletRequest)req).getSession().getId() + ";Path=/");
HttpServletResponse response = (HttpServletResponse)res;
chain.doFilter(req,response);
}
@Override
public void destroy() {
}
}
<filter>
<filter-name>SecurityFilter</filter-name>
<filter-class>package.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
解决方法
您可以依靠 request.getScheme() 来了解它是 HTTP 还是 HTTPS。
但是,更好的解决方案是让您的本地服务器采用 HTTPS 连接。这可以通过向本地域添加自签名证书来轻松完成。您可以转到此 site 并生成自签名证书。然后可以将其放置在 Web 服务器或应用程序服务器上。