skylvsme
skylvsme

Reputation: 35

Vaadin 14 and Push: Accessing Spring SecurityContext and Authentication outside the request thread

I had the same problem this guy had: https://vaadin.com/forum/thread/3383122/17008971

When receiving a status from the server I try to refresh content via push (using ui.access) on the client. That content needs the current principal's information.

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

this

authentication 

is returning null.

He solved this problem using Vaadin Shared Security, but I can't find any repo or library called Vaadin Shared Sec. Are there any other ways to solve the problem?

Upvotes: 1

Views: 514

Answers (1)

J. Diogo Oliveira
J. Diogo Oliveira

Reputation: 141

Why not just get the auth details in the view constructor and make them class-scoped, or have a bean to do that and set its values ? E.g.

@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);
    }
}

I based this answer (tested it as well) in this tutorial, if you want to learn more about it: https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security/speciale

Upvotes: 3

Related Questions