使用Spring Cloud Gateway登录后,Spring Clould oauth2重定向到“ /”

时间:2020-08-01 13:00:19

标签: spring spring-boot spring-security spring-cloud spring-cloud-gateway

我是春季oauth2的新手。通过文档检查,我在Spring Cloud alibaba nacos环境中为oauth2做了一个简单的功能。

在设计中,我想为oauth请求从网关到auth微服务添加重定向。然后使用表单登录名对auth微服务进行授权,并授权范围,然后重定向到oauth url中设置的重定向url。

直接提出对微服务进行身份验证的请求时,它会很好地工作。但是,如果向网关提出请求,则登录后它将重定向到“ /”方向,并引发404错误。

通过调查 SavedRequestAwareAuthenticationSuccessHandler ,我发现请求中包含的会话为空。此外,我检查了 HttpSessionRequestCache ,当保存请求时,它也会获得空会话。由于请求未保存,因此登录后无法重定向到原始URL,也无法重定向到默认URL“ /”。

但是我不知道为什么与请求相关的会话为空。我也尝试做一个演示项目,如下所示:

    @RequestMapping(value = "hello",method = RequestMethod.GET)
    public RedirectView hello(HttpServletRequest request){
        System.out.println("Hello:"+request.getSession().getId());
        return new RedirectView("thanks");
    }

    @RequestMapping(value = "thanks",method = RequestMethod.GET)
    public ResponseEntity<String> thanks(HttpServletRequest request){
        System.out.println("Thanks:"+request.getSession().getId());
        return new ResponseEntity("aaa",HttpStatus.OK);
    }

使用网关时,打印的会话ID不同。但是没有网关,它们是相同的。以下是我的网关设置:

server:
  port: 8080

spring:
  application:
    name: flower-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: order-routes
          uri: lb://flower-order
          predicates:
            - Path=/order/**
        - id: core-routes
          uri: lb://flower-core
          predicates:
            - Path=/**
        - id: auth-routes
          uri: lb://flower-auth
          predicates:
            - Path=/oauth/**

所以我想这是由Spring Cloud Gateway引起的。但是我不知道如何解决它。请给我一些信息。谢谢。


新更新:

当我将身份验证网关更改为

- id: auth-routes
          uri: https://127.0.0.1:8082
          predicates:
            - Path=/oauth/**

它通过正常行为。这是否意味着它是由负载平衡引起的。但是由于我只有一个正在运行的实体,因此不太确定。这是否意味着它应该使用分布式会话管理,例如spring session?与实际生产环境中一样,auth服务不会只有一个实体。

1 个答案:

答案 0 :(得分:0)

您可以创建身份验证成功处理程序。例如,有一个名为 RedirectServerAuthenticationSuccessHandler (ServerAuthenticationSuccessHandler的实现之一)。

如果请求缓存具有重定向uri,它将重定向原始url(因此,登录前首先请求的url)。如果没有,它将重定向到您指定的URL。

示例配置

@EnableWebFluxSecurity
public class GatewaySecurityConfiguration {

    @Value("${redirect.url}")
    private String redirectFrontendAddress;

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
                ...
                .oauth2Login()
                .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler(redirectFrontendAddress))
                
                ...
    }
}
相关问题