在spring boot RESTful 应用程序中,如何防止登录用户再次登录?

In spring boot RESTful application, how to prevent logged in user to log in again?

我使用 springboot 创建了一个简单的 restful 应用程序。它只有两个 api,登录和注册。用户登录后,它 returns 一个 jwt。这是我的配置

protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling()
                    .authenticationEntryPoint(unauthorizedHandler)
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/api/**").permitAll()
                    .antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
                    .antMatchers(HttpMethod.GET, "/api/users/checkUsernameAvailability", "/api/users/checkEmailAvailability").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

问题是,我注意到经过身份验证的用户可以再次调用 /login api,并返回一个新的 jwt 令牌。

有没有办法为未经身份验证的用户配置一些 api?喜欢.antMatchers(HttpMethod.POST, "/api/auth/**").unauthenticatedOnly()

如果没有配置,我想到的解决方法是向用户 table 添加一个 is_authenticated 列,并且只对 is_authentiacted = false 的用户进行身份验证。有什么好方法吗?

如果你想在 server-side 上验证 jwt 令牌的出现,我认为令牌必须保存在 Redis 等存储中,并通过过滤器检查它(将其设置在 Spring 安全)。

一个可能的简单解决方案是使用 Spring 会话,如果您想通过 Spring 安全本身来控制它(无需额外工作)。

Spring Session类似于HttpSession,但是由Redis、Mongo等支持,因此可以使用Spring Security中提供的session并发策略来确保只有一个用户认证是有效的。您必须在后端切换到 Stateful

就我个人而言,我在几个项目中使用了Spring session(secures RESTful API),我认为它很好。这里是 an example of using Spring session (Reactive stack)(but I have not configured the session control rule). Here is a microservice example(Servlet stack).