gpt4 book ai didi

java - Spring Security 更改重定向 URL 以使用 HTTPS 而不是 HTTP

转载 作者:搜寻专家 更新时间:2023-11-01 03:46:48 25 4
gpt4 key购买 nike

我正在使用受 Spring Security SSO 登录保护的 Spring 微服务(使用 Cloudfoundry UAA)。

部署在云上的微服务可通过 HTTPS URL 访问。由于 HTTPS URL 属于 ELB(负载均衡器/Web 服务器),因此来自 ELB 的微服务实际请求来自 HTTP。因此,当将用户重定向到登录页面时,Spring 在 302 Location header 中生成 HTTP URL 而不是 HTTPS URL。

流程如下

Browser
->(https://mymicroservice.com) Unauthenticated request (Load balancer)
->(http://internal_lan_ip:someport) Microservice
-> 302 Location http://mymicroservice.com/login
-> Browser http://mymicroservice.com/login (failed)

In short it goes from HTTPS -> HTTP -> 302 HTTP (failed as ELB doesn't serve on HTTP)

以下是我尝试过的

x-forwarded-proto

由于负载均衡器也没有将 x-forwarded-proto 正确填充为 HTTPS,而是给我 HTTP,我不能使用 Spring 的支持。

需要 channel HTTPS

它也不起作用,因为它会导致来自 Spring 的无限重定向,因为 Spring 从未收到来自 ELB 的 HTTPS 请求,尽管已正确生成 HTTPS 重定向 URL。

拦截器/过滤器

使用 ServletFilter 检查响应 header Location,如果存在,将 http:// 替换为 https://.

坦率地说,最后一个选项是我的最终选项,因为我无法控制 ELB 配置。

现在的问题是我无法在 spring 重定向到 /login URL 后拦截响应,而后者又应该重定向到 SSO URL。

我尝试了多种拦截器组合(postHandle、afterCompletion),使用 Spring security 将其注入(inject)过滤器链中的不同位置,最后将过滤器顺序设置为最低。这些都不会在重定向后拦截未经身份验证的请求。

@Component
@Order(Ordered.LOWEST_PRECEDENCE)
class RedirectUrlProtocolUpdaterFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String locationHeader = response.getHeader("Location");
System.out.println("############ inside interceptor");

for(String name: response.getHeaderNames()) {
System.out.println(name + " : " + response.getHeader(name));
}

if(locationHeader != null && locationHeader.startsWith("http://")) {
System.out.println("###################### setting location header");

locationHeader = locationHeader.replaceAll("http://", "https://");
response.setHeader("Location", locationHeader);
}

filterChain.doFilter(request, response);

}
}

我如何在过滤器/拦截器中正确拦截 Spring Security 的 /login 重定向并更新 Location header 以包含正确的协议(protocol)?

感谢任何提示。

最佳答案

如果您想更新 Location header 信息,您可以尝试使用 HttpResponseInterceptor。

这是来自 google HttpResponseInterceptor 的使用示例: https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/http/HttpResponseInterceptor

其他选项来自 Apache: https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/class-use/HttpResponseInterceptor.html

关于java - Spring Security 更改重定向 URL 以使用 HTTPS 而不是 HTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119553/

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