【问题标题】:SpringBoot webflux authenticate using query parameter使用查询参数的 Spring Boot webflux 身份验证
【发布时间】:2020-02-11 00:40:00
【问题描述】:

在Springboot webflux中,我可以使用这段代码得到当前的原理

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

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

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

【问题讨论】:

  • 扩展处理Authorization 标头的过滤器以检查查询参数。

标签: spring-boot authentication spring-webflux


【解决方案1】:

您可以设置自己的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 相对)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2018-02-27
    • 2017-04-12
    • 2019-03-18
    • 2015-08-09
    • 2018-11-17
    • 1970-01-01
    • 2018-05-01
    相关资源
    最近更新 更多