gpt4 book ai didi

java - 英雄库 : spring boot acces to endpoints with https only

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:01 26 4
gpt4 key购买 nike

我在 heroku 上部署了一个 Spring Boot java 应用程序。我想确保我的注册端点只能通过 https 访问。到目前为止我已经知道,heroku 使用负载均衡器将每个 https 连接重定向到带有特殊 header (X-forwarded-porto) 的 http。我正在使用

compile("org.springframework.boot:spring-boot-starter-security")

用于加密工具(散列密码)。我已将“security.basic.enable”属性设置为 false(实际上不知道在那种情况下是否重要。)。

已尝试设置这些设置:

tomcat:
remote_ip_header: x-forwarded-for
protocol_header: x-forwarded-proto

在我的 application.yml 中

问题是,我如何才能真正强制端点只能通过 https 链接使用?对于 http,它可能会返回 404 或其他内容。我正在使用 gradle,很难找到任何使用它的引用。尝试了一些在谷歌中发现的东西,但没有用(或者我不知道如何正确实现它们......)。我仍然可以使用 postman 通过 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) { ... }

最佳答案

实际上我在这个 repo 中找到了一个解决方案(终于)https://github.com/fenrirx22/springmvc-https-enforcer .

创建了 2 个类:

@Configuration
public class ApiConfig {
@Bean
public Filter httpsEnforcerFilter(){
return new HttpsEnforcer();
}
}

和:

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
}
}

像魅力一样工作。

关于java - 英雄库 : spring boot acces to endpoints with https only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com