【问题标题】:Vaadin 14 and Push: Accessing Spring SecurityContext and Authentication outside the request threadVaadin 14 和 Push:在请求线程之外访问 Spring SecurityContext 和 Authentication
【发布时间】:2021-05-02 11:50:15
【问题描述】:

我遇到了这个人遇到的同样问题: https://vaadin.com/forum/thread/3383122/17008971

从服务器接收状态时,我尝试通过客户端上的推送(使用 ui.access)刷新内容。该内容需要当前委托人的信息。

final SecurityContext securityContext = SecurityContextHolder.getContext();
final Authentication authentication = securityContext.getAuthentication();

这个

authentication 

正在返回 null。

他使用 Vaadin Shared Security 解决了这个问题,但我找不到任何名为 Vaadin Shared Sec 的存储库或库。有没有其他方法可以解决这个问题?

【问题讨论】:

  • 持有人通常只根据请求填写。如果将主体和异步任务所需的任何其他内容传递给任务,通常会更容易推理。
  • 你在调用 SecurityContextHolder.getContext();从后台线程。如果是这样,那么它应该返回 null 。您需要重构您的视图逻辑,以便它处理与用户相关的信息,而无需您从后台线程直接调用。

标签: spring security vaadin push


【解决方案1】:

为什么不直接在视图构造函数中获取 auth 详细信息并将它们设置为类范围,或者使用 bean 来执行此操作并设置其值?例如

@Route("some-view")
public class SomeView extends VerticalLayout {
    Authentication authentication;
    private void doHeavyStuff() {
        try {
            Thread.sleep(1500);
        } catch (InterruptedException ex) {
            // ignore
        }
    }
    public SomeView() {
        authentication = SecurityContextHolder.getContext().getAuthentication();
        final Button button = new Button("Click me", e -> {
            Notification.show("CLICKED");
            getUI().ifPresent(ui -> {
                ExecutorService executor = Executors.newSingleThreadExecutor();
                executor.submit(() -> {
                    doHeavyStuff();
                    ui.access(() -> {
                        Notification.show("Calculation done");
                    });
                });
            });
        });
        add(button);
        // simple link to the logout endpoint provided by Spring Security
        Element logoutLink = ElementFactory.createAnchor("logout", "Logout");
        getElement().appendChild(logoutLink);
    }
}

如果您想了解更多信息,我在本教程中基于此答案(也对其进行了测试): https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security/speciale

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2021-05-27
    • 2018-10-01
    • 2011-11-02
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多