Restore session from cookie (JWT)

This project is taken as a basis https://vaadin.com/start/latest - Full Stack App

So, I have sush steps

  1. My JWT token is saved in cookies
  2. SecurityConfig
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .csrf().disable()
        .formLogin().disable()
        .httpBasic().disable()
        // Register our CustomRequestCache, that saves unauthorized access attempts, so
        // the user is redirected after login.
        .requestCache().requestCache(new CustomRequestCache())
        .and()
        .authorizeRequests()
        // Allow all flow internal requests.
        .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
        .mvcMatchers(PAGE_ROOT, PAGE_ROOT + PAGE_LOGIN_URL).permitAll()
        // Allow all requests by logged in users.
        .anyRequest().hasAnyAuthority(EnumUtils.getNames(RoleEnum.class));
  }

  /**
   * Allows access to static resources, bypassing Spring security.
   */
  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers(
        // Vaadin Flow static resources
        "/VAADIN/**",
        // the standard favicon URI
        "/favicon.ico",
        // the robots exclusion standard
        "/robots.txt",
        // web application manifest
        "/manifest.webmanifest",
        "/sw.js",
        "/offline-page.html",
        // icons and images
        "/icons/**",
        "/images/**",
        // (development mode) static resources
        "/frontend/**",
        // (development mode) webjars
        "/webjars/**",
        // (production mode) static resources
        "/frontend-es5/**",
        "/frontend-es6/**");
  }
}
  1. InitListener
@Slf4j
@Component
@RequiredArgsConstructor
public class InitListener implements VaadinServiceInitListener {

  private final AuthService authService;

  @Override
  public void serviceInit(ServiceInitEvent event) {
    final AtomicInteger sessionsCount = new AtomicInteger(0);
    final VaadinService vaadinService = event.getSource();
    vaadinService.addSessionInitListener(
        sessionInitEvent -> {
          log.info("New Vaadin session created. Current count is: {}", sessionsCount.incrementAndGet());
          authService.signInFromCookie(sessionInitEvent.getSession());
          log.info("restoreSession - FINISH");
        });
    vaadinService.addSessionDestroyListener(
        sessionDestroyEvent -> log.info("Vaadin session destroyed. Current count is {} ", sessionsCount.decrementAndGet()));

    event.getSource().addUIInitListener(uiEvent -> {
      UI ui = uiEvent.getUI();
      ui.add(new OfflineBanner());
      ui.addBeforeEnterListener(this::beforeEnter);
    });
  }

  /**
   * Reroutes the user if she is not authorized to access the view.
   *
   * @param event before navigation event with event details
   */
  private void beforeEnter(BeforeEnterEvent event) {
    log.info("beforeEnter - START");
    boolean accessGranted = SecurityUtils.isAccessGranted(event.getNavigationTarget());
    if (!accessGranted) {
      if (SecurityUtils.isUserLoggedIn()) {
        event.rerouteToError(AccessDeniedException.class);
      } else {
        event.rerouteTo(LoginView.class);
      }
    }
  }
}

So my questions

  1. Sometimes I see two VaadinSessions. Why two sessions can start?
  2. SpringSecurtiy fulfills faster than I take a token and get the current user. How can this problem be solved?
2020-03-08 10:31:26.918  INFO 28930 --- [nio-8080-exec-1]
 o.a.c.c.C.[Tomcat]
.[localhost]
.
[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-08 10:31:26.918  INFO 28930 --- [nio-8080-exec-1]
 o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-03-08 10:31:26.923  INFO 28930 --- [nio-8080-exec-1]
 o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2020-03-08 10:31:29.207  WARN 28930 --- [nio-8080-exec-2]
 c.v.f.s.DefaultDeploymentConfiguration   : 
====================================================================
Vaadin is running in DEBUG MODE.
In order to run your application in production mode and disable debug features, you should enable it by setting the servlet init parameter productionMode to true.
See https://vaadin.com/docs/v14/flow/production/tutorial-production-mode-basic.html for more information about the production mode.
====================================================================
2020-03-08 10:31:30.306  INFO 28930 --- [nio-8080-exec-2]
 c.vaadin.flow.spring.SpringInstantiator  : The number of beans implementing 'I18NProvider' is 0. Cannot use Spring beans for I18N, falling back to the default behavior
2020-03-08 10:31:30.306  INFO 28930 --- [nio-8080-exec-2]
 c.r.v.config.listener.InitListener   : New Vaadin session created. Current count is: 1
2020-03-08 10:31:30.307  INFO 28930 --- [nio-8080-exec-2]
 com.rednavis.vaadin.service.AuthService  : AccessCookies exists

On the first question. I found some information. So I’m not alone in this matter. But did not find a solution = (

  1. https://vaadin.com/forum/thread/17604535/com-vaadin-flow-server-vaadinserviceinitlistener
  2. https://github.com/vaadin/spring/issues/531
  3. https://github.com/vaadin/flow/issues/6454

But problems remain with the second question
For example user open http://localhost:8080/privateView
In class InitListener

public class InitListener implements VaadinServiceInitListener{}
  1. I get AccessToken from Cookie
  2. I send it to a third-party server to get the user
  3. Then set the user in SecurityContextHolder

But while actions 1-3
Spring Security checks that there is no authorized user does not allow me to this page. Redirect to LoginView