英文:
Mono does not emit value when subscribed
问题
我试图在响应式Spring应用程序中使用Spring Security验证身份。在控制器中,我无法读取Mono<Authentication>的内容。当我订阅时,它不会发出任何值。我在控制器中有以下代码:
@Controller
public class TestConroller {
 public void test(){
   Mono<Authentication> monoAuth = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
   monoAuth.subscribe(authentication -> validate(authentication));
 }
 private void validate(Authentication authentication){
   System.out.println(authentication.getPrincipal().getName());
 }
}
validate方法从未被调用。
英文:
I am trying to validate authentication in reactive spring application with Spring Security. I could not read content from Mono<Authentication> in the controller. It is not emitting any values when I subscribed. I have the following code in the controller:
@Controller
public class TestConroller {
 public void test(){
   Mono<Authentication> monoAuth=ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
   monoAuth.subscribe(authentication->validate(authentication) 
 }
 private void validate(Authentication authentication){
   System.out.println(authentication.getPrincipal().getName());
 }
}
The validate method is never called
答案1
得分: 1
尽管 "在订阅之前什么都不会发生", 但你不需要显式调用 subscribe。如果返回 Mono<T>,WebFlux会在后台进行订阅。你只需要构建一个组合不同的响应式操作符的流。
public Mono<String> test() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -> validate(ctx.getAuthentication()));
    }
    
    private String validate(Authentication authentication){
        String name = ((Principal) authentication.getPrincipal()).getName();
        // 验证
        return name;
    }
英文:
Although "nothing happens until you subscribe", you don't need to call subscribe explicitly. WebFlux will subscribe behind the scene if you return Mono<T>. You just need to build a flow combining different reactive operators.
public Mono<String> test() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -> validate(ctx.getAuthentication()));
    }
    
    private String validate(Authentication authentication){
        String name = ((Principal) authentication.getPrincipal()).getName();
        // validate
        return name;
    }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论