使用ReactiveSecurityContextHolder手动设置身份验证

jgzswidk  于 2022-12-13  发布在  Spring
关注(0)|答案(2)|浏览(348)

我正在尝试使用Spring Web Flux设置Spring Security。我不知道如何手动设置SecurityContextReactiveSecurityContextHolder。您有什么资源或提示吗?以我编写的这个过滤器为例,它读取JWT标记,需要手动设置身份验证:

@Slf4j
public class JwtTokenAuthenticationFilter implements WebFilter {

    private final JwtAuthenticationConfig config;

    private final JwtParser jwtParser = Jwts.parser();

    public JwtTokenAuthenticationFilter(JwtAuthenticationConfig config) {
        this.config = config;
        jwtParser.setSigningKey(config.getSecret().getBytes());
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        String token = exchange.getRequest().getHeaders().getFirst(config.getHeader());
        if (token != null && token.startsWith(config.getPrefix() + " ")) {
            token = token.replace(config.getPrefix() + " ", "");
            try {
                Claims claims = jwtParser.parseClaimsJws(token).getBody();
                String username = claims.getSubject();
                @SuppressWarnings("unchecked")
                List<String> authorities = claims.get("authorities", List.class);
                if (username != null) {
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null,
                            authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));

                    // TODO set authentication into ReactiveSecurityContextHolder 
                }
            } catch (Exception ex) {
                log.warn(ex.toString(), ex);
                ReactiveSecurityContextHolder.clearContext();
            }
        }
        return chain.filter(exchange);
    }
}
icomxhvb

icomxhvb1#

我设法通过调用以下内容更新SecurityContext:

return chain.filter(exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(auth));

如果我错了,或者有更好的方法来管理它,请纠正我。

gz5pxeao

gz5pxeao2#

我搜索了很多关于这个问题,并得到这个东西的工作。你可以尝试设置上下文,同时传递过滤器链如下。

return chain.filter(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));

相关问题