spring 如何自动使用 https 进行请求?
Posted
技术标签:
【中文标题】spring 如何自动使用 https 进行请求?【英文标题】:How spring use https for request automatically? 【发布时间】:2015-10-31 19:18:05 【问题描述】:我正在使用 spring 3.2.8.RELEASE 和 tomcat 7.0.55 实现一个 Web 应用程序。
我需要 spring 将 https 用于某些请求,例如“/login”,但不是用于所有请求。
应用程序在 http 和 https 上完美运行,但我想过滤一些请求以自动在 https 上运行。
如何配置 spring 来做到这一点?
【问题讨论】:
【参考方案1】:您可以通过在每个拦截 URL 上添加 requires-channel- attribute 来配置需要 https。
例如:
<security:intercept-url pattern="/your_url" access="your_role" requires-channel="https"/>
编辑:
web.xml 中必需的 spring 安全映射:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我希望这会奏效。
【讨论】:
谢谢,我应该将哪个配置添加到 web.xml? web.xml中是否需要定义securityChainFIlter? 是的,这是必要的。我正在更新我的答案。 如果它解决了您的问题,请接受并投票这个答案,以便它也可以帮助其他人。 感谢@Babak Behzadi,我为你投了 1 票 :)【参考方案2】:如果您的应用程序同时支持 HTTP 和 HTTPS,并且您要求特定的 URL 只能通过 HTTPS 访问,那么使用 requires-channel 属性直接支持:
<http>
<intercept-url pattern="/secure/**" access="ROLE_USER" requires-channel="https"/>
<intercept-url pattern="/**" access="ROLE_USER" requires-channel="any"/>
...
</http>
【讨论】:
谢谢,我应该将哪个配置添加到 web.xml?是否需要在web.xml中定义securityChainFIlter? 请参阅:docs.spring.io/spring-security/site/docs/3.1.x/reference/… 感谢您的关注!【参考方案3】:Spring 对其所有内部 URL 映射使用控制器 servlet。为避免使用此控制器,请更改 Web.xml 文件中的 URL 映射。
在这里寻找类似的答案:Spring MVC URL pattern mappping in web.xml?
或在此处查找有关配置“前端控制器”的 spring 文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html。这也将让您很好地了解其工作原理和组合方式。
祝你好运,如果您需要更多帮助,请告诉我!
顺便说一句:我想我会把它扔进去。在这里你可以看到映射到/example/...
。你也可以在spring config文件中设置这种东西,但都遵循相同的原则。
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
【讨论】:
以上是关于spring 如何自动使用 https 进行请求?的主要内容,如果未能解决你的问题,请参考以下文章
使用 spring SecurityWebFilterChain 如何禁用/阻止除少数已知路径外的所有非 https 请求
如何在负载均衡器后面强制 Spring Security 发出 https 重定向请求
如何使用 spring 记录 RestTemplate 请求和响应?
Spring Webflux:如何使用不同的线程进行请求和响应