Java Spring MVC:安全配置requireSecure()必须永久重定向301
.和().requireChannel().anyRequest().requiresCure()) 我用上面的配置强制HTTPS,问题是它暂时重定向用户(302)。我希望http状态代码应该是301(永久重定向)Java Spring MVC:安全配置requireSecure()必须永久重定向301,java,spring,spring-mvc,redirect,spring-security,Java,Spring,Spring Mvc,Redirect,Spring Security,.和().requireChannel().anyRequest().requiresCure()) 我用上面的配置强制HTTPS,问题是它暂时重定向用户(302)。我希望http状态代码应该是301(永久重定向) 这是对我有用的 首先定义使用状态301的RedirectStrategy,并围绕状态301构建SecureChannelProcessor final RedirectStrategy redirectStrategy = new RedirectStrategy() { @
这是对我有用的 首先定义使用状态301的
RedirectStrategy
,并围绕状态301构建SecureChannelProcessor
final RedirectStrategy redirectStrategy = new RedirectStrategy() {
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response,
String url) throws IOException {
response.addHeader("Location", response.encodeRedirectURL(url));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.flushBuffer();
}
};
final RetryWithHttpsEntryPoint entryPoint = new RetryWithHttpsEntryPoint();
entryPoint.setRedirectStrategy(redirectStrategy);
final SecureChannelProcessor secureChannelProcessor = new SecureChannelProcessor();
secureChannelProcessor.setEntryPoint(entryPoint);
然后使用此SecureChannelProcessor
配置:
http.requiresChannel().anyRequest().requiresSecure().channelProcessors(Arrays.asList(secureChannelProcessor)).and()
... other configuration
这是如何工作的
.requireChannel().anyRequest().requirescure()
添加了SecureChannelProcessor
实例,该实例具有RetryWithHttpsEntryPoint
,而该实例又具有重定向策略。所以要改变重定向策略,我们必须构建入口点和处理器对象
请注意,当我们进行重定向时,需要response.flushBuffer()
,因为除非提交响应,否则Spring将继续处理请求flushBuffer()
确保它是
还请注意,PortMapper
用于在重定向时更改端口。如果不定义它,将使用默认值,将80更改为443,将8080更改为8443。如果端口不同,您可能还需要配置PortMapper
,并将其注入RetryWithHttpsEntryPoint
实例
对于unsecurechannelprocessor
来说,一切都是相似的。这需要任何maven依赖项吗?`org.springframework.beans.factory.BeanCreationException:创建名为“org.springframework.security.web.access.channel”的bean时出错。ChannelProcessingFilter@41921212“:调用init方法失败;嵌套异常为java.lang.IllegalArgumentException:不受支持的配置属性:[需要不安全的通道]`请将完整堆栈跟踪添加到问题中您不是偶然添加了一个unsecureChannelProcessor
到requiresSecure()
?完整堆栈跟踪如何?这对我来说非常有效,谢谢分享,遗憾的是,很难将Spring设置为301而不是302。
http.requiresChannel().anyRequest().requiresSecure().channelProcessors(Arrays.asList(secureChannelProcessor)).and()
... other configuration