在Spring Web中,我将@PreAuthorize与SpEl一起使用以检查当前用户的权限。像这样:
@Component
public class CustomSecurity {
public boolean checkPermission(){
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
CurrentAccount currentAccount = (CurrentAccount)authentication.getPrincipal();
return currentAccount.getUsername().equals("admin");
}
}
在RestController中:
@PreAuthorize("@customSecurity.checkPermission()")
@GetMapping("/")
public Object getWidgetValues() {
return "Hello admin";
}
现在,我尝试使用WebFlux。 编写了reactCheckPermission。
public boolean checkPermission2() {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getPrincipal)
.map(o -> (CurrentAccount) o)
.map(currentAccount -> currentAccount.getUsername().equals("admin"))
.block();
}
但是它抛出IllegalStateException(“ block()/ blockFirst()/ blockLast()被阻止,线程并行不支持
将布尔值更改为Mono,但@PreAuthroze仅需要布尔值,而不需要Mono。
如何在WebFlux中使用@PreAuthorize对吗?
答案 0 :(得分:0)
我找到了一个解决方案。
@PreAuthorize("@customSecurity.checkPermission(#account)")
@GetMapping("/")
public Object getWidgetValues(@AuthenticationPrincipal(expression = "account") Account account) {
return "Hello admin";
}
ReactiveUserDetailsService中使用CurrentAccount的地方
public class CurrentAccount extends User {
private Account account;
public CurrentAccount(Account account) {
super(account.getLogin(), account.getPassword(), true, true,
true, !account.isLocked(),
AuthorityUtils.createAuthorityList(account.getRole().name()));
this.account = account;
}