我正在开发Spring Cloud Gateway,它在Spring Security Filter Chain的帮助下使用OAuth2进行身份验证。目前我在OAuth2的登录页面上遇到了一个错误,因为我需要解决一些未知的授权请求未找到错误。我已经找到了一种方法,通过添加自定义位置头并在异常发生时将用户路由到该位置。目前我面临着挑战,在Spring安全过滤器链之前进行控制。下面是我使用的代码块:
@Bean
@Order(1)
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity serverHttpSecurity)
throws Exception {
ServerRequestCache requestCache = NoOpServerRequestCache.getInstance();
WebFilter webFilter = new CustomWebFilter();
serverHttpSecurity
//.addFilterAt(webFilter, SecurityWebFiltersOrder.FIRST)
.cors().and().headers()
.frameOptions().disable()
.and().requestCache().requestCache(requestCache)
.and().csrf().disable()
.authorizeExchange().pathMatchers("/**").authenticated()
.and().oauth2Login()
.and().oauth2Client()
.and().oauth2ResourceServer().jwt();
return serverHttpSecurity.build();
}
字符串
在这里,我尝试在身份验证之前添加过滤器,但它阻止了请求,我得到了一个空响应,它不会将我路由到登录页面。
.addFilterAt(webFilter, SecurityWebFiltersOrder.FIRST)
型
下面是我的自定义WebFilter,我已经添加了代码来添加位置标题。
public class CustomWebFilter implements WebFilter {
@Autowired
URIconfig uRIconfig;
final Logger logger = LoggerFactory.getLogger(CustomWebFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
URI location = exchange.getRequest().getURI();
uRIconfig.setLocation(location);
logger.info("Custom Pre Filter executed");
return chain.filter(exchange);
}
}
型
在请求重定向到OAuth2登录页面之前,有人可以帮助我添加头或cookie吗?或者我如何使用过滤器?
任何帮助是非常感谢.提前感谢!
2条答案
按热度按时间jtjikinw1#
我通过将spring安全过滤器链的顺序更改为5并在我的自定义过滤器中添加@Order(Ordered.HIGHEST_PRECEDENCE)来解决这个问题。现在我的过滤器在我的keycloak登录页面之前调用,我可以添加我的自定义实现。下面是我所做的更改:
Application.yml
字符串
CustomWebFilter.java
型
nr9pn0ug2#
OP的回答是正确的,它可以工作。然而,我不喜欢改变spring的默认值(就我对spring的理解而言)。
字符串
所以我选择了另一条路线,这也会起作用。再次感谢OP展示了一条如何做到这一点的道路。
型
在SecurityConfig类中,您可以执行此操作。
型