在Springboot webflux中,我可以使用此代码了解当前原理
Object principal = ReactiveSecurityContextHolder.getContext().getAuthentication().getPrincipal();
用户通过身份验证。但是我有一种情况,其中JWT
令牌将作为查询参数而不是authorization
头发送,我知道如何将令牌转换为Authentication
对象
我如何将那个Authentication
对象注入当前的ReactiveSecurityContextHolder
答案 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
相对)。