fen*_*x22 3 java spring heroku
我在heroku上部署了Spring Boot Java应用程序。我想确保只能通过https访问我的注册端点。到目前为止,我知道,heroku使用负载平衡器将每个https连接重定向到带有特殊标头(X-forwarded-porto)的http。我在用
compile("org.springframework.boot:spring-boot-starter-security")
Run Code Online (Sandbox Code Playgroud)
用于加密工具(哈希密码)。我已经将“ security.basic.enable”属性设置为false(实际上不知道在这种情况下是否重要。)。
已尝试设置以下设置:
tomcat:
remote_ip_header: x-forwarded-for
protocol_header: x-forwarded-proto
Run Code Online (Sandbox Code Playgroud)
在我的application.yml中
问题是,我如何才能强制仅通过https链接使用端点?对于http,它可能会返回404之类的内容。我正在使用gradle,它很难找到使用它的任何参考。尝试了一些在google中找到的东西,但是没有用(或者我不知道如何正确实现它们...)。我仍然可以使用邮递员通过http访问我的端点。现在看起来像这样:
@Controller
@RequestMapping("/users")
public class AccountController {
@Autowired
private AccountRepository accountDao;
@RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Resource<Account>> createAccount(@RequestBody @Valid Account account) { ... }
Run Code Online (Sandbox Code Playgroud)
实际上,我已经在此仓库https://github.com/fenrirx22/springmvc-https-enforcer中找到了一个解决方案(终于)。
创建了2个课程:
@Configuration
public class ApiConfig {
@Bean
public Filter httpsEnforcerFilter(){
return new HttpsEnforcer();
}
}
Run Code Online (Sandbox Code Playgroud)
和:
public class HttpsEnforcer implements Filter {
private FilterConfig filterConfig;
public static final String X_FORWARDED_PROTO = "x-forwarded-proto";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (request.getHeader(X_FORWARDED_PROTO) != null) {
if (request.getHeader(X_FORWARDED_PROTO).indexOf("https") != 0) {
response.sendRedirect("https://" + request.getServerName() + request.getPathInfo());
return;
}
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
// nothing
}
}
Run Code Online (Sandbox Code Playgroud)
奇迹般有效。
归档时间: |
|
查看次数: |
938 次 |
最近记录: |