Java Spring MVC:安全配置requireSecure()必须永久重定向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() { @

.和().requireChannel().anyRequest().requiresCure())

我用上面的配置强制HTTPS,问题是它暂时重定向用户(302)。我希望http状态代码应该是301(永久重定向)


这是对我有用的

首先定义使用状态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