SpringBoot Webflux使用查询参数进行身份验证

时间:2019-10-14 11:34:46

标签: spring-boot authentication spring-webflux

在Springboot webflux中,我可以使用此代码了解当前原理

Object principal = ReactiveSecurityContextHolder.getContext().getAuthentication().getPrincipal();

用户通过身份验证。但是我有一种情况,其中JWT令牌将作为查询参数而不是authorization头发送,我知道如何将令牌转换为Authentication对象

我如何将那个Authentication对象注入当前的ReactiveSecurityContextHolder

1 个答案:

答案 0 :(得分:0)

您可以设置自己的Authentication并从查询参数中获取令牌,如下所示:

@Component
public class CustomAuthentication implements ServerSecurityContextRepository {

    private static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private ReactiveAuthenticationManager authenticationManager;

    @Override
    public Mono<Void> save(ServerWebExchange serverWebExchange, SecurityContext securityContext) {
        throw new UnsupportedOperationException("No support");
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        String authJwt = request.getQueryParams().getFirst("Authentication");

        if (authJwt != null && authJwt.startsWith(TOKEN_PREFIX)) {
            authJwt = authJwt.replace(TOKEN_PREFIX, "");
            Authentication authentication =
                new UsernamePasswordAuthenticationToken(getPrincipalFromJwt(authJwt), authJwt);
            return this.authenticationManager.authenticate(authentication).map((authentication1 -> new SecurityContextImpl(authentication)));
        }
        return Mono.empty();
    }

    private String getPrincipalFromJwt(String authJwt) {
        return  authJwt;
    }
}

这是一个简单的代码块,演示如何实现目标。您可以改进getPrincipalFromJwt()方法以返回要设置为主体的其他对象。或者,您可以完全使用Authentication的另一种实现(与本示例中的UsernamePasswordAuthenticationToken相对)。