我是 Spring oauth2 的新人。通过文档检查,我在spring cloud alibaba nacos环境下对oauth2做了一个简单的功能。
在设计中,我想添加从网关到auth微服务的oauth请求的重定向。然后auth微服务通过表单登录进行授权,并授权范围,然后重定向到oauth url中设置的重定向url。
直接向身份验证微服务提出请求时,效果很好。但如果向网关发出请求,登录后,它将重定向到“/”方向并引发 404 错误。
通过调查SavedRequestAwareAuthenticationSuccessHandler,我发现请求中包含的会话为空。此外,我检查了HttpSessionRequestCache,它在保存请求时也得到了空会话。由于请求未保存,因此登录后无法重定向到原始网址并重定向到默认网址“/”。
但是不知道为什么请求相关的session是空的。我还尝试做一个演示项目,如下所示:
@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 会话?在实际生产环境中,auth 服务不会只有一个实体。
你是如何解决这个问题的?