我在我的程序中使用webflux和oauth2安全(keycloack as UAA server
),我想从oauth2 jwt中提取一些信息,并且我做得很好。但我需要在过滤器中获取一些信息。当我使用我的旧方法时,它在filter (WebFilter
)中不起作用。有没有办法解析token并从中获取信息?我的方法正确吗?或者我应该使用springSecurityFilterChain
而不是WebFilter来提取它?我想用url中的accountId检查令牌中的accountId,客户端使用过滤器发送。
我听到的是我提取accountId的代码,它在WebFilter中不起作用,但当我使用它的服务或控制器时,它就能起作用
public class SecurityFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).map(Principal::getName).filter((accountId) -> accountId.equals(clientAccountId)
.switchIfEmpty(Mono.error(new SystemException("401 ERROR")));;
return webFilterChain.filter(serverWebExchange);
}
Hear是我提取accountId的第二种方法:
public class SecurityFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
serverWebExchange.getPrincipal().map(Principal::getName).filter((accountId) -> accountId.equals(clientAccountId). .switchIfEmpty(Mono.error(new SystemException("401 ERROR")));;
return webFilterChain.filter(serverWebExchange);
}
我的安全配置是:
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.pathMatchers("/api/**").authenticated()
// .pathMatchers("/**").permitAll()
.anyExchange().authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new HttpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST))
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(grantedAuthoritiesExtractor());
return http.build();
}
我想我应该有另一个SecurityWebFilterChain
方法来为我做这件事。
发布于 2021-05-17 00:11:04
你正在寻找这样的smth
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
var clientAccountId = "clientId";
return exchange.getPrincipal()
.map(Principal::getName)
.flatMap((accountId) -> {
if (accountId.equals(clientAccountId) && exchange.getRequest().getPath().value().equals("/my/api")) {
return Mono.just(accountId);
}
return Mono.error(new IllegalArgumentException("401 ERROR"));
})
.flatMap(tokenJwt -> chain.filter(exchange))
.onErrorResume(r -> {
exchange.getResponse().setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
return exchange.getResponse().setComplete();
});
}
注意:当你使用reactive的时候,直到你或者spring订阅了它,它才会被执行。
https://stackoverflow.com/questions/67511688
复制