spring-security 如何使用Spring WebFlux获取“身份验证”对象?

beq87vna  于 2022-11-11  发布在  Spring
关注(0)|答案(2)|浏览(230)

使用SpringMVC和Spring Security,我可以实现一个控制器,如下所示(用Java):

@RestController
@RequestMapping("/auth")
class AuthController {
    private final AuthService authService;

    AuthController(AuthService authService) {
        this.authService = authService;
    }

    @GetMapping("/roles")
    Collection<String> findRoles(Authentication authentication) {
        final Object principal = authentication.getPrincipal();
        ...;
    }
}

但是,在使用Spring WebFlux 和Spring Security(包括React性部分)时,我基本上如何将org.springframework.security.core.Authentication的对象注入到 handler 类(或 service 类)中?

x6yk4ghg

x6yk4ghg1#

有很多例子:https://github.com/spring-projects/spring-security
下面这个例子说明了如何在rest控制器的情况下获取Principal:
https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebflux/src/main/java/sample/HelloUserController.java#L35
这一个展示了如何在webflux的情况下获取Principal:
https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebfluxfn/src/main/java/sample/HelloUserController.java#L37

e5nqia27

e5nqia272#

//@AuthenticationPrincipal Mono<UserLogin> principal
//@AuthenticationPrincipal Mono<Authentication> principal

@GetMapping("/me")
public Mono<Map<String, Object>> current(@AuthenticationPrincipal Mono<Principal> principal) {
    return principal
            .map(user ->
                    Map.of(
                            "name", user.getName(),
                            "roles", AuthorityUtils.authorityListToSet(((Authentication) user)
                                    .getAuthorities())
                    )
            );
}

您也可以用途:

ReactiveSecurityContextHolder.getContext()
            .map(m->m.getAuthentication())
            .map(m->m.getPrincipal());

相关问题